ogwasm.pas 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181
  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. { TWasmObjSymbolLinkingData }
  35. TWasmObjSymbolLinkingData = class
  36. public
  37. ImportModule: string;
  38. ImportName: string;
  39. FuncType: TWasmFuncType;
  40. ExeFunctionIndex: Integer;
  41. constructor Create;
  42. destructor Destroy;override;
  43. end;
  44. { TWasmObjSymbol }
  45. TWasmObjSymbol = class(TObjSymbol)
  46. FuncIndex: Integer;
  47. SymbolIndex: Integer;
  48. GlobalIndex: Integer;
  49. TagIndex: Integer;
  50. AliasOf: string;
  51. ExtraData: TWasmObjSymbolExtraData;
  52. LinkingData: TWasmObjSymbolLinkingData;
  53. constructor create(AList:TFPHashObjectList;const AName:string);override;
  54. destructor Destroy;override;
  55. function IsAlias: Boolean;
  56. end;
  57. { TWasmObjRelocation }
  58. TWasmObjRelocation = class(TObjRelocation)
  59. public
  60. TypeIndex: Integer;
  61. Addend: LongInt;
  62. constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
  63. end;
  64. { TWasmObjSymbolExtraData }
  65. TWasmObjSymbolExtraData = class(TFPHashObject)
  66. TypeIdx: Integer;
  67. ExceptionTagTypeIdx: Integer;
  68. ImportModule: string;
  69. ImportName: string;
  70. ExportName: string;
  71. GlobalType: TWasmBasicType;
  72. GlobalIsImmutable: Boolean;
  73. Locals: array of TWasmBasicType;
  74. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  75. procedure AddLocal(bastyp: TWasmBasicType);
  76. end;
  77. { TWasmObjSection }
  78. TWasmObjSection = class(TObjSection)
  79. public
  80. SegIdx: Integer;
  81. SegSymIdx: Integer;
  82. SegOfs: qword;
  83. FileSectionOfs: qword;
  84. MainFuncSymbol: TWasmObjSymbol;
  85. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  86. function IsCode: Boolean;
  87. function IsData: Boolean;
  88. function IsDebug: Boolean;
  89. end;
  90. { TWasmFuncTypeTable }
  91. TWasmFuncTypeTable = class
  92. private
  93. FFuncTypes: array of TWasmFuncType;
  94. function GetCount: Integer;
  95. function GetItem(Index: Integer): TWasmFuncType;
  96. public
  97. destructor Destroy; override;
  98. function AddOrGetFuncType(wft: TWasmFuncType): integer;
  99. property Count: Integer read GetCount;
  100. property Items[Index: Integer]: TWasmFuncType read GetItem; default;
  101. end;
  102. { TWasmObjData }
  103. TWasmObjData = class(TObjData)
  104. private
  105. FFuncTypes: TWasmFuncTypeTable;
  106. FObjSymbolsExtraDataList: TFPHashObjectList;
  107. FLastFuncName: string;
  108. function is_smart_section(atype:TAsmSectiontype):boolean;
  109. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  110. public
  111. constructor create(const n:string);override;
  112. destructor destroy; override;
  113. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  114. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  115. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  116. function globalref(asmsym:TAsmSymbol):TObjSymbol;
  117. function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
  118. procedure DeclareGlobalType(gt: tai_globaltype);
  119. procedure DeclareFuncType(ft: tai_functype);
  120. procedure DeclareTagType(tt: tai_tagtype);
  121. procedure DeclareExportName(en: tai_export_name);
  122. procedure DeclareImportModule(aim: tai_import_module);
  123. procedure DeclareImportName(ain: tai_import_name);
  124. procedure DeclareLocal(al: tai_local);
  125. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  126. property FuncTypes: TWasmFuncTypeTable read FFuncTypes;
  127. end;
  128. { TWasmObjOutput }
  129. TWasmObjOutput = class(tObjOutput)
  130. private
  131. FData: TWasmObjData;
  132. FWasmRelocationCodeTable: tdynamicarray;
  133. FWasmRelocationCodeTableEntriesCount: Integer;
  134. FWasmRelocationDataTable: tdynamicarray;
  135. FWasmRelocationDataTableEntriesCount: Integer;
  136. FWasmRelocationDebugFrameTable: tdynamicarray;
  137. FWasmRelocationDebugFrameTableEntriesCount: Integer;
  138. FWasmRelocationDebugInfoTable: tdynamicarray;
  139. FWasmRelocationDebugInfoTableEntriesCount: Integer;
  140. FWasmRelocationDebugLineTable: tdynamicarray;
  141. FWasmRelocationDebugLineTableEntriesCount: Integer;
  142. FWasmRelocationDebugAbbrevTable: tdynamicarray;
  143. FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
  144. FWasmRelocationDebugArangesTable: tdynamicarray;
  145. FWasmRelocationDebugArangesTableEntriesCount: Integer;
  146. FWasmRelocationDebugRangesTable: tdynamicarray;
  147. FWasmRelocationDebugRangesTableEntriesCount: Integer;
  148. FWasmRelocationDebugStrTable: tdynamicarray;
  149. FWasmRelocationDebugStrTableEntriesCount: Integer;
  150. FWasmSymbolTable: tdynamicarray;
  151. FWasmSymbolTableEntriesCount: Integer;
  152. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  153. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  154. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  155. procedure WriteWasmSection(wsid: TWasmSectionID);
  156. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  157. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  158. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  159. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  160. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  161. function IsExternalFunction(sym: TObjSymbol): Boolean;
  162. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  163. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  164. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  165. procedure WriteSymbolTable;
  166. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  167. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  168. procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  169. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  170. procedure DoRelocations;
  171. procedure WriteRelocations;
  172. function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  173. protected
  174. function writeData(Data:TObjData):boolean;override;
  175. public
  176. constructor create(AWriter:TObjectWriter);override;
  177. destructor destroy;override;
  178. end;
  179. { TWasmObjInput }
  180. TWasmObjInput = class(TObjInput)
  181. private
  182. FFuncTypes: array of TWasmFuncType;
  183. public
  184. constructor create;override;
  185. destructor Destroy;override;
  186. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  187. function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
  188. end;
  189. { TWasmExeOutput }
  190. TWasmExeOutput = class(TExeOutput)
  191. private
  192. FImports: TFPHashObjectList;
  193. FFuncTypes: TWasmFuncTypeTable;
  194. FFunctionImports: array of record
  195. ModName: ansistring;
  196. Name: ansistring;
  197. TypeIdx: uint32;
  198. end;
  199. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  200. protected
  201. function writeData:boolean;override;
  202. procedure DoRelocationFixup(objsec:TObjSection);override;
  203. public
  204. constructor create;override;
  205. destructor destroy;override;
  206. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  207. procedure AfterUnusedSectionRemoval;override;
  208. end;
  209. { TWasmAssembler }
  210. TWasmAssembler = class(tinternalassembler)
  211. constructor create(info: pasminfo; smart:boolean);override;
  212. end;
  213. implementation
  214. uses
  215. cutils,verbose,version,globals,ogmap;
  216. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  217. var
  218. b: byte;
  219. i: Integer;
  220. begin
  221. for i:=1 to 5 do
  222. begin
  223. b:=byte(v) and 127;
  224. v:=v shr 7;
  225. if i<>5 then
  226. b:=b or 128;
  227. d.write(b,1);
  228. end;
  229. end;
  230. procedure WriteUleb5(d: tobjsection; v: uint64);
  231. var
  232. b: byte;
  233. i: Integer;
  234. begin
  235. for i:=1 to 5 do
  236. begin
  237. b:=byte(v) and 127;
  238. v:=v shr 7;
  239. if i<>5 then
  240. b:=b or 128;
  241. d.write(b,1);
  242. end;
  243. end;
  244. procedure WriteSleb5(d: tdynamicarray; v: int64);
  245. var
  246. b: byte;
  247. i: Integer;
  248. begin
  249. for i:=1 to 5 do
  250. begin
  251. b:=byte(v) and 127;
  252. v:=SarInt64(v,7);
  253. if i<>5 then
  254. b:=b or 128;
  255. d.write(b,1);
  256. end;
  257. end;
  258. procedure WriteSleb5(d: tobjsection; v: int64);
  259. var
  260. b: byte;
  261. i: Integer;
  262. begin
  263. for i:=1 to 5 do
  264. begin
  265. b:=byte(v) and 127;
  266. v:=SarInt64(v,7);
  267. if i<>5 then
  268. b:=b or 128;
  269. d.write(b,1);
  270. end;
  271. end;
  272. procedure WriteUleb(d: tdynamicarray; v: uint64);
  273. var
  274. b: byte;
  275. begin
  276. repeat
  277. b:=byte(v) and 127;
  278. v:=v shr 7;
  279. if v<>0 then
  280. b:=b or 128;
  281. d.write(b,1);
  282. until v=0;
  283. end;
  284. procedure WriteUleb(w: TObjectWriter; v: uint64);
  285. var
  286. b: byte;
  287. begin
  288. repeat
  289. b:=byte(v) and 127;
  290. v:=v shr 7;
  291. if v<>0 then
  292. b:=b or 128;
  293. w.write(b,1);
  294. until v=0;
  295. end;
  296. procedure WriteSleb(d: tdynamicarray; v: int64);
  297. var
  298. b: byte;
  299. Done: Boolean=false;
  300. begin
  301. repeat
  302. b:=byte(v) and 127;
  303. v:=SarInt64(v,7);
  304. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  305. Done:=true
  306. else
  307. b:=b or 128;
  308. d.write(b,1);
  309. until Done;
  310. end;
  311. procedure WriteByte(d: tdynamicarray; b: byte);
  312. begin
  313. d.write(b,1);
  314. end;
  315. procedure WriteName(d: tdynamicarray; const s: string);
  316. begin
  317. WriteUleb(d,Length(s));
  318. d.writestr(s);
  319. end;
  320. function ReadUleb(d: tdynamicarray): uint64;
  321. var
  322. b: byte;
  323. shift:integer;
  324. begin
  325. b:=0;
  326. result:=0;
  327. shift:=0;
  328. repeat
  329. d.read(b,1);
  330. result:=result or (uint64(b and 127) shl shift);
  331. inc(shift,7);
  332. until (b and 128)=0;
  333. end;
  334. function ReadSleb(d: tdynamicarray): int64;
  335. var
  336. b: byte;
  337. shift:integer;
  338. begin
  339. b:=0;
  340. result:=0;
  341. shift:=0;
  342. repeat
  343. d.read(b,1);
  344. result:=result or (uint64(b and 127) shl shift);
  345. inc(shift,7);
  346. until (b and 128)=0;
  347. {$ifopt Q+}
  348. {$define overflowon}
  349. {$Q-}
  350. {$endif}
  351. {$ifopt R+}
  352. {$define rangeon}
  353. {$R-}
  354. {$endif}
  355. if (b and 64)<>0 then
  356. result:=result or (high(uint64) shl shift);
  357. end;
  358. {$ifdef overflowon}
  359. {$Q+}
  360. {$undef overflowon}
  361. {$endif}
  362. {$ifdef rangeon}
  363. {$R+}
  364. {$undef rangeon}
  365. {$endif}
  366. procedure AddSleb5(d: tdynamicarray; v: int64);
  367. var
  368. q: Int64;
  369. p: LongWord;
  370. begin
  371. p:=d.Pos;
  372. q:=ReadSleb(d);
  373. q:=q+v;
  374. d.seek(p);
  375. WriteSleb5(d,q);
  376. end;
  377. procedure AddUleb5(d: tdynamicarray; v: int64);
  378. var
  379. q: UInt64;
  380. p: LongWord;
  381. begin
  382. p:=d.Pos;
  383. q:=ReadUleb(d);
  384. q:=q+v;
  385. d.seek(p);
  386. WriteUleb5(d,q);
  387. end;
  388. procedure AddInt32(d: tdynamicarray; v: int32);
  389. var
  390. q: int32;
  391. p: LongWord;
  392. begin
  393. p:=d.Pos;
  394. d.read(q,4);
  395. {$ifdef FPC_BIG_ENDIAN}
  396. q:=SwapEndian(q);
  397. {$endif FPC_BIG_ENDIAN}
  398. q:=q+v;
  399. {$ifdef FPC_BIG_ENDIAN}
  400. q:=SwapEndian(q);
  401. {$endif FPC_BIG_ENDIAN}
  402. d.seek(p);
  403. d.write(q,4);
  404. end;
  405. {****************************************************************************
  406. TWasmObjSymbolLinkingData
  407. ****************************************************************************}
  408. constructor TWasmObjSymbolLinkingData.Create;
  409. begin
  410. ExeFunctionIndex:=-1;
  411. end;
  412. destructor TWasmObjSymbolLinkingData.Destroy;
  413. begin
  414. FuncType.Free;
  415. inherited Destroy;
  416. end;
  417. {****************************************************************************
  418. TWasmObjRelocation
  419. ****************************************************************************}
  420. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  421. begin
  422. DataOffset:=ADataOffset;
  423. Symbol:=nil;
  424. OrgSize:=0;
  425. Group:=nil;
  426. ObjSection:=nil;
  427. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  428. TypeIndex:=ATypeIndex;
  429. end;
  430. {****************************************************************************
  431. TWasmObjSymbol
  432. ****************************************************************************}
  433. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  434. begin
  435. inherited create(AList,AName);
  436. FuncIndex:=-1;
  437. SymbolIndex:=-1;
  438. GlobalIndex:=-1;
  439. TagIndex:=-1;
  440. AliasOf:='';
  441. ExtraData:=nil;
  442. LinkingData:=TWasmObjSymbolLinkingData.Create;
  443. end;
  444. destructor TWasmObjSymbol.Destroy;
  445. begin
  446. LinkingData.Free;
  447. inherited Destroy;
  448. end;
  449. function TWasmObjSymbol.IsAlias: Boolean;
  450. begin
  451. result:=AliasOf<>'';
  452. end;
  453. {****************************************************************************
  454. TWasmObjSymbolExtraData
  455. ****************************************************************************}
  456. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  457. begin
  458. inherited Create(HashObjectList,s);
  459. TypeIdx:=-1;
  460. ExceptionTagTypeIdx:=-1;
  461. end;
  462. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  463. begin
  464. SetLength(Locals,Length(Locals)+1);
  465. Locals[High(Locals)]:=bastyp;
  466. end;
  467. {****************************************************************************
  468. TWasmObjSection
  469. ****************************************************************************}
  470. constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  471. begin
  472. inherited create(AList, Aname, Aalign, Aoptions);
  473. SegIdx:=-1;
  474. SegSymIdx:=-1;
  475. MainFuncSymbol:=nil;
  476. end;
  477. function TWasmObjSection.IsCode: Boolean;
  478. const
  479. CodePrefix = '.text';
  480. begin
  481. result:=(Length(Name)>=Length(CodePrefix)) and
  482. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  483. end;
  484. function TWasmObjSection.IsData: Boolean;
  485. begin
  486. result:=not (IsCode or IsDebug);
  487. end;
  488. function TWasmObjSection.IsDebug: Boolean;
  489. const
  490. DebugPrefix = '.debug';
  491. begin
  492. result:=(Length(Name)>=Length(DebugPrefix)) and
  493. (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
  494. end;
  495. {****************************************************************************
  496. TWasmFuncTypeTable
  497. ****************************************************************************}
  498. function TWasmFuncTypeTable.GetCount: Integer;
  499. begin
  500. Result:=Length(FFuncTypes);
  501. end;
  502. function TWasmFuncTypeTable.GetItem(Index: Integer): TWasmFuncType;
  503. begin
  504. if (Index<Low(FFuncTypes)) or (Index>High(FFuncTypes)) then
  505. internalerror(2023123101);
  506. Result:=FFuncTypes[Index];
  507. end;
  508. destructor TWasmFuncTypeTable.Destroy;
  509. var
  510. i: Integer;
  511. begin
  512. for i:=low(FFuncTypes) to high(FFuncTypes) do
  513. begin
  514. FFuncTypes[i].free;
  515. FFuncTypes[i]:=nil;
  516. end;
  517. end;
  518. function TWasmFuncTypeTable.AddOrGetFuncType(wft: TWasmFuncType): integer;
  519. var
  520. i: Integer;
  521. begin
  522. for i:=low(FFuncTypes) to high(FFuncTypes) do
  523. if wft.Equals(FFuncTypes[i]) then
  524. exit(i);
  525. result:=Length(FFuncTypes);
  526. SetLength(FFuncTypes,result+1);
  527. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  528. end;
  529. {****************************************************************************
  530. TWasmObjData
  531. ****************************************************************************}
  532. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  533. begin
  534. { For bss we need to set some flags that are target dependent,
  535. it is easier to disable it for smartlinking. It doesn't take up
  536. filespace }
  537. result:=not(target_info.system in systems_darwin) and
  538. create_smartlink_sections and
  539. (atype<>sec_toc) and
  540. (atype<>sec_user) and
  541. { on embedded systems every byte counts, so smartlink bss too }
  542. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  543. end;
  544. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  545. const aname: string; aorder: TAsmSectionOrder): string;
  546. const
  547. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  548. '.text',
  549. '.data',
  550. { why doesn't .rodata work? (FK) }
  551. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  552. { vtables (and anything else containing relocations), otherwise those are }
  553. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  554. { vtable for a class called Window: }
  555. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  556. { TODO: .data.ro not yet working}
  557. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  558. '.rodata',
  559. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  560. '.data',
  561. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  562. '.rodata',
  563. '.bss',
  564. '.tbss',
  565. '.pdata',
  566. '', { stubs }
  567. '__DATA,__nl_symbol_ptr',
  568. '__DATA,__la_symbol_ptr',
  569. '__DATA,__mod_init_func',
  570. '__DATA,__mod_term_func',
  571. '.stab',
  572. '.stabstr',
  573. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  574. '.eh_frame',
  575. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  576. '.fpc',
  577. '.toc',
  578. '.init',
  579. '.fini',
  580. '.objc_class',
  581. '.objc_meta_class',
  582. '.objc_cat_cls_meth',
  583. '.objc_cat_inst_meth',
  584. '.objc_protocol',
  585. '.objc_string_object',
  586. '.objc_cls_meth',
  587. '.objc_inst_meth',
  588. '.objc_cls_refs',
  589. '.objc_message_refs',
  590. '.objc_symbols',
  591. '.objc_category',
  592. '.objc_class_vars',
  593. '.objc_instance_vars',
  594. '.objc_module_info',
  595. '.objc_class_names',
  596. '.objc_meth_var_types',
  597. '.objc_meth_var_names',
  598. '.objc_selector_strs',
  599. '.objc_protocol_ext',
  600. '.objc_class_ext',
  601. '.objc_property',
  602. '.objc_image_info',
  603. '.objc_cstring_object',
  604. '.objc_sel_fixup',
  605. '__DATA,__objc_data',
  606. '__DATA,__objc_const',
  607. '.objc_superrefs',
  608. '__DATA, __datacoal_nt,coalesced',
  609. '.objc_classlist',
  610. '.objc_nlclasslist',
  611. '.objc_catlist',
  612. '.obcj_nlcatlist',
  613. '.objc_protolist',
  614. '.stack',
  615. '.heap',
  616. '.gcc_except_table',
  617. '.ARM.attributes'
  618. );
  619. var
  620. sep : string[3];
  621. secname : string;
  622. begin
  623. secname:=secnames[atype];
  624. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  625. begin
  626. result:=secname+'.'+aname;
  627. exit;
  628. end;
  629. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  630. Thus, data which normally goes into .rodata and .rodata_norel sections must
  631. end up in .data section }
  632. if (atype in [sec_rodata,sec_rodata_norel]) and
  633. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  634. secname:='.data';
  635. { Windows correctly handles reallocations in readonly sections }
  636. if (atype=sec_rodata) and
  637. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  638. secname:='.rodata';
  639. { section type user gives the user full controll on the section name }
  640. if atype=sec_user then
  641. secname:=aname;
  642. if is_smart_section(atype) and (aname<>'') then
  643. begin
  644. case aorder of
  645. secorder_begin :
  646. sep:='.b_';
  647. secorder_end :
  648. sep:='.z_';
  649. else
  650. sep:='.n_';
  651. end;
  652. result:=secname+sep+aname
  653. end
  654. else
  655. result:=secname;
  656. end;
  657. constructor TWasmObjData.create(const n: string);
  658. begin
  659. inherited;
  660. CObjSection:=TWasmObjSection;
  661. CObjSymbol:=TWasmObjSymbol;
  662. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  663. FFuncTypes:=TWasmFuncTypeTable.Create;
  664. end;
  665. destructor TWasmObjData.destroy;
  666. var
  667. i: Integer;
  668. begin
  669. FObjSymbolsExtraDataList.Free;
  670. FFuncTypes.Free;
  671. inherited destroy;
  672. end;
  673. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  674. const aname: string; aorder: TAsmSectionOrder): string;
  675. begin
  676. if (atype=sec_fpc) or
  677. ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
  678. atype:=sec_data;
  679. Result:=sectionname_gas(atype, aname, aorder);
  680. end;
  681. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  682. p: TObjSymbol; Reloctype: TObjRelocationType);
  683. const
  684. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  685. var
  686. objreloc: TWasmObjRelocation;
  687. begin
  688. if CurrObjSec=nil then
  689. internalerror(200403072);
  690. { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
  691. todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
  692. if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
  693. Reloctype:=RELOC_ABSOLUTE;
  694. objreloc:=nil;
  695. case Reloctype of
  696. RELOC_FUNCTION_INDEX_LEB:
  697. begin
  698. if Data<>0 then
  699. internalerror(2021092502);
  700. if len<>5 then
  701. internalerror(2021092503);
  702. if not assigned(p) then
  703. internalerror(2021092504);
  704. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  705. CurrObjSec.ObjRelocations.Add(objreloc);
  706. writebytes(leb_zero,5);
  707. end;
  708. RELOC_MEMORY_ADDR_LEB,
  709. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  710. begin
  711. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  712. internalerror(2021092602);
  713. if len<>5 then
  714. internalerror(2021092503);
  715. if not assigned(p) then
  716. internalerror(2021092504);
  717. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  718. objreloc.Addend:=Data;
  719. CurrObjSec.ObjRelocations.Add(objreloc);
  720. if RelocType=RELOC_MEMORY_ADDR_LEB then
  721. WriteUleb5(CurrObjSec,Data)
  722. else
  723. WriteSleb5(CurrObjSec,Data);
  724. end;
  725. RELOC_ABSOLUTE:
  726. begin
  727. if len<>4 then
  728. internalerror(2021092607);
  729. if not assigned(p) then
  730. internalerror(2021092608);
  731. if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
  732. (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
  733. begin
  734. objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
  735. objreloc.Addend:=Data+p.Address;
  736. CurrObjSec.ObjRelocations.Add(objreloc);
  737. {inc(data,p.address);}
  738. data:=0;
  739. Data:=NtoLE(Data);
  740. writebytes(Data,4);
  741. end
  742. else
  743. begin
  744. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  745. objreloc.Addend:=Data;
  746. CurrObjSec.ObjRelocations.Add(objreloc);
  747. Data:=NtoLE(Data);
  748. writebytes(Data,4);
  749. end;
  750. end;
  751. RELOC_TYPE_INDEX_LEB:
  752. begin
  753. if len<>5 then
  754. internalerror(2021092612);
  755. if assigned(p) then
  756. internalerror(2021092613);
  757. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  758. CurrObjSec.ObjRelocations.Add(objreloc);
  759. WriteUleb5(CurrObjSec,Data);
  760. end;
  761. RELOC_GLOBAL_INDEX_LEB:
  762. begin
  763. if len<>5 then
  764. internalerror(2021092701);
  765. if Data<>0 then
  766. internalerror(2021092702);
  767. if not assigned(p) then
  768. internalerror(2021092703);
  769. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  770. CurrObjSec.ObjRelocations.Add(objreloc);
  771. WriteUleb5(CurrObjSec,0);
  772. end;
  773. RELOC_TAG_INDEX_LEB:
  774. begin
  775. if len<>5 then
  776. internalerror(2021092712);
  777. if Data<>0 then
  778. internalerror(2021092713);
  779. if not assigned(p) then
  780. internalerror(2021092714);
  781. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  782. CurrObjSec.ObjRelocations.Add(objreloc);
  783. WriteSleb5(CurrObjSec,0);
  784. end;
  785. else
  786. internalerror(2021092501);
  787. end;
  788. end;
  789. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  790. begin
  791. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  792. if not assigned(result) then
  793. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  794. end;
  795. function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
  796. begin
  797. if assigned(asmsym) then
  798. begin
  799. if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
  800. internalerror(2021092706);
  801. result:=symbolref(asmsym);
  802. result.typ:=asmsym.typ;
  803. end
  804. else
  805. result:=nil;
  806. end;
  807. function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
  808. begin
  809. if assigned(asmsym) then
  810. begin
  811. if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
  812. internalerror(2021092707);
  813. result:=symbolref(asmsym);
  814. result.typ:=AT_WASM_EXCEPTION_TAG;
  815. end
  816. else
  817. result:=nil;
  818. end;
  819. procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
  820. var
  821. ObjSymExtraData: TWasmObjSymbolExtraData;
  822. ObjSym: TObjSymbol;
  823. begin
  824. if not gt.is_external then
  825. begin
  826. ObjSym:=symboldefine(gt.sym);
  827. ObjSym.typ:=AT_WASM_GLOBAL;
  828. end;
  829. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
  830. ObjSymExtraData.GlobalType:=gt.gtype;
  831. ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
  832. end;
  833. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  834. var
  835. i: Integer;
  836. ObjSymExtraData: TWasmObjSymbolExtraData;
  837. begin
  838. FLastFuncName:=ft.funcname;
  839. i:=FFuncTypes.AddOrGetFuncType(ft.functype);
  840. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  841. ObjSymExtraData.TypeIdx:=i;
  842. end;
  843. procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
  844. var
  845. ObjSymExtraData: TWasmObjSymbolExtraData;
  846. ft: TWasmFuncType;
  847. i: Integer;
  848. begin
  849. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
  850. ft:=TWasmFuncType.Create([],tt.params);
  851. i:=FFuncTypes.AddOrGetFuncType(ft);
  852. ft.free;
  853. ObjSymExtraData.ExceptionTagTypeIdx:=i;
  854. end;
  855. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  856. var
  857. ObjSymExtraData: TWasmObjSymbolExtraData;
  858. begin
  859. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  860. ObjSymExtraData.ExportName:=en.extname;
  861. end;
  862. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  863. var
  864. ObjSymExtraData: TWasmObjSymbolExtraData;
  865. begin
  866. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  867. ObjSymExtraData.ImportModule:=aim.importmodule;
  868. end;
  869. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  870. var
  871. ObjSymExtraData: TWasmObjSymbolExtraData;
  872. begin
  873. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  874. ObjSymExtraData.ImportName:=ain.importname;
  875. end;
  876. procedure TWasmObjData.DeclareLocal(al: tai_local);
  877. var
  878. ObjSymExtraData: TWasmObjSymbolExtraData;
  879. begin
  880. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  881. ObjSymExtraData.AddLocal(al.bastyp);
  882. end;
  883. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  884. var
  885. valsym: TObjSymbol;
  886. aliassym: TWasmObjSymbol;
  887. begin
  888. valsym:=CreateSymbol(avalue);
  889. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  890. aliassym.AliasOf:=valsym.Name;
  891. end;
  892. {****************************************************************************
  893. TWasmObjOutput
  894. ****************************************************************************}
  895. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  896. var
  897. b: byte;
  898. begin
  899. b:=ord(wsid);
  900. Writer.write(b,1);
  901. WriteUleb(Writer,FWasmSections[wsid].size);
  902. Writer.writearray(FWasmSections[wsid]);
  903. end;
  904. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  905. var
  906. b: byte;
  907. begin
  908. b:=0;
  909. Writer.write(b,1);
  910. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  911. Writer.writearray(FWasmCustomSections[wcst]);
  912. end;
  913. procedure TWasmObjOutput.CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  914. var
  915. buf: array [0..4095] of byte;
  916. bs: Integer;
  917. begin
  918. while size>0 do
  919. begin
  920. if size<SizeOf(buf) then
  921. bs:=Integer(size)
  922. else
  923. bs:=SizeOf(buf);
  924. src.read(buf,bs);
  925. dest.write(buf,bs);
  926. dec(size,bs);
  927. end;
  928. end;
  929. procedure TWasmObjOutput.WriteZeros(dest: tdynamicarray; size: QWord);
  930. var
  931. buf : array[0..1023] of byte;
  932. bs: Integer;
  933. begin
  934. fillchar(buf,sizeof(buf),0);
  935. while size>0 do
  936. begin
  937. if size<SizeOf(buf) then
  938. bs:=Integer(size)
  939. else
  940. bs:=SizeOf(buf);
  941. dest.write(buf,bs);
  942. dec(size,bs);
  943. end;
  944. end;
  945. procedure TWasmObjOutput.WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  946. var
  947. i: Integer;
  948. begin
  949. WriteUleb(dest,Length(wrt));
  950. for i:=low(wrt) to high(wrt) do
  951. WriteWasmBasicType(dest,wrt[i]);
  952. end;
  953. procedure TWasmObjOutput.WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  954. begin
  955. WriteByte(dest,encode_wasm_basic_type(wbt));
  956. end;
  957. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  958. var
  959. ExtraData: TWasmObjSymbolExtraData;
  960. begin
  961. if sym.bind=AB_EXTERNAL then
  962. begin
  963. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  964. result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
  965. end
  966. else
  967. result:=false;
  968. end;
  969. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  970. var
  971. ExtraData: TWasmObjSymbolExtraData;
  972. begin
  973. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  974. begin
  975. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  976. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  977. end
  978. else
  979. result:=false;
  980. end;
  981. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  982. var
  983. i,
  984. rle_entries,
  985. cnt: Integer;
  986. lasttype: TWasmBasicType;
  987. begin
  988. if Length(ed.Locals)=0 then
  989. begin
  990. WriteUleb(dest,0);
  991. exit;
  992. end;
  993. rle_entries:=1;
  994. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  995. if ed.Locals[i]<>ed.Locals[i-1] then
  996. inc(rle_entries);
  997. WriteUleb(dest,rle_entries);
  998. lasttype:=ed.Locals[Low(ed.Locals)];
  999. cnt:=1;
  1000. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  1001. if ed.Locals[i]=ed.Locals[i-1] then
  1002. inc(cnt)
  1003. else
  1004. begin
  1005. WriteUleb(dest,cnt);
  1006. WriteWasmBasicType(dest,lasttype);
  1007. lasttype:=ed.Locals[i];
  1008. cnt:=1;
  1009. end;
  1010. WriteUleb(dest,cnt);
  1011. WriteWasmBasicType(dest,lasttype);
  1012. end;
  1013. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  1014. var
  1015. encoded_locals: tdynamicarray;
  1016. ObjSymExtraData: TWasmObjSymbolExtraData;
  1017. codelen: LongWord;
  1018. ObjSection: TWasmObjSection;
  1019. codeexprlen: QWord;
  1020. begin
  1021. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1022. ObjSection:=TWasmObjSection(objsym.objsection);
  1023. ObjSection.Data.seek(objsym.address);
  1024. codeexprlen:=objsym.size;
  1025. encoded_locals:=tdynamicarray.Create(64);
  1026. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  1027. codelen:=encoded_locals.size+codeexprlen+1;
  1028. WriteUleb(dest,codelen);
  1029. encoded_locals.seek(0);
  1030. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  1031. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  1032. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  1033. WriteByte(dest,$0B);
  1034. encoded_locals.Free;
  1035. end;
  1036. procedure TWasmObjOutput.WriteSymbolTable;
  1037. begin
  1038. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  1039. FWasmSymbolTable.seek(0);
  1040. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  1041. end;
  1042. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  1043. begin
  1044. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  1045. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  1046. FWasmRelocationCodeTable.seek(0);
  1047. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  1048. end;
  1049. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  1050. begin
  1051. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  1052. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  1053. FWasmRelocationDataTable.seek(0);
  1054. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  1055. end;
  1056. procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  1057. begin
  1058. if EntriesCount>0 then
  1059. begin
  1060. WriteUleb(FWasmCustomSections[cst],SectionIndex);
  1061. WriteUleb(FWasmCustomSections[cst],EntriesCount);
  1062. Table.seek(0);
  1063. CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
  1064. WriteWasmCustomSection(cst);
  1065. end;
  1066. end;
  1067. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  1068. begin
  1069. if FWasmLinkingSubsections[wlst].size>0 then
  1070. begin
  1071. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  1072. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1073. FWasmLinkingSubsections[wlst].seek(0);
  1074. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1075. end;
  1076. end;
  1077. procedure TWasmObjOutput.DoRelocations;
  1078. var
  1079. si, ri: Integer;
  1080. objsec: TWasmObjSection;
  1081. objrel: TWasmObjRelocation;
  1082. begin
  1083. for si:=0 to FData.ObjSectionList.Count-1 do
  1084. begin
  1085. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1086. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1087. begin
  1088. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1089. case objrel.typ of
  1090. RELOC_FUNCTION_INDEX_LEB:
  1091. begin
  1092. if not assigned(objrel.symbol) then
  1093. internalerror(2021092509);
  1094. objsec.Data.seek(objrel.DataOffset);
  1095. if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
  1096. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1097. else
  1098. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
  1099. end;
  1100. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1101. begin
  1102. if not assigned(objrel.symbol) then
  1103. internalerror(2021092605);
  1104. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1105. begin
  1106. objsec.Data.seek(objrel.DataOffset);
  1107. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1108. end;
  1109. end;
  1110. RELOC_MEMORY_ADDR_LEB:
  1111. begin
  1112. if not assigned(objrel.symbol) then
  1113. internalerror(2021092606);
  1114. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1115. internalerror(2021092628);
  1116. if objrel.symbol.bind<>AB_EXTERNAL then
  1117. begin
  1118. objsec.Data.seek(objrel.DataOffset);
  1119. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1120. end;
  1121. end;
  1122. RELOC_ABSOLUTE:
  1123. begin
  1124. if assigned(objrel.ObjSection) then
  1125. begin
  1126. { todo: should we do something here? }
  1127. //Writeln('todo: section relocation');
  1128. end
  1129. else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1130. begin
  1131. objsec.Data.seek(objrel.DataOffset);
  1132. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1133. end;
  1134. end;
  1135. RELOC_TYPE_INDEX_LEB:
  1136. ;
  1137. RELOC_GLOBAL_INDEX_LEB:
  1138. begin
  1139. if not assigned(objrel.symbol) then
  1140. internalerror(2021092509);
  1141. objsec.Data.seek(objrel.DataOffset);
  1142. if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
  1143. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1144. else
  1145. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
  1146. end;
  1147. RELOC_TAG_INDEX_LEB:
  1148. begin
  1149. if not assigned(objrel.symbol) then
  1150. internalerror(2021092716);
  1151. objsec.Data.seek(objrel.DataOffset);
  1152. if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
  1153. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1154. else
  1155. WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
  1156. end;
  1157. else
  1158. internalerror(2021092510);
  1159. end;
  1160. end;
  1161. end;
  1162. end;
  1163. procedure TWasmObjOutput.WriteRelocations;
  1164. var
  1165. si, ri: Integer;
  1166. objsec: TWasmObjSection;
  1167. objrel: TWasmObjRelocation;
  1168. relout: tdynamicarray;
  1169. relcount: PInteger;
  1170. FuncSym: TWasmObjSymbol;
  1171. begin
  1172. for si:=0 to FData.ObjSectionList.Count-1 do
  1173. begin
  1174. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1175. if objsec.IsCode then
  1176. begin
  1177. relout:=FWasmRelocationCodeTable;
  1178. relcount:=@FWasmRelocationCodeTableEntriesCount;
  1179. end
  1180. else if objsec.IsData then
  1181. begin
  1182. relout:=FWasmRelocationDataTable;
  1183. relcount:=@FWasmRelocationDataTableEntriesCount;
  1184. end
  1185. else if objsec.IsDebug then
  1186. begin
  1187. case objsec.Name of
  1188. '.debug_frame':
  1189. begin
  1190. relout:=FWasmRelocationDebugFrameTable;
  1191. relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
  1192. end;
  1193. '.debug_info':
  1194. begin
  1195. relout:=FWasmRelocationDebugInfoTable;
  1196. relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
  1197. end;
  1198. '.debug_line':
  1199. begin
  1200. relout:=FWasmRelocationDebugLineTable;
  1201. relcount:=@FWasmRelocationDebugLineTableEntriesCount;
  1202. end;
  1203. '.debug_abbrev':
  1204. begin
  1205. relout:=FWasmRelocationDebugAbbrevTable;
  1206. relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
  1207. end;
  1208. '.debug_aranges':
  1209. begin
  1210. relout:=FWasmRelocationDebugArangesTable;
  1211. relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
  1212. end;
  1213. '.debug_ranges':
  1214. begin
  1215. relout:=FWasmRelocationDebugRangesTable;
  1216. relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
  1217. end;
  1218. '.debug_str':
  1219. begin
  1220. relout:=FWasmRelocationDebugStrTable;
  1221. relcount:=@FWasmRelocationDebugStrTableEntriesCount;
  1222. end;
  1223. else
  1224. internalerror(2022071601);
  1225. end;
  1226. end
  1227. else
  1228. continue;
  1229. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1230. begin
  1231. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1232. case objrel.typ of
  1233. RELOC_FUNCTION_INDEX_LEB:
  1234. begin
  1235. if not assigned(objrel.symbol) then
  1236. internalerror(2021092508);
  1237. Inc(relcount^);
  1238. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  1239. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1240. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1241. end;
  1242. RELOC_MEMORY_ADDR_LEB:
  1243. begin
  1244. if not assigned(objrel.symbol) then
  1245. internalerror(2021092603);
  1246. Inc(relcount^);
  1247. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1248. internalerror(2021092628);
  1249. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  1250. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1251. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1252. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1253. end;
  1254. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1255. begin
  1256. if not assigned(objrel.symbol) then
  1257. internalerror(2021092604);
  1258. Inc(relcount^);
  1259. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1260. begin
  1261. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  1262. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1263. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1264. end
  1265. else
  1266. begin
  1267. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  1268. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1269. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1270. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1271. end;
  1272. end;
  1273. RELOC_ABSOLUTE:
  1274. begin
  1275. // todo: figure this out, why do these exist?
  1276. //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
  1277. // Writeln('!!! ', objrel.symbol.name);
  1278. if assigned(objrel.objsection) then
  1279. begin
  1280. Inc(relcount^);
  1281. WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
  1282. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1283. if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
  1284. message1(asmw_e_illegal_unset_index,objrel.objsection.name)
  1285. else
  1286. WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
  1287. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1288. end
  1289. else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
  1290. begin
  1291. Inc(relcount^);
  1292. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  1293. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1294. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1295. end
  1296. else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
  1297. begin
  1298. Inc(relcount^);
  1299. WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
  1300. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1301. FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
  1302. if FuncSym.SymbolIndex<0 then
  1303. message1(asmw_e_illegal_unset_index,FuncSym.Name)
  1304. else
  1305. WriteUleb(relout,FuncSym.SymbolIndex);
  1306. WriteSleb(relout,objrel.Addend+objrel.symbol.address); { addend to add to the address }
  1307. end
  1308. else
  1309. begin
  1310. Inc(relcount^);
  1311. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1312. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1313. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1314. begin
  1315. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1316. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1317. end
  1318. else
  1319. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1320. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1321. end;
  1322. end;
  1323. RELOC_TYPE_INDEX_LEB:
  1324. begin
  1325. Inc(relcount^);
  1326. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1327. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1328. WriteUleb(relout,objrel.TypeIndex);
  1329. end;
  1330. RELOC_GLOBAL_INDEX_LEB:
  1331. begin
  1332. if not assigned(objrel.symbol) then
  1333. internalerror(2021092704);
  1334. Inc(relcount^);
  1335. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1336. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1337. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1338. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1339. else
  1340. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1341. end;
  1342. RELOC_TAG_INDEX_LEB:
  1343. begin
  1344. if not assigned(objrel.symbol) then
  1345. internalerror(2021092717);
  1346. Inc(relcount^);
  1347. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1348. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1349. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1350. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1351. else
  1352. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1353. end;
  1354. else
  1355. internalerror(2021092507);
  1356. end;
  1357. end;
  1358. end;
  1359. end;
  1360. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1361. begin
  1362. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1363. end;
  1364. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1365. var
  1366. section_nr: Integer;
  1367. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1368. var
  1369. objsec: TWasmObjSection;
  1370. begin
  1371. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1372. if Assigned(objsec) then
  1373. begin
  1374. debug_section_nr:=section_nr;
  1375. Inc(section_nr);
  1376. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1377. Inc(FWasmSymbolTableEntriesCount);
  1378. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1379. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1380. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1381. end;
  1382. end;
  1383. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1384. var
  1385. objsec: TWasmObjSection;
  1386. begin
  1387. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1388. if Assigned(objsec) then
  1389. begin
  1390. if oso_Data in objsec.SecOptions then
  1391. begin
  1392. objsec.Data.seek(0);
  1393. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1394. end
  1395. else
  1396. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1397. WriteWasmCustomSection(st);
  1398. end;
  1399. end;
  1400. var
  1401. i: Integer;
  1402. objsec: TWasmObjSection;
  1403. segment_count: Integer = 0;
  1404. cur_seg_ofs: qword = 0;
  1405. types_count,
  1406. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1407. code_section_nr, data_section_nr,
  1408. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1409. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1410. debug_ranges_section_nr,
  1411. NextGlobalIndex, NextTagIndex: Integer;
  1412. import_globals_count: Integer = 0;
  1413. globals_count: Integer = 0;
  1414. import_functions_count: Integer = 0;
  1415. export_functions_count: Integer = 0;
  1416. functions_count: Integer = 0;
  1417. import_exception_tags_count: Integer = 0;
  1418. exception_tags_count: Integer = 0;
  1419. objsym, ObjSymAlias: TWasmObjSymbol;
  1420. cust_sec: TWasmCustomSectionType;
  1421. SegmentFlags, SymbolFlags: UInt64;
  1422. begin
  1423. FData:=TWasmObjData(Data);
  1424. { each custom sections starts with its name }
  1425. for cust_sec in TWasmCustomSectionType do
  1426. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1427. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1428. for i:=0 to Data.ObjSymbolList.Count-1 do
  1429. begin
  1430. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1431. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1432. if objsym.bind=AB_EXTERNAL then
  1433. Inc(import_exception_tags_count)
  1434. else
  1435. Inc(exception_tags_count);
  1436. if objsym.typ=AT_WASM_GLOBAL then
  1437. if objsym.bind=AB_EXTERNAL then
  1438. Inc(import_globals_count)
  1439. else
  1440. Inc(globals_count);
  1441. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1442. Inc(import_globals_count);
  1443. if IsExternalFunction(objsym) then
  1444. Inc(import_functions_count);
  1445. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1446. begin
  1447. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1448. Inc(functions_count);
  1449. end;
  1450. if IsExportedFunction(objsym) then
  1451. Inc(export_functions_count);
  1452. end;
  1453. types_count:=FData.FFuncTypes.Count;
  1454. WriteUleb(FWasmSections[wsiType],types_count);
  1455. for i:=0 to types_count-1 do
  1456. with FData.FFuncTypes[i] do
  1457. begin
  1458. WriteByte(FWasmSections[wsiType],$60);
  1459. WriteWasmResultType(FWasmSections[wsiType],params);
  1460. WriteWasmResultType(FWasmSections[wsiType],results);
  1461. end;
  1462. for i:=0 to Data.ObjSectionList.Count-1 do
  1463. begin
  1464. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1465. if objsec.IsCode then
  1466. objsec.SegIdx:=-1
  1467. else if objsec.IsData then
  1468. begin
  1469. objsec.SegIdx:=segment_count;
  1470. objsec.SegOfs:=cur_seg_ofs;
  1471. Inc(segment_count);
  1472. Inc(cur_seg_ofs,objsec.Size);
  1473. end;
  1474. end;
  1475. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1476. WriteUleb(FWasmSections[wsiImport],imports_count);
  1477. { import memories }
  1478. WriteName(FWasmSections[wsiImport],'env');
  1479. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1480. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1481. WriteByte(FWasmSections[wsiImport],$00); { min }
  1482. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1483. { import globals }
  1484. NextGlobalIndex:=0;
  1485. for i:=0 to Data.ObjSymbolList.Count-1 do
  1486. begin
  1487. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1488. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1489. begin
  1490. objsym.GlobalIndex:=NextGlobalIndex;
  1491. Inc(NextGlobalIndex);
  1492. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1493. if objsym.ExtraData.ImportModule<>'' then
  1494. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1495. else
  1496. WriteName(FWasmSections[wsiImport],'env');
  1497. WriteName(FWasmSections[wsiImport],objsym.Name);
  1498. WriteByte(FWasmSections[wsiImport],$03); { global }
  1499. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1500. if objsym.ExtraData.GlobalIsImmutable then
  1501. WriteByte(FWasmSections[wsiImport],$00) { const }
  1502. else
  1503. WriteByte(FWasmSections[wsiImport],$01); { var }
  1504. end
  1505. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1506. begin
  1507. objsym.GlobalIndex:=NextGlobalIndex;
  1508. Inc(NextGlobalIndex);
  1509. objsym.ExtraData:=nil;
  1510. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1511. WriteName(FWasmSections[wsiImport],objsym.Name);
  1512. WriteByte(FWasmSections[wsiImport],$03); { global }
  1513. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1514. WriteByte(FWasmSections[wsiImport],$01); { var }
  1515. end;
  1516. end;
  1517. { import functions }
  1518. NextImportFunctionIndex:=0;
  1519. for i:=0 to Data.ObjSymbolList.Count-1 do
  1520. begin
  1521. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1522. if IsExternalFunction(objsym) then
  1523. begin
  1524. objsym.FuncIndex:=NextImportFunctionIndex;
  1525. Inc(NextImportFunctionIndex);
  1526. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1527. if objsym.ExtraData.ImportModule<>'' then
  1528. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1529. else
  1530. WriteName(FWasmSections[wsiImport],'env');
  1531. WriteName(FWasmSections[wsiImport],objsym.Name);
  1532. WriteByte(FWasmSections[wsiImport],$00); { func }
  1533. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1534. end;
  1535. end;
  1536. { import tables }
  1537. WriteName(FWasmSections[wsiImport],'env');
  1538. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1539. WriteByte(FWasmSections[wsiImport],$01); { table }
  1540. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1541. WriteByte(FWasmSections[wsiImport],$00); { min }
  1542. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1543. { import tags }
  1544. NextTagIndex:=0;
  1545. for i:=0 to Data.ObjSymbolList.Count-1 do
  1546. begin
  1547. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1548. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1549. begin
  1550. objsym.TagIndex:=NextTagIndex;
  1551. Inc(NextTagIndex);
  1552. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1553. if objsym.ExtraData.ImportModule<>'' then
  1554. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1555. else
  1556. WriteName(FWasmSections[wsiImport],'env');
  1557. WriteName(FWasmSections[wsiImport],objsym.Name);
  1558. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1559. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1560. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1561. end;
  1562. end;
  1563. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1564. NextFunctionIndex:=NextImportFunctionIndex;
  1565. for i:=0 to Data.ObjSymbolList.Count-1 do
  1566. begin
  1567. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1568. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1569. begin
  1570. objsym.FuncIndex:=NextFunctionIndex;
  1571. Inc(NextFunctionIndex);
  1572. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1573. end;
  1574. end;
  1575. if exception_tags_count>0 then
  1576. begin
  1577. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1578. for i:=0 to Data.ObjSymbolList.Count-1 do
  1579. begin
  1580. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1581. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1582. begin
  1583. objsym.TagIndex:=NextTagIndex;
  1584. Inc(NextTagIndex);
  1585. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1586. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1587. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1588. end;
  1589. end;
  1590. end;
  1591. if globals_count>0 then
  1592. begin
  1593. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1594. for i:=0 to Data.ObjSymbolList.Count-1 do
  1595. begin
  1596. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1597. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1598. begin
  1599. objsym.GlobalIndex:=NextGlobalIndex;
  1600. Inc(NextGlobalIndex);
  1601. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1602. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1603. if objsym.ExtraData.GlobalIsImmutable then
  1604. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1605. else
  1606. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1607. { init expr }
  1608. case objsym.ExtraData.GlobalType of
  1609. wbt_i32:
  1610. begin
  1611. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1612. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1613. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1614. end;
  1615. wbt_i64:
  1616. begin
  1617. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1618. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1619. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1620. end;
  1621. wbt_f32:
  1622. begin
  1623. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1624. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1625. WriteByte(FWasmSections[wsiGlobal],$00);
  1626. WriteByte(FWasmSections[wsiGlobal],$00);
  1627. WriteByte(FWasmSections[wsiGlobal],$00);
  1628. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1629. end;
  1630. wbt_f64:
  1631. begin
  1632. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1633. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1634. WriteByte(FWasmSections[wsiGlobal],$00);
  1635. WriteByte(FWasmSections[wsiGlobal],$00);
  1636. WriteByte(FWasmSections[wsiGlobal],$00);
  1637. WriteByte(FWasmSections[wsiGlobal],$00);
  1638. WriteByte(FWasmSections[wsiGlobal],$00);
  1639. WriteByte(FWasmSections[wsiGlobal],$00);
  1640. WriteByte(FWasmSections[wsiGlobal],$00);
  1641. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1642. end;
  1643. wbt_externref:
  1644. begin
  1645. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1646. WriteByte(FWasmSections[wsiGlobal],$6F);
  1647. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1648. end;
  1649. wbt_funcref:
  1650. begin
  1651. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1652. WriteByte(FWasmSections[wsiGlobal],$70);
  1653. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1654. end;
  1655. else
  1656. internalerror(2022052801);
  1657. end;
  1658. end;
  1659. end;
  1660. end;
  1661. if export_functions_count>0 then
  1662. begin
  1663. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1664. for i:=0 to Data.ObjSymbolList.Count-1 do
  1665. begin
  1666. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1667. if IsExportedFunction(objsym) then
  1668. begin
  1669. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1670. WriteByte(FWasmSections[wsiExport],0); { func }
  1671. if (objsym.FuncIndex<0) then
  1672. message1(asmw_e_illegal_unset_index,objsym.name)
  1673. else
  1674. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1675. end;
  1676. end;
  1677. end;
  1678. for i:=0 to Data.ObjSymbolList.Count-1 do
  1679. begin
  1680. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1681. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1682. begin
  1683. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1684. Inc(FWasmSymbolTableEntriesCount);
  1685. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1686. if objsym.bind=AB_GLOBAL then
  1687. WriteUleb(FWasmSymbolTable,0)
  1688. else if objsym.bind=AB_LOCAL then
  1689. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1690. else if objsym.bind=AB_EXTERNAL then
  1691. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1692. else if objsym.bind=AB_WEAK then
  1693. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  1694. else
  1695. internalerror(2021092715);
  1696. if (objsym.TagIndex<0) then
  1697. message1(asmw_e_illegal_unset_index,objsym.name)
  1698. else
  1699. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  1700. if objsym.bind<>AB_EXTERNAL then
  1701. WriteName(FWasmSymbolTable,objsym.Name);
  1702. end
  1703. else if objsym.typ=AT_WASM_GLOBAL then
  1704. begin
  1705. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1706. Inc(FWasmSymbolTableEntriesCount);
  1707. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  1708. if objsym.bind=AB_EXTERNAL then
  1709. begin
  1710. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1711. if (objsym.GlobalIndex<0) then
  1712. message1(asmw_e_illegal_unset_index,objsym.name)
  1713. else
  1714. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1715. end
  1716. else
  1717. begin
  1718. WriteUleb(FWasmSymbolTable,0);
  1719. if (objsym.GlobalIndex<0) then
  1720. message1(asmw_e_illegal_unset_index,objsym.name)
  1721. else
  1722. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1723. WriteName(FWasmSymbolTable,objsym.Name);
  1724. end;
  1725. end
  1726. else if IsExternalFunction(objsym) then
  1727. begin
  1728. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1729. Inc(FWasmSymbolTableEntriesCount);
  1730. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1731. if objsym.ExtraData.ImportModule<>'' then
  1732. begin
  1733. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1734. if (objsym.FuncIndex<0) then
  1735. message1(asmw_e_illegal_unset_index,objsym.name)
  1736. else
  1737. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1738. WriteName(FWasmSymbolTable,objsym.Name);
  1739. end
  1740. else
  1741. begin
  1742. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1743. if (objsym.FuncIndex<0) then
  1744. message1(asmw_e_illegal_unset_index,objsym.name)
  1745. else
  1746. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1747. end;
  1748. end
  1749. else if objsym.typ=AT_FUNCTION then
  1750. begin
  1751. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1752. Inc(FWasmSymbolTableEntriesCount);
  1753. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1754. if objsym.IsAlias then
  1755. begin
  1756. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1757. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1758. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1759. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1760. end
  1761. else
  1762. begin
  1763. if IsExportedFunction(objsym) then
  1764. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  1765. else
  1766. WriteUleb(FWasmSymbolTable,0);
  1767. if (objsym.FuncIndex<0) then
  1768. message1(asmw_e_illegal_unset_index,objsym.name)
  1769. else
  1770. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1771. end;
  1772. WriteName(FWasmSymbolTable,objsym.Name);
  1773. end
  1774. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1775. begin
  1776. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  1777. begin
  1778. {todo: debug symbols}
  1779. end
  1780. else
  1781. begin
  1782. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1783. Inc(FWasmSymbolTableEntriesCount);
  1784. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1785. if objsym.bind=AB_GLOBAL then
  1786. SymbolFlags:=0
  1787. else if objsym.bind=AB_LOCAL then
  1788. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  1789. else if objsym.bind=AB_EXTERNAL then
  1790. SymbolFlags:=WASM_SYM_UNDEFINED
  1791. else
  1792. internalerror(2021092506);
  1793. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1794. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  1795. WriteUleb(FWasmSymbolTable,SymbolFlags);
  1796. WriteName(FWasmSymbolTable,objsym.Name);
  1797. if objsym.bind<>AB_EXTERNAL then
  1798. begin
  1799. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1800. WriteUleb(FWasmSymbolTable,objsym.offset);
  1801. WriteUleb(FWasmSymbolTable,objsym.size);
  1802. end;
  1803. end;
  1804. end;
  1805. end;
  1806. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1807. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1808. if ts_wasm_threads in current_settings.targetswitches then
  1809. begin
  1810. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1811. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1812. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1813. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1814. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1815. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1816. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1817. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1818. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1819. end
  1820. else
  1821. begin
  1822. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  1823. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1824. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1825. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1826. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1827. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1828. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1829. end;
  1830. { Write the producers section:
  1831. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1832. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1833. WriteName(FWasmCustomSections[wcstProducers],'language');
  1834. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1835. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1836. WriteName(FWasmCustomSections[wcstProducers],'');
  1837. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1838. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1839. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1840. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1841. code_section_nr:=-1;
  1842. data_section_nr:=-1;
  1843. debug_abbrev_section_nr:=-1;
  1844. debug_info_section_nr:=-1;
  1845. debug_str_section_nr:=-1;
  1846. debug_line_section_nr:=-1;
  1847. debug_frame_section_nr:=-1;
  1848. debug_aranges_section_nr:=-1;
  1849. debug_ranges_section_nr:=-1;
  1850. section_nr:=0;
  1851. WriteWasmSection(wsiType);
  1852. Inc(section_nr);
  1853. WriteWasmSection(wsiImport);
  1854. Inc(section_nr);
  1855. WriteWasmSection(wsiFunction);
  1856. Inc(section_nr);
  1857. if exception_tags_count>0 then
  1858. begin
  1859. WriteWasmSection(wsiTag);
  1860. Inc(section_nr);
  1861. end;
  1862. if globals_count>0 then
  1863. begin
  1864. WriteWasmSection(wsiGlobal);
  1865. Inc(section_nr);
  1866. end;
  1867. if export_functions_count>0 then
  1868. begin
  1869. WriteWasmSection(wsiExport);
  1870. Inc(section_nr);
  1871. end;
  1872. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1873. if segment_count>0 then
  1874. Inc(section_nr); { the DataCount section }
  1875. code_section_nr:=section_nr; { the Code section }
  1876. Inc(section_nr);
  1877. if segment_count>0 then
  1878. begin
  1879. data_section_nr:=section_nr; { the Data section }
  1880. Inc(section_nr);
  1881. end;
  1882. { the debug sections }
  1883. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1884. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1885. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1886. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1887. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1888. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1889. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1890. DoRelocations;
  1891. if segment_count>0 then
  1892. begin
  1893. WriteUleb(FWasmSections[wsiData],segment_count);
  1894. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  1895. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  1896. for i:=0 to Data.ObjSectionList.Count-1 do
  1897. begin
  1898. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1899. if objsec.IsData then
  1900. begin
  1901. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  1902. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  1903. SegmentFlags:=0;
  1904. if (ts_wasm_threads in current_settings.targetswitches) and
  1905. (oso_threadvar in objsec.SecOptions) then
  1906. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  1907. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  1908. WriteByte(FWasmSections[wsiData],0);
  1909. WriteByte(FWasmSections[wsiData],$41);
  1910. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  1911. WriteByte(FWasmSections[wsiData],$0b);
  1912. WriteUleb(FWasmSections[wsiData],objsec.Size);
  1913. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  1914. if oso_Data in objsec.SecOptions then
  1915. begin
  1916. objsec.Data.seek(0);
  1917. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  1918. end
  1919. else
  1920. begin
  1921. WriteZeros(FWasmSections[wsiData],objsec.Size);
  1922. end;
  1923. end;
  1924. end;
  1925. end;
  1926. WriteUleb(FWasmSections[wsiCode],functions_count);
  1927. for i:=0 to Data.ObjSymbolList.Count-1 do
  1928. begin
  1929. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1930. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1931. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  1932. end;
  1933. if segment_count>0 then
  1934. WriteWasmSection(wsiDataCount);
  1935. WriteWasmSection(wsiCode);
  1936. if segment_count>0 then
  1937. WriteWasmSection(wsiData);
  1938. MaybeWriteDebugSection(wcstDebugAbbrev);
  1939. MaybeWriteDebugSection(wcstDebugInfo);
  1940. MaybeWriteDebugSection(wcstDebugStr);
  1941. MaybeWriteDebugSection(wcstDebugLine);
  1942. MaybeWriteDebugSection(wcstDebugFrame);
  1943. MaybeWriteDebugSection(wcstDebugAranges);
  1944. MaybeWriteDebugSection(wcstDebugRanges);
  1945. WriteRelocations;
  1946. WriteSymbolTable;
  1947. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  1948. if segment_count>0 then
  1949. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  1950. WriteRelocationCodeTable(code_section_nr);
  1951. if segment_count>0 then
  1952. WriteRelocationDataTable(data_section_nr);
  1953. WriteWasmCustomSection(wcstLinking);
  1954. Inc(section_nr);
  1955. WriteWasmCustomSection(wcstRelocCode);
  1956. Inc(section_nr);
  1957. if segment_count>0 then
  1958. begin
  1959. WriteWasmCustomSection(wcstRelocData);
  1960. Inc(section_nr);
  1961. end;
  1962. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  1963. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  1964. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  1965. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  1966. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  1967. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  1968. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  1969. WriteWasmCustomSection(wcstProducers);
  1970. Inc(section_nr);
  1971. WriteWasmCustomSection(wcstTargetFeatures);
  1972. Inc(section_nr);
  1973. result:=true;
  1974. end;
  1975. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  1976. var
  1977. i: TWasmSectionID;
  1978. j: TWasmCustomSectionType;
  1979. k: TWasmLinkingSubsectionType;
  1980. begin
  1981. inherited;
  1982. cobjdata:=TWasmObjData;
  1983. for i in TWasmSectionID do
  1984. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  1985. for j in TWasmCustomSectionType do
  1986. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  1987. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1988. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  1989. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  1990. FWasmSymbolTableEntriesCount:=0;
  1991. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  1992. FWasmRelocationCodeTableEntriesCount:=0;
  1993. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  1994. FWasmRelocationDataTableEntriesCount:=0;
  1995. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  1996. FWasmRelocationDebugFrameTableEntriesCount:=0;
  1997. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  1998. FWasmRelocationDebugInfoTableEntriesCount:=0;
  1999. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  2000. FWasmRelocationDebugLineTableEntriesCount:=0;
  2001. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  2002. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  2003. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2004. FWasmRelocationDebugArangesTableEntriesCount:=0;
  2005. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2006. FWasmRelocationDebugRangesTableEntriesCount:=0;
  2007. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  2008. FWasmRelocationDebugStrTableEntriesCount:=0;
  2009. end;
  2010. destructor TWasmObjOutput.destroy;
  2011. var
  2012. i: TWasmSectionID;
  2013. j: TWasmCustomSectionType;
  2014. k: TWasmLinkingSubsectionType;
  2015. begin
  2016. for i in TWasmSectionID do
  2017. FWasmSections[i].Free;
  2018. for j in TWasmCustomSectionType do
  2019. FWasmCustomSections[j].Free;
  2020. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2021. FWasmLinkingSubsections[k].Free;
  2022. FWasmSymbolTable.Free;
  2023. FWasmRelocationCodeTable.Free;
  2024. FWasmRelocationDataTable.Free;
  2025. FWasmRelocationDebugFrameTable.Free;
  2026. FWasmRelocationDebugInfoTable.Free;
  2027. FWasmRelocationDebugLineTable.Free;
  2028. FWasmRelocationDebugAbbrevTable.Free;
  2029. FWasmRelocationDebugArangesTable.Free;
  2030. FWasmRelocationDebugRangesTable.Free;
  2031. FWasmRelocationDebugStrTable.Free;
  2032. inherited destroy;
  2033. end;
  2034. {****************************************************************************
  2035. TWasmObjInput
  2036. ****************************************************************************}
  2037. constructor TWasmObjInput.create;
  2038. begin
  2039. inherited create;
  2040. cobjdata:=TWasmObjData;
  2041. end;
  2042. destructor TWasmObjInput.Destroy;
  2043. var
  2044. i: Integer;
  2045. begin
  2046. for i:=low(FFuncTypes) to high(FFuncTypes) do
  2047. begin
  2048. FFuncTypes[i].free;
  2049. FFuncTypes[i]:=nil;
  2050. end;
  2051. inherited Destroy;
  2052. end;
  2053. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2054. var
  2055. ModuleMagic: array [0..3] of Byte;
  2056. ModuleVersion: array [0..3] of Byte;
  2057. i: Integer;
  2058. begin
  2059. result:=false;
  2060. if not AReader.read(ModuleMagic,4) then
  2061. exit;
  2062. for i:=0 to 3 do
  2063. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2064. exit;
  2065. if not AReader.read(ModuleVersion,4) then
  2066. exit;
  2067. for i:=0 to 3 do
  2068. if ModuleVersion[i]<>WasmVersion[i] then
  2069. exit;
  2070. result:=true;
  2071. end;
  2072. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2073. type
  2074. TLimits = record
  2075. Min, Max: uint32;
  2076. HasMax: Boolean;
  2077. end;
  2078. var
  2079. SectionIndex: Integer = -1;
  2080. SectionId: Byte;
  2081. SectionSize: uint32;
  2082. SectionStart: LongInt;
  2083. CheckSectionBounds: Boolean;
  2084. TypeSectionRead: Boolean = false;
  2085. ImportSectionRead: Boolean = false;
  2086. FunctionSectionRead: Boolean = false;
  2087. GlobalSectionRead: Boolean = false;
  2088. ExportSectionRead: Boolean = false;
  2089. CodeSectionRead: Boolean = false;
  2090. DataSectionRead: Boolean = false;
  2091. DataCountSectionRead: Boolean = false;
  2092. SegmentInfoSectionRead: Boolean = false;
  2093. SymbolTableSectionRead: Boolean = false;
  2094. CodeSectionIndex: Integer = -1;
  2095. DataSectionIndex: Integer = -1;
  2096. FuncTypes: array of record
  2097. IsImport: Boolean;
  2098. ImportName: ansistring;
  2099. ImportModName: ansistring;
  2100. typidx: uint32;
  2101. IsExported: Boolean;
  2102. ExportName: ansistring;
  2103. end;
  2104. FuncTypeImportsCount: uint32;
  2105. TableTypes: array of record
  2106. IsImport: Boolean;
  2107. ImportName: ansistring;
  2108. ImportModName: ansistring;
  2109. reftype: TWasmBAsicType;
  2110. limits: TLimits;
  2111. IsExported: Boolean;
  2112. ExportName: ansistring;
  2113. end;
  2114. TableTypeImportsCount: uint32;
  2115. MemTypes: array of record
  2116. IsImport: Boolean;
  2117. ImportName: ansistring;
  2118. ImportModName: ansistring;
  2119. limits: TLimits;
  2120. IsExported: Boolean;
  2121. ExportName: ansistring;
  2122. end;
  2123. MemTypeImportsCount: uint32;
  2124. GlobalTypes: array of record
  2125. IsImport: Boolean;
  2126. ImportName: ansistring;
  2127. ImportModName: ansistring;
  2128. valtype: TWasmBasicType;
  2129. IsMutable: Boolean;
  2130. IsExported: Boolean;
  2131. ExportName: ansistring;
  2132. end;
  2133. GlobalTypeImportsCount: uint32;
  2134. CodeSegments: array of record
  2135. CodeSectionOffset: uint32;
  2136. CodeSize: uint32;
  2137. DataPos: LongInt;
  2138. SegName: ansistring;
  2139. SegIsExported: Boolean;
  2140. end;
  2141. DataSegments: array of record
  2142. DataSectionOffset: uint32;
  2143. Active: Boolean;
  2144. MemIdx: uint32;
  2145. Len: uint32;
  2146. Offset: int32;
  2147. DataPos: LongInt;
  2148. SegName: ansistring;
  2149. SegAlignment: uint32;
  2150. SegFlags: uint32;
  2151. end;
  2152. SymbolTable: array of record
  2153. SymFlags: uint32;
  2154. TargetSection: uint32;
  2155. SymIndex: uint32;
  2156. SymOffset: uint32;
  2157. SymSize: uint32;
  2158. SymKind: Byte;
  2159. SymName: ansistring;
  2160. ObjSym: TWasmObjSymbol;
  2161. end;
  2162. { meaning of first index: }
  2163. { table 0 is code relocs }
  2164. { table 1 is data relocs }
  2165. { tables 2.. are custom section relocs }
  2166. RelocationTable: array of array of record
  2167. RelocType: Byte;
  2168. RelocOffset: uint32;
  2169. RelocIndex: uint32;
  2170. RelocAddend: int32;
  2171. end;
  2172. function ReadSection: Boolean;
  2173. function read(out b;len:longint):boolean;
  2174. begin
  2175. result:=false;
  2176. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2177. result:=AReader.read(b,len)
  2178. else
  2179. begin
  2180. { trying to read beyond the end of the section }
  2181. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2182. result:=false;
  2183. end;
  2184. end;
  2185. function ReadUleb(out v: uint64): boolean;
  2186. var
  2187. b: byte;
  2188. shift:integer;
  2189. begin
  2190. result:=false;
  2191. b:=0;
  2192. v:=0;
  2193. shift:=0;
  2194. repeat
  2195. if not read(b,1) then
  2196. exit;
  2197. v:=v or (uint64(b and 127) shl shift);
  2198. inc(shift,7);
  2199. until (b and 128)=0;
  2200. result:=true;
  2201. end;
  2202. function ReadUleb32(out v: uint32): boolean;
  2203. var
  2204. vv: uint64;
  2205. begin
  2206. result:=false;
  2207. v:=default(uint32);
  2208. if not ReadUleb(vv) then
  2209. exit;
  2210. if vv>high(uint32) then
  2211. exit;
  2212. v:=vv;
  2213. result:=true;
  2214. end;
  2215. function ReadSleb(out v: int64): boolean;
  2216. var
  2217. b: byte;
  2218. shift:integer;
  2219. begin
  2220. result:=false;
  2221. b:=0;
  2222. v:=0;
  2223. shift:=0;
  2224. repeat
  2225. if not read(b,1) then
  2226. exit;
  2227. v:=v or (uint64(b and 127) shl shift);
  2228. inc(shift,7);
  2229. until (b and 128)=0;
  2230. {$ifopt Q+}
  2231. {$define overflowon}
  2232. {$Q-}
  2233. {$endif}
  2234. {$ifopt R+}
  2235. {$define rangeon}
  2236. {$R-}
  2237. {$endif}
  2238. if (b and 64)<>0 then
  2239. v:=v or (high(uint64) shl shift);
  2240. result:=true;
  2241. end;
  2242. {$ifdef overflowon}
  2243. {$Q+}
  2244. {$undef overflowon}
  2245. {$endif}
  2246. {$ifdef rangeon}
  2247. {$R+}
  2248. {$undef rangeon}
  2249. {$endif}
  2250. function ReadSleb32(out v: int32): boolean;
  2251. var
  2252. vv: int64;
  2253. begin
  2254. result:=false;
  2255. v:=default(int32);
  2256. if not ReadSleb(vv) then
  2257. exit;
  2258. if (vv>high(int32)) or (vv<low(int32)) then
  2259. exit;
  2260. v:=vv;
  2261. result:=true;
  2262. end;
  2263. function ReadName(out v: ansistring): boolean;
  2264. var
  2265. len: uint32;
  2266. begin
  2267. result:=false;
  2268. if not ReadUleb32(len) then
  2269. exit;
  2270. SetLength(v,len);
  2271. if len>0 then
  2272. result:=read(v[1],len)
  2273. else
  2274. result:=true;
  2275. end;
  2276. function ReadCustomSection: Boolean;
  2277. function ReadRelocationSection: Boolean;
  2278. var
  2279. TargetSection, RelocCount: uint32;
  2280. i: Integer;
  2281. RelocTableIndex: Integer;
  2282. begin
  2283. Result:=False;
  2284. if not ReadUleb32(TargetSection) then
  2285. begin
  2286. InputError('Error reading the index of the target section of a relocation section');
  2287. exit;
  2288. end;
  2289. if TargetSection=CodeSectionIndex then
  2290. RelocTableIndex:=0
  2291. else if TargetSection=DataSectionIndex then
  2292. RelocTableIndex:=1
  2293. else
  2294. begin
  2295. InputError('Relocation for custom sections not supported, yet');
  2296. exit;
  2297. end;
  2298. if not ReadUleb32(RelocCount) then
  2299. begin
  2300. InputError('Error reading the relocation entries count from a relocation section');
  2301. exit;
  2302. end;
  2303. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2304. for i:=0 to RelocCount-1 do
  2305. with RelocationTable[RelocTableIndex,i] do
  2306. begin
  2307. if not Read(RelocType,1) then
  2308. begin
  2309. InputError('Error reading the relocation type of a relocation entry');
  2310. exit;
  2311. end;
  2312. if not (TWasmRelocationType(RelocType) in [R_WASM_FUNCTION_INDEX_LEB,
  2313. R_WASM_MEMORY_ADDR_LEB,
  2314. R_WASM_TABLE_INDEX_SLEB,
  2315. R_WASM_MEMORY_ADDR_SLEB,
  2316. R_WASM_SECTION_OFFSET_I32,
  2317. R_WASM_TABLE_INDEX_I32,
  2318. R_WASM_FUNCTION_OFFSET_I32,
  2319. R_WASM_MEMORY_ADDR_I32,
  2320. R_WASM_TYPE_INDEX_LEB,
  2321. R_WASM_GLOBAL_INDEX_LEB,
  2322. R_WASM_TAG_INDEX_LEB]) then
  2323. begin
  2324. InputError('Unsupported relocation type: ' + tostr(RelocType));
  2325. exit;
  2326. end;
  2327. if not ReadUleb32(RelocOffset) then
  2328. begin
  2329. InputError('Error reading the relocation offset of a relocation entry');
  2330. exit;
  2331. end;
  2332. if not ReadUleb32(RelocIndex) then
  2333. begin
  2334. InputError('Error reading the relocation index of a relocation entry');
  2335. exit;
  2336. end;
  2337. if TWasmRelocationType(RelocType) in [R_WASM_FUNCTION_OFFSET_I32,R_WASM_SECTION_OFFSET_I32,R_WASM_MEMORY_ADDR_LEB,R_WASM_MEMORY_ADDR_SLEB,R_WASM_MEMORY_ADDR_I32] then
  2338. begin
  2339. if not ReadSleb32(RelocAddend) then
  2340. begin
  2341. InputError('Error reading the relocation addend of a relocation entry');
  2342. exit;
  2343. end;
  2344. end;
  2345. end;
  2346. if AReader.Pos<>(SectionStart+SectionSize) then
  2347. begin
  2348. InputError('Unexpected relocation section size');
  2349. exit;
  2350. end;
  2351. Result:=True;
  2352. end;
  2353. function ReadLinkingSection: Boolean;
  2354. function ReadSegmentInfo: Boolean;
  2355. var
  2356. SegmentCount: uint32;
  2357. i: Integer;
  2358. begin
  2359. Result:=False;
  2360. if SegmentInfoSectionRead then
  2361. begin
  2362. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2363. exit;
  2364. end;
  2365. SegmentInfoSectionRead:=True;
  2366. if not ReadUleb32(SegmentCount) then
  2367. begin
  2368. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2369. exit;
  2370. end;
  2371. if SegmentCount<>Length(DataSegments) then
  2372. begin
  2373. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2374. exit;
  2375. end;
  2376. for i:=0 to SegmentCount-1 do
  2377. with DataSegments[i] do
  2378. begin
  2379. if not ReadName(SegName) then
  2380. begin
  2381. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2382. exit;
  2383. end;
  2384. if not ReadUleb32(SegAlignment) then
  2385. begin
  2386. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2387. exit;
  2388. end;
  2389. if not ReadUleb32(SegFlags) then
  2390. begin
  2391. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2392. exit;
  2393. end;
  2394. end;
  2395. if AReader.Pos<>(SectionStart+SectionSize) then
  2396. begin
  2397. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2398. exit;
  2399. end;
  2400. Result:=True;
  2401. end;
  2402. function ReadSymbolTable: Boolean;
  2403. var
  2404. SymCount: uint32;
  2405. i: Integer;
  2406. SymKindName: string;
  2407. begin
  2408. Result:=False;
  2409. if SymbolTableSectionRead then
  2410. begin
  2411. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2412. exit;
  2413. end;
  2414. SymbolTableSectionRead:=True;
  2415. if not ReadUleb32(SymCount) then
  2416. begin
  2417. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2418. exit;
  2419. end;
  2420. SetLength(SymbolTable,SymCount);
  2421. for i:=0 to SymCount-1 do
  2422. with SymbolTable[i] do
  2423. begin
  2424. if not Read(SymKind,1) then
  2425. begin
  2426. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2427. exit;
  2428. end;
  2429. if not ReadUleb32(SymFlags) then
  2430. begin
  2431. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2432. exit;
  2433. end;
  2434. case SymKind of
  2435. byte(SYMTAB_FUNCTION),
  2436. byte(SYMTAB_GLOBAL),
  2437. byte(SYMTAB_EVENT),
  2438. byte(SYMTAB_TABLE):
  2439. begin
  2440. WriteStr(SymKindName, TWasmSymbolType(SymKind));
  2441. if not ReadUleb32(SymIndex) then
  2442. begin
  2443. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2444. exit;
  2445. end;
  2446. if ((SymKind=byte(SYMTAB_FUNCTION)) and (SymIndex>high(FuncTypes))) then
  2447. begin
  2448. InputError('Symbol index too high');
  2449. exit;
  2450. end;
  2451. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2452. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2453. begin
  2454. if not ReadName(SymName) then
  2455. begin
  2456. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2457. exit;
  2458. end;
  2459. end;
  2460. end;
  2461. byte(SYMTAB_DATA):
  2462. begin
  2463. if not ReadName(SymName) then
  2464. begin
  2465. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2466. exit;
  2467. end;
  2468. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2469. begin
  2470. if not ReadUleb32(SymIndex) then
  2471. begin
  2472. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2473. exit;
  2474. end;
  2475. if SymIndex>high(DataSegments) then
  2476. begin
  2477. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2478. exit;
  2479. end;
  2480. if not ReadUleb32(SymOffset) then
  2481. begin
  2482. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2483. exit;
  2484. end;
  2485. if not ReadUleb32(SymSize) then
  2486. begin
  2487. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2488. exit;
  2489. end;
  2490. end;
  2491. end;
  2492. byte(SYMTAB_SECTION):
  2493. begin
  2494. if not ReadUleb32(TargetSection) then
  2495. begin
  2496. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2497. exit;
  2498. end;
  2499. end;
  2500. else
  2501. begin
  2502. InputError('Unsupported symbol kind: ' + tostr(SymKind));
  2503. exit;
  2504. end;
  2505. end;
  2506. end;
  2507. if AReader.Pos<>(SectionStart+SectionSize) then
  2508. begin
  2509. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2510. exit;
  2511. end;
  2512. Result:=True;
  2513. end;
  2514. const
  2515. ExpectedVersion = 2;
  2516. var
  2517. Version, SubsectionSize, SaveSectionSize: uint32;
  2518. SubsectionType: Byte;
  2519. SaveSectionStart: LongInt;
  2520. begin
  2521. Result:=False;
  2522. if not ReadUleb32(Version) then
  2523. begin
  2524. InputError('Error reading the version of the ''linking'' section');
  2525. exit;
  2526. end;
  2527. if Version<>ExpectedVersion then
  2528. begin
  2529. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2530. exit;
  2531. end;
  2532. while AReader.Pos<(SectionStart+SectionSize) do
  2533. begin
  2534. if not read(SubsectionType, 1) then
  2535. begin
  2536. InputError('Error reading subsection type in the ''linking'' section');
  2537. exit;
  2538. end;
  2539. if not ReadUleb32(SubsectionSize) then
  2540. begin
  2541. InputError('Error reading subsection size in the ''linking'' section');
  2542. exit;
  2543. end;
  2544. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2545. begin
  2546. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2547. exit;
  2548. end;
  2549. SaveSectionStart:=SectionStart;
  2550. SaveSectionSize:=SectionSize;
  2551. SectionStart:=AReader.Pos;
  2552. SectionSize:=SubsectionSize;
  2553. case SubsectionType of
  2554. Byte(WASM_SEGMENT_INFO):
  2555. if not ReadSegmentInfo then
  2556. begin
  2557. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2558. exit;
  2559. end;
  2560. Byte(WASM_SYMBOL_TABLE):
  2561. if not ReadSymbolTable then
  2562. begin
  2563. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2564. exit;
  2565. end;
  2566. else
  2567. begin
  2568. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2569. exit;
  2570. end;
  2571. end;
  2572. AReader.Seek(SectionStart+SectionSize);
  2573. SectionStart:=SaveSectionStart;
  2574. SectionSize:=SaveSectionSize;
  2575. end;
  2576. result:=True;
  2577. end;
  2578. function ReadProducersSection: Boolean;
  2579. begin
  2580. Result:=False;
  2581. end;
  2582. function ReadTargetFeaturesSection: Boolean;
  2583. begin
  2584. Result:=False;
  2585. end;
  2586. const
  2587. RelocationSectionPrefix = 'reloc.';
  2588. var
  2589. SectionName: ansistring;
  2590. begin
  2591. Result:=False;
  2592. ReadName(SectionName);
  2593. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2594. begin
  2595. if not ReadRelocationSection then
  2596. begin
  2597. InputError('Error reading the relocation section ''' + SectionName + '''');
  2598. exit;
  2599. end;
  2600. end
  2601. else
  2602. case SectionName of
  2603. 'linking':
  2604. if not ReadLinkingSection then
  2605. begin
  2606. InputError('Error reading the ''linking'' section');
  2607. exit;
  2608. end;
  2609. 'producers':
  2610. Result:=ReadProducersSection;
  2611. 'target_features':
  2612. Result:=ReadTargetFeaturesSection;
  2613. else
  2614. InputError('Unsupported custom section: ''' + SectionName + '''');
  2615. end;
  2616. Result:=True;
  2617. end;
  2618. function ReadTypeSection: Boolean;
  2619. var
  2620. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2621. FuncTypeId, WasmTypeId: Byte;
  2622. i, j: Integer;
  2623. wbt: TWasmBasicType;
  2624. begin
  2625. Result:=False;
  2626. if TypeSectionRead then
  2627. begin
  2628. InputError('Type section is duplicated');
  2629. exit;
  2630. end;
  2631. TypeSectionRead:=True;
  2632. if not ReadUleb32(FuncTypesCount) then
  2633. begin
  2634. InputError('Error reading the func types count');
  2635. exit;
  2636. end;
  2637. SetLength(FFuncTypes,FuncTypesCount);
  2638. for i:=0 to FuncTypesCount - 1 do
  2639. begin
  2640. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2641. if not AReader.read(FuncTypeId,1) then
  2642. begin
  2643. InputError('Error reading the function type identifier');
  2644. exit;
  2645. end;
  2646. if FuncTypeId<>$60 then
  2647. begin
  2648. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2649. exit;
  2650. end;
  2651. if not ReadUleb32(ParamsCount) then
  2652. begin
  2653. InputError('Error reading the function parameters count');
  2654. exit;
  2655. end;
  2656. for j:=0 to ParamsCount-1 do
  2657. begin
  2658. if not AReader.read(WasmTypeId,1) then
  2659. begin
  2660. InputError('Error reading a function parameter basic type');
  2661. exit;
  2662. end;
  2663. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2664. begin
  2665. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2666. exit;
  2667. end;
  2668. FFuncTypes[i].add_param(wbt);
  2669. end;
  2670. if not ReadUleb32(ResultsCount) then
  2671. begin
  2672. InputError('Error reading the function results count');
  2673. exit;
  2674. end;
  2675. for j:=0 to ResultsCount-1 do
  2676. begin
  2677. if not AReader.read(WasmTypeId,1) then
  2678. begin
  2679. InputError('Error reading a function result basic type');
  2680. exit;
  2681. end;
  2682. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2683. begin
  2684. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2685. exit;
  2686. end;
  2687. FFuncTypes[i].add_result(wbt);
  2688. end;
  2689. end;
  2690. if AReader.Pos<>(SectionStart+SectionSize) then
  2691. begin
  2692. InputError('Unexpected type section size');
  2693. exit;
  2694. end;
  2695. Result:=true;
  2696. end;
  2697. function ReadImportSection: Boolean;
  2698. var
  2699. ImportsCount: uint32;
  2700. i: Integer;
  2701. ModName, Name: ansistring;
  2702. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2703. GlobalType, GlobalMutabilityType: Byte;
  2704. begin
  2705. Result:=False;
  2706. if ImportSectionRead then
  2707. begin
  2708. InputError('Import section is duplicated');
  2709. exit;
  2710. end;
  2711. ImportSectionRead:=True;
  2712. if not ReadUleb32(ImportsCount) then
  2713. begin
  2714. InputError('Error reading the imports count');
  2715. exit;
  2716. end;
  2717. for i:=0 to ImportsCount-1 do
  2718. begin
  2719. if not ReadName(ModName) then
  2720. begin
  2721. InputError('Error reading import module name');
  2722. exit;
  2723. end;
  2724. if not ReadName(Name) then
  2725. begin
  2726. InputError('Error import name');
  2727. exit;
  2728. end;
  2729. if not AReader.Read(ImportType,1) then
  2730. begin
  2731. InputError('Error reading import type');
  2732. exit;
  2733. end;
  2734. case ImportType of
  2735. $00: { func }
  2736. begin
  2737. Inc(FuncTypeImportsCount);
  2738. SetLength(FuncTypes,FuncTypeImportsCount);
  2739. with FuncTypes[FuncTypeImportsCount-1] do
  2740. begin
  2741. IsImport:=True;
  2742. ImportName:=Name;
  2743. ImportModName:=ModName;
  2744. if not ReadUleb32(typidx) then
  2745. begin
  2746. InputError('Error reading type index for func import');
  2747. exit;
  2748. end;
  2749. if typidx>high(FFuncTypes) then
  2750. begin
  2751. InputError('Type index in func import exceeds bounds of the types table');
  2752. exit;
  2753. end;
  2754. end;
  2755. end;
  2756. $01: { table }
  2757. begin
  2758. Inc(TableTypeImportsCount);
  2759. SetLength(TableTypes,TableTypeImportsCount);
  2760. with TableTypes[TableTypeImportsCount-1] do
  2761. begin
  2762. IsImport:=True;
  2763. ImportName:=Name;
  2764. ImportModName:=ModName;
  2765. if not AReader.read(TableElemTyp,1) then
  2766. begin
  2767. InputError('Error reading table element type for table import');
  2768. exit;
  2769. end;
  2770. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  2771. begin
  2772. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2773. exit;
  2774. end;
  2775. if not (reftype in WasmReferenceTypes) then
  2776. begin
  2777. InputError('Table element type for table import must be a reference type');
  2778. exit;
  2779. end;
  2780. if not AReader.read(TableLimitsKind,1) then
  2781. begin
  2782. InputError('Error reading table limits kind for table import');
  2783. exit;
  2784. end;
  2785. case TableLimitsKind of
  2786. $00:
  2787. begin
  2788. limits.HasMax:=False;
  2789. limits.Max:=high(limits.Max);
  2790. if not ReadUleb32(limits.min) then
  2791. begin
  2792. InputError('Error reading table limits min for table import');
  2793. exit;
  2794. end;
  2795. end;
  2796. $01:
  2797. begin
  2798. limits.HasMax:=True;
  2799. if not ReadUleb32(limits.min) then
  2800. begin
  2801. InputError('Error reading table limits min for table import');
  2802. exit;
  2803. end;
  2804. if not ReadUleb32(limits.max) then
  2805. begin
  2806. InputError('Error reading table limits max for table import');
  2807. exit;
  2808. end;
  2809. if limits.min>limits.max then
  2810. begin
  2811. InputError('Table limits min exceed table limits max in table import');
  2812. exit;
  2813. end;
  2814. end;
  2815. else
  2816. begin
  2817. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2818. exit;
  2819. end;
  2820. end;
  2821. end;
  2822. end;
  2823. $02: { mem }
  2824. begin
  2825. Inc(MemTypeImportsCount);
  2826. SetLength(MemTypes,MemTypeImportsCount);
  2827. with MemTypes[MemTypeImportsCount-1] do
  2828. begin
  2829. IsImport:=True;
  2830. ImportName:=Name;
  2831. ImportModName:=ModName;
  2832. if not AReader.read(MemoryLimitsKind,1) then
  2833. begin
  2834. InputError('Error reading memory limits kind for memory import');
  2835. exit;
  2836. end;
  2837. case MemoryLimitsKind of
  2838. $00:
  2839. begin
  2840. limits.HasMax:=False;
  2841. limits.Max:=high(limits.Max);
  2842. if not ReadUleb32(limits.min) then
  2843. begin
  2844. InputError('Error reading memory limits min for memory import');
  2845. exit;
  2846. end;
  2847. end;
  2848. $01:
  2849. begin
  2850. limits.HasMax:=True;
  2851. if not ReadUleb32(limits.min) then
  2852. begin
  2853. InputError('Error reading memory limits min for memory import');
  2854. exit;
  2855. end;
  2856. if not ReadUleb32(limits.max) then
  2857. begin
  2858. InputError('Error reading memory limits max for memory import');
  2859. exit;
  2860. end;
  2861. if limits.Min>limits.Max then
  2862. begin
  2863. InputError('Memory limits min exceed memory limits max in memory import');
  2864. exit;
  2865. end;
  2866. end;
  2867. else
  2868. begin
  2869. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2870. exit;
  2871. end;
  2872. end;
  2873. end;
  2874. end;
  2875. $03: { global }
  2876. begin
  2877. Inc(GlobalTypeImportsCount);
  2878. SetLength(GlobalTypes,GlobalTypeImportsCount);
  2879. with GlobalTypes[GlobalTypeImportsCount-1] do
  2880. begin
  2881. IsImport:=True;
  2882. ImportName:=Name;
  2883. ImportModName:=ModName;
  2884. if not AReader.read(GlobalType,1) then
  2885. begin
  2886. InputError('Error reading global type for global import');
  2887. exit;
  2888. end;
  2889. if not decode_wasm_basic_type(GlobalType,valtype) then
  2890. begin
  2891. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  2892. exit;
  2893. end;
  2894. if not AReader.read(GlobalMutabilityType,1) then
  2895. begin
  2896. InputError('Error reading global mutability flag for global import');
  2897. exit;
  2898. end;
  2899. case GlobalMutabilityType of
  2900. $00:
  2901. IsMutable:=False;
  2902. $01:
  2903. IsMutable:=True;
  2904. else
  2905. begin
  2906. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  2907. exit;
  2908. end;
  2909. end;
  2910. end;
  2911. end;
  2912. else
  2913. begin
  2914. InputError('Unknown import type: $' + HexStr(ImportType,2));
  2915. exit;
  2916. end;
  2917. end;
  2918. end;
  2919. if AReader.Pos<>(SectionStart+SectionSize) then
  2920. begin
  2921. InputError('Unexpected import section size');
  2922. exit;
  2923. end;
  2924. Result:=true;
  2925. end;
  2926. function ReadFunctionSection: Boolean;
  2927. var
  2928. FunctionsCount: uint32;
  2929. i: Integer;
  2930. begin
  2931. Result:=False;
  2932. if FunctionSectionRead then
  2933. begin
  2934. InputError('Function section is duplicated');
  2935. exit;
  2936. end;
  2937. FunctionSectionRead:=True;
  2938. if not ReadUleb32(FunctionsCount) then
  2939. begin
  2940. InputError('Error reading the functions count');
  2941. exit;
  2942. end;
  2943. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  2944. for i:=0 to FunctionsCount-1 do
  2945. with FuncTypes[i + FuncTypeImportsCount] do
  2946. begin
  2947. IsImport:=False;
  2948. if not ReadUleb32(typidx) then
  2949. begin
  2950. InputError('Error reading type index for function');
  2951. exit;
  2952. end;
  2953. if typidx>high(FFuncTypes) then
  2954. begin
  2955. InputError('Type index in the function section exceeds bounds of the types table');
  2956. exit;
  2957. end;
  2958. end;
  2959. if AReader.Pos<>(SectionStart+SectionSize) then
  2960. begin
  2961. InputError('Unexpected function section size');
  2962. exit;
  2963. end;
  2964. Result:=true;
  2965. end;
  2966. function ReadGlobalSection: Boolean;
  2967. function ParseExpr: Boolean;
  2968. var
  2969. B: Byte;
  2970. tmpbuf: array [1..8] of Byte;
  2971. tmpInt32: int32;
  2972. tmpInt64: int64;
  2973. begin
  2974. Result:=False;
  2975. repeat
  2976. if not Read(B, 1) then
  2977. exit;
  2978. case B of
  2979. $0B: { end }
  2980. ;
  2981. $41: { i32.const }
  2982. if not ReadSleb32(tmpInt32) then
  2983. exit;
  2984. $42: { i64.const }
  2985. if not ReadSleb(tmpInt64) then
  2986. exit;
  2987. $43: { f32.const }
  2988. if not Read(tmpbuf, 4) then
  2989. exit;
  2990. $44: { f64.const }
  2991. if not Read(tmpbuf, 8) then
  2992. exit;
  2993. $D0: { ref.null }
  2994. if not Read(tmpbuf, 1) then
  2995. exit;
  2996. else
  2997. begin
  2998. InputError('Unsupported opcode in global initializer');
  2999. exit;
  3000. end;
  3001. end;
  3002. until b = $0B;
  3003. Result:=True;
  3004. end;
  3005. var
  3006. GlobalsCount: uint32;
  3007. i: Integer;
  3008. vt: Byte;
  3009. mut: Byte;
  3010. begin
  3011. Result:=False;
  3012. if GlobalSectionRead then
  3013. begin
  3014. InputError('Global section is duplicated');
  3015. exit;
  3016. end;
  3017. GlobalSectionRead:=True;
  3018. if not ReadUleb32(GlobalsCount) then
  3019. begin
  3020. InputError('Error reading the globals count from the global section');
  3021. exit;
  3022. end;
  3023. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3024. for i:=0 to GlobalsCount-1 do
  3025. with GlobalTypes[i + GlobalTypeImportsCount] do
  3026. begin
  3027. if not read(vt,1) then
  3028. begin
  3029. InputError('Error reading the type of a global from the global section');
  3030. exit;
  3031. end;
  3032. if not decode_wasm_basic_type(vt,valtype) then
  3033. begin
  3034. InputError('Unsupported type of global in the global section');
  3035. exit;
  3036. end;
  3037. if not read(mut,1) then
  3038. begin
  3039. InputError('Error reading the mutability flag of a global in the global section');
  3040. exit;
  3041. end;
  3042. case mut of
  3043. $00:
  3044. IsMutable:=False;
  3045. $01:
  3046. IsMutable:=True;
  3047. else
  3048. begin
  3049. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3050. exit;
  3051. end;
  3052. end;
  3053. if not ParseExpr then
  3054. begin
  3055. InputError('Error parsing the global initializer expression in the global section');
  3056. exit;
  3057. end;
  3058. end;
  3059. if AReader.Pos<>(SectionStart+SectionSize) then
  3060. begin
  3061. InputError('Unexpected global section size');
  3062. exit;
  3063. end;
  3064. Result:=True;
  3065. end;
  3066. function ReadExportSection: Boolean;
  3067. var
  3068. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx: uint32;
  3069. i: Integer;
  3070. Name: ansistring;
  3071. ExportType: Byte;
  3072. begin
  3073. Result:=False;
  3074. if ExportSectionRead then
  3075. begin
  3076. InputError('Export section is duplicated');
  3077. exit;
  3078. end;
  3079. ExportSectionRead:=True;
  3080. if not ReadUleb32(ExportsCount) then
  3081. begin
  3082. InputError('Error reading the exports count from the export section');
  3083. exit;
  3084. end;
  3085. for i:=0 to ExportsCount-1 do
  3086. begin
  3087. if not ReadName(Name) then
  3088. begin
  3089. InputError('Error reading an export name from the export section');
  3090. exit;
  3091. end;
  3092. if not Read(ExportType,1) then
  3093. begin
  3094. InputError('Error reading an export type from the export section');
  3095. exit;
  3096. end;
  3097. case ExportType of
  3098. $00: { func }
  3099. begin
  3100. if not ReadUleb32(FuncIdx) then
  3101. begin
  3102. InputError('Error reading a func index from the export section');
  3103. exit;
  3104. end;
  3105. if FuncIdx>high(FuncTypes) then
  3106. begin
  3107. InputError('Func index too high in the export section');
  3108. exit;
  3109. end;
  3110. with FuncTypes[FuncIdx] do
  3111. begin
  3112. IsExported:=True;
  3113. ExportName:=Name;
  3114. end;
  3115. end;
  3116. $01: { table }
  3117. begin
  3118. if not ReadUleb32(TableIdx) then
  3119. begin
  3120. InputError('Error reading a table index from the export section');
  3121. exit;
  3122. end;
  3123. if TableIdx>high(TableTypes) then
  3124. begin
  3125. InputError('Table index too high in the export section');
  3126. exit;
  3127. end;
  3128. with TableTypes[TableIdx] do
  3129. begin
  3130. IsExported:=True;
  3131. ExportName:=Name;
  3132. end;
  3133. end;
  3134. $02: { mem }
  3135. begin
  3136. if not ReadUleb32(MemIdx) then
  3137. begin
  3138. InputError('Error reading a mem index from the export section');
  3139. exit;
  3140. end;
  3141. if MemIdx>high(MemTypes) then
  3142. begin
  3143. InputError('Mem index too high in the export section');
  3144. exit;
  3145. end;
  3146. with MemTypes[MemIdx] do
  3147. begin
  3148. IsExported:=True;
  3149. ExportName:=Name;
  3150. end;
  3151. end;
  3152. $03: { global }
  3153. begin
  3154. if not ReadUleb32(GlobalIdx) then
  3155. begin
  3156. InputError('Error reading a global index from the export section');
  3157. exit;
  3158. end;
  3159. if GlobalIdx>high(GlobalTypes) then
  3160. begin
  3161. InputError('Global index too high in the export section');
  3162. exit;
  3163. end;
  3164. with GlobalTypes[GlobalIdx] do
  3165. begin
  3166. IsExported:=True;
  3167. ExportName:=Name;
  3168. end;
  3169. end;
  3170. else
  3171. begin
  3172. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3173. exit;
  3174. end;
  3175. end;
  3176. end;
  3177. if AReader.Pos<>(SectionStart+SectionSize) then
  3178. begin
  3179. InputError('Unexpected export section size');
  3180. exit;
  3181. end;
  3182. Result:=True;
  3183. end;
  3184. function ReadCodeSection: Boolean;
  3185. var
  3186. CodeEntriesCount: uint32;
  3187. i: Integer;
  3188. begin
  3189. Result:=False;
  3190. if CodeSectionRead then
  3191. begin
  3192. InputError('Code section is duplicated');
  3193. exit;
  3194. end;
  3195. CodeSectionRead:=True;
  3196. CodeSectionIndex:=SectionIndex;
  3197. if not ReadUleb32(CodeEntriesCount) then
  3198. begin
  3199. InputError('Error reading the code entries cound from the code section');
  3200. exit;
  3201. end;
  3202. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3203. begin
  3204. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3205. exit;
  3206. end;
  3207. SetLength(CodeSegments,CodeEntriesCount);
  3208. for i:=0 to CodeEntriesCount-1 do
  3209. with CodeSegments[i] do
  3210. begin
  3211. if not ReadUleb32(CodeSize) then
  3212. begin
  3213. InputError('Error reading the code size of an entry in the code section');
  3214. exit;
  3215. end;
  3216. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3217. begin
  3218. InputError('Code segment exceeds the bounds of the code section');
  3219. exit;
  3220. end;
  3221. DataPos:=AReader.Pos;
  3222. CodeSectionOffset:=AReader.Pos-SectionStart;
  3223. AReader.Seek(AReader.Pos+CodeSize);
  3224. end;
  3225. if AReader.Pos<>(SectionStart+SectionSize) then
  3226. begin
  3227. InputError('Unexpected code section size');
  3228. exit;
  3229. end;
  3230. Result:=true;
  3231. end;
  3232. function ReadDataSection: Boolean;
  3233. function ReadExpr(out ExprV: int32): Boolean;
  3234. var
  3235. b: Byte;
  3236. begin
  3237. Result:=False;
  3238. if not Read(b,1) then
  3239. exit;
  3240. if b<>$41 then
  3241. begin
  3242. InputError('Only i32.const expressions supported');
  3243. exit;
  3244. end;
  3245. if not ReadSleb32(ExprV) then
  3246. exit;
  3247. if not Read(b,1) then
  3248. exit;
  3249. if b<>$0B then
  3250. begin
  3251. InputError('Only single const expressions supported');
  3252. exit;
  3253. end;
  3254. Result:=True;
  3255. end;
  3256. var
  3257. DataCount: uint32;
  3258. DataType: Byte;
  3259. i: Integer;
  3260. begin
  3261. Result:=False;
  3262. if DataSectionRead then
  3263. begin
  3264. InputError('Data section is duplicated');
  3265. exit;
  3266. end;
  3267. DataSectionRead:=True;
  3268. DataSectionIndex:=SectionIndex;
  3269. if not ReadUleb32(DataCount) then
  3270. begin
  3271. InputError('Error reading the data entries count from the data section');
  3272. exit;
  3273. end;
  3274. if DataCountSectionRead then
  3275. begin
  3276. if Length(DataSegments)<>DataCount then
  3277. begin
  3278. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3279. exit;
  3280. end;
  3281. end
  3282. else
  3283. SetLength(DataSegments,DataCount);
  3284. for i:=0 to DataCount-1 do
  3285. with DataSegments[i] do
  3286. begin
  3287. if not read(DataType, 1) then
  3288. begin
  3289. InputError('Error reading data type of segment from the data section');
  3290. exit;
  3291. end;
  3292. case DataType of
  3293. 0:
  3294. begin
  3295. Active:=True;
  3296. MemIdx:=0;
  3297. if not ReadExpr(Offset) then
  3298. begin
  3299. InputError('Error reading memory offset of segment from the data section');
  3300. exit;
  3301. end;
  3302. end;
  3303. 1:
  3304. Active:=False;
  3305. 2:
  3306. begin
  3307. Active:=True;
  3308. if not ReadUleb32(MemIdx) then
  3309. begin
  3310. InputError('Error reading MemIdx of segment from the data section');
  3311. exit;
  3312. end;
  3313. if not ReadExpr(Offset) then
  3314. begin
  3315. InputError('Error reading memory offset of segment from the data section');
  3316. exit;
  3317. end;
  3318. end;
  3319. else
  3320. begin
  3321. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3322. exit;
  3323. end;
  3324. end;
  3325. if MemIdx<>0 then
  3326. begin
  3327. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3328. exit;
  3329. end;
  3330. if not Active then
  3331. begin
  3332. InputError('Passive memory segments not supported');
  3333. exit;
  3334. end;
  3335. if not ReadUleb32(Len) then
  3336. begin
  3337. InputError('Error reading data segment length');
  3338. exit;
  3339. end;
  3340. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3341. begin
  3342. InputError('Data segment exceeds the bounds of the data section');
  3343. exit;
  3344. end;
  3345. DataPos:=AReader.Pos;
  3346. DataSectionOffset:=AReader.Pos-SectionStart;
  3347. AReader.Seek(AReader.Pos+Len);
  3348. end;
  3349. if AReader.Pos<>(SectionStart+SectionSize) then
  3350. begin
  3351. InputError('Unexpected data section size');
  3352. exit;
  3353. end;
  3354. Result:=true;
  3355. end;
  3356. function ReadDataCountSection: Boolean;
  3357. var
  3358. DataCount: uint32;
  3359. begin
  3360. Result:=False;
  3361. if DataCountSectionRead then
  3362. begin
  3363. InputError('Data count section is duplicated');
  3364. exit;
  3365. end;
  3366. DataCountSectionRead:=True;
  3367. if DataSectionRead then
  3368. begin
  3369. InputError('The data count section must occur before the data section');
  3370. exit;
  3371. end;
  3372. if not ReadUleb32(DataCount) then
  3373. begin
  3374. InputError('Error reading the data count from the data count section');
  3375. exit;
  3376. end;
  3377. if AReader.Pos<>(SectionStart+SectionSize) then
  3378. begin
  3379. InputError('Unexpected data count section size');
  3380. exit;
  3381. end;
  3382. SetLength(DataSegments, DataCount);
  3383. Result:=true;
  3384. end;
  3385. begin
  3386. Result:=False;
  3387. Inc(SectionIndex);
  3388. if not AReader.read(SectionId,1) then
  3389. begin
  3390. InputError('Error reading section ID');
  3391. exit;
  3392. end;
  3393. CheckSectionBounds:=false;
  3394. if not ReadUleb32(SectionSize) then
  3395. begin
  3396. InputError('Error reading section size');
  3397. exit;
  3398. end;
  3399. if (AReader.Pos+SectionSize)>AReader.size then
  3400. begin
  3401. InputError('Section exceeds beyond the end of file');
  3402. exit;
  3403. end;
  3404. SectionStart:=AReader.Pos;
  3405. CheckSectionBounds:=true;
  3406. case SectionId of
  3407. Byte(wsiCustom):
  3408. if not ReadCustomSection then
  3409. begin
  3410. InputError('Error encountered, while reading a custom section');
  3411. exit;
  3412. end;
  3413. Byte(wsiType):
  3414. if not ReadTypeSection then
  3415. begin
  3416. InputError('Error reading the type section');
  3417. exit;
  3418. end;
  3419. Byte(wsiImport):
  3420. if not ReadImportSection then
  3421. begin
  3422. InputError('Error reading the import section');
  3423. exit;
  3424. end;
  3425. Byte(wsiFunction):
  3426. if not ReadFunctionSection then
  3427. begin
  3428. InputError('Error reading the function section');
  3429. exit;
  3430. end;
  3431. Byte(wsiGlobal):
  3432. if not ReadGlobalSection then
  3433. begin
  3434. InputError('Error reading the global section');
  3435. exit;
  3436. end;
  3437. Byte(wsiExport):
  3438. if not ReadExportSection then
  3439. begin
  3440. InputError('Error reading the export section');
  3441. exit;
  3442. end;
  3443. Byte(wsiCode):
  3444. if not ReadCodeSection then
  3445. begin
  3446. InputError('Error reading the code section');
  3447. exit;
  3448. end;
  3449. Byte(wsiData):
  3450. if not ReadDataSection then
  3451. begin
  3452. InputError('Error reading the data section');
  3453. exit;
  3454. end;
  3455. Byte(wsiDataCount):
  3456. begin
  3457. if not ReadDataCountSection then
  3458. begin
  3459. InputError('Error reading the data count section');
  3460. exit;
  3461. end;
  3462. end
  3463. else
  3464. begin
  3465. InputError('Unknown section: ' + ToStr(SectionId));
  3466. exit;
  3467. end;
  3468. end;
  3469. if SectionSize>0 then
  3470. AReader.seek(SectionStart+SectionSize);
  3471. Result:=True;
  3472. end;
  3473. function FindCodeSegment(Ofs: uint32): Integer;
  3474. var
  3475. L, R, M: Integer;
  3476. begin
  3477. L:=Low(CodeSegments);
  3478. R:=High(CodeSegments);
  3479. while L<=R do
  3480. begin
  3481. M:=(L+R) div 2;
  3482. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  3483. L:=M+1
  3484. else if CodeSegments[M].CodeSectionOffset > Ofs then
  3485. R:=M-1
  3486. else
  3487. begin
  3488. Result:=M;
  3489. exit;
  3490. end;
  3491. end;
  3492. Result:=-1;
  3493. end;
  3494. function FindDataSegment(Ofs: uint32): Integer;
  3495. var
  3496. L, R, M: Integer;
  3497. begin
  3498. L:=Low(DataSegments);
  3499. R:=High(DataSegments);
  3500. while L<=R do
  3501. begin
  3502. M:=(L+R) div 2;
  3503. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  3504. L:=M+1
  3505. else if DataSegments[M].DataSectionOffset > Ofs then
  3506. R:=M-1
  3507. else
  3508. begin
  3509. Result:=M;
  3510. exit;
  3511. end;
  3512. end;
  3513. Result:=-1;
  3514. end;
  3515. var
  3516. ModuleMagic: array [0..3] of Byte;
  3517. ModuleVersion: array [0..3] of Byte;
  3518. i, j, FirstDataSegmentIdx, SegI: Integer;
  3519. CurrSec, ObjSec: TObjSection;
  3520. BaseSectionOffset: UInt32;
  3521. ObjReloc: TWasmObjRelocation;
  3522. begin
  3523. FReader:=AReader;
  3524. InputFileName:=AReader.FileName;
  3525. objdata:=CObjData.Create(InputFileName);
  3526. result:=false;
  3527. CodeSegments:=nil;
  3528. DataSegments:=nil;
  3529. SymbolTable:=nil;
  3530. RelocationTable:=nil;
  3531. SetLength(RelocationTable,2);
  3532. FuncTypes:=nil;
  3533. FuncTypeImportsCount:=0;
  3534. TableTypes:=nil;
  3535. TableTypeImportsCount:=0;
  3536. MemTypes:=nil;
  3537. MemTypeImportsCount:=0;
  3538. GlobalTypes:=nil;
  3539. GlobalTypeImportsCount:=0;
  3540. if not AReader.read(ModuleMagic,4) then
  3541. exit;
  3542. for i:=0 to 3 do
  3543. if ModuleMagic[i]<>WasmModuleMagic[i] then
  3544. exit;
  3545. if not AReader.read(ModuleVersion,4) then
  3546. exit;
  3547. for i:=0 to 3 do
  3548. if ModuleVersion[i]<>WasmVersion[i] then
  3549. exit;
  3550. while AReader.Pos<AReader.size do
  3551. if not ReadSection then
  3552. exit;
  3553. { fill the code segment names }
  3554. for i:=low(SymbolTable) to high(SymbolTable) do
  3555. with SymbolTable[i] do
  3556. if (SymKind=byte(SYMTAB_FUNCTION)) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  3557. begin
  3558. if FuncTypes[SymIndex].IsImport then
  3559. begin
  3560. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  3561. exit;
  3562. end;
  3563. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  3564. begin
  3565. SegName:='.text.n_'+SymName;
  3566. SegIsExported:=FuncTypes[SymIndex].IsExported;
  3567. end;
  3568. end;
  3569. { create segments }
  3570. for i:=low(CodeSegments) to high(CodeSegments) do
  3571. with CodeSegments[i] do
  3572. begin
  3573. if SegIsExported then
  3574. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  3575. else
  3576. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  3577. CurrSec.DataPos:=DataPos;
  3578. CurrSec.Size:=CodeSize;
  3579. end;
  3580. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  3581. for i:=low(DataSegments) to high(DataSegments) do
  3582. with DataSegments[i] do
  3583. if Active then
  3584. begin
  3585. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  3586. CurrSec.DataPos:=DataPos;
  3587. CurrSec.MemPos:=Offset;
  3588. CurrSec.Size:=Len;
  3589. end;
  3590. ReadSectionContent(ObjData);
  3591. for i:=low(SymbolTable) to high(SymbolTable) do
  3592. with SymbolTable[i] do
  3593. case SymKind of
  3594. byte(SYMTAB_DATA):
  3595. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3596. begin
  3597. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3598. objsym.bind:=AB_EXTERNAL;
  3599. objsym.typ:=AT_DATA;
  3600. objsym.objsection:=nil;
  3601. objsym.offset:=0;
  3602. objsym.size:=0;
  3603. end
  3604. else
  3605. begin
  3606. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3607. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  3608. objsym.bind:=AB_LOCAL
  3609. else
  3610. objsym.bind:=AB_GLOBAL;
  3611. objsym.typ:=AT_DATA;
  3612. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  3613. objsym.offset:=SymOffset;
  3614. objsym.size:=SymSize;
  3615. end;
  3616. byte(SYMTAB_FUNCTION):
  3617. begin
  3618. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3619. begin
  3620. if not FuncTypes[SymIndex].IsImport then
  3621. begin
  3622. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  3623. exit;
  3624. end;
  3625. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3626. begin
  3627. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3628. objsym.bind:=AB_EXTERNAL;
  3629. objsym.typ:=AT_FUNCTION;
  3630. objsym.objsection:=nil;
  3631. objsym.offset:=0;
  3632. objsym.size:=0;
  3633. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  3634. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  3635. end
  3636. else
  3637. begin
  3638. if FuncTypes[SymIndex].ImportModName = 'env' then
  3639. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  3640. else
  3641. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  3642. objsym.bind:=AB_EXTERNAL;
  3643. objsym.typ:=AT_FUNCTION;
  3644. objsym.objsection:=nil;
  3645. objsym.offset:=0;
  3646. objsym.size:=0;
  3647. end;
  3648. end
  3649. else
  3650. begin
  3651. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3652. objsym.bind:=AB_GLOBAL;
  3653. objsym.typ:=AT_FUNCTION;
  3654. objsym.objsection:=TObjSection(ObjData.ObjSectionList[SymIndex-FuncTypeImportsCount]);
  3655. objsym.offset:=0;
  3656. objsym.size:=objsym.objsection.Size;
  3657. end;
  3658. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  3659. end;
  3660. byte(SYMTAB_GLOBAL),
  3661. byte(SYMTAB_SECTION),
  3662. byte(SYMTAB_EVENT),
  3663. byte(SYMTAB_TABLE):
  3664. {TODO};
  3665. else
  3666. internalerror(2023122701);
  3667. end;
  3668. for j:=0 to high(RelocationTable) do
  3669. for i:=0 to high(RelocationTable[j]) do
  3670. with RelocationTable[j,i] do
  3671. begin
  3672. case j of
  3673. 0:
  3674. begin
  3675. SegI:=FindCodeSegment(RelocOffset);
  3676. if SegI=-1 then
  3677. begin
  3678. InputError('Relocation offset not found in code segment');
  3679. Exit;
  3680. end;
  3681. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  3682. ObjSec:=TObjSection(ObjData.ObjSectionList[SegI]);
  3683. end;
  3684. 1:
  3685. begin
  3686. SegI:=FindDataSegment(RelocOffset);
  3687. if SegI=-1 then
  3688. begin
  3689. InputError('Relocation offset not found in data segment');
  3690. Exit;
  3691. end;
  3692. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  3693. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  3694. end
  3695. else
  3696. internalerror(2023122801);
  3697. end;
  3698. case TWasmRelocationType(RelocType) of
  3699. R_WASM_FUNCTION_INDEX_LEB:
  3700. begin
  3701. if RelocIndex>high(SymbolTable) then
  3702. begin
  3703. InputError('Symbol index in relocation too high');
  3704. exit;
  3705. end;
  3706. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3707. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB))
  3708. else
  3709. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3710. end;
  3711. R_WASM_TABLE_INDEX_SLEB:
  3712. begin
  3713. if RelocIndex>high(SymbolTable) then
  3714. begin
  3715. InputError('Symbol index in relocation too high');
  3716. exit;
  3717. end;
  3718. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3719. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB))
  3720. else
  3721. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3722. end;
  3723. R_WASM_TABLE_INDEX_I32:
  3724. begin
  3725. if RelocIndex>high(SymbolTable) then
  3726. begin
  3727. InputError('Symbol index in relocation too high');
  3728. exit;
  3729. end;
  3730. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3731. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE))
  3732. else
  3733. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3734. end;
  3735. R_WASM_MEMORY_ADDR_LEB:
  3736. begin
  3737. if RelocIndex>high(SymbolTable) then
  3738. begin
  3739. InputError('Symbol index in relocation too high');
  3740. exit;
  3741. end;
  3742. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3743. begin
  3744. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  3745. ObjReloc.Addend:=RelocAddend;
  3746. ObjSec.ObjRelocations.Add(ObjReloc);
  3747. end
  3748. else
  3749. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3750. end;
  3751. R_WASM_MEMORY_ADDR_SLEB:
  3752. begin
  3753. if RelocIndex>high(SymbolTable) then
  3754. begin
  3755. InputError('Symbol index in relocation too high');
  3756. exit;
  3757. end;
  3758. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3759. begin
  3760. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  3761. ObjReloc.Addend:=RelocAddend;
  3762. ObjSec.ObjRelocations.Add(ObjReloc);
  3763. end
  3764. else
  3765. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3766. end;
  3767. R_WASM_MEMORY_ADDR_I32:
  3768. begin
  3769. if RelocIndex>high(SymbolTable) then
  3770. begin
  3771. InputError('Symbol index in relocation too high');
  3772. exit;
  3773. end;
  3774. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3775. begin
  3776. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  3777. ObjReloc.Addend:=RelocAddend;
  3778. ObjSec.ObjRelocations.Add(ObjReloc);
  3779. end
  3780. else
  3781. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3782. end;
  3783. R_WASM_TYPE_INDEX_LEB:
  3784. begin
  3785. if RelocIndex>high(FFuncTypes) then
  3786. begin
  3787. InputError('Type index in relocation too high');
  3788. exit;
  3789. end;
  3790. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateTypeIndex(RelocOffset-BaseSectionOffset,RelocIndex));
  3791. end;
  3792. R_WASM_FUNCTION_OFFSET_I32:
  3793. begin
  3794. if RelocIndex>high(SymbolTable) then
  3795. begin
  3796. InputError('Symbol index in relocation too high');
  3797. exit;
  3798. end;
  3799. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3800. begin
  3801. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  3802. ObjReloc.Addend:=RelocAddend;
  3803. ObjSec.ObjRelocations.Add(ObjReloc);
  3804. end
  3805. else
  3806. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3807. end;
  3808. R_WASM_SECTION_OFFSET_I32,
  3809. R_WASM_GLOBAL_INDEX_LEB,
  3810. R_WASM_TAG_INDEX_LEB:
  3811. {TODO};
  3812. else
  3813. internalerror(2023122802);
  3814. end;
  3815. end;
  3816. Result:=True;
  3817. end;
  3818. {****************************************************************************
  3819. TWasmExeOutput
  3820. ****************************************************************************}
  3821. function TWasmExeOutput.writeData: boolean;
  3822. begin
  3823. result:=false;
  3824. {TODO: implement}
  3825. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  3826. Writer.write(WasmVersion,SizeOf(WasmVersion));
  3827. result := true;
  3828. end;
  3829. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  3830. begin
  3831. {TODO: implement}
  3832. end;
  3833. constructor TWasmExeOutput.create;
  3834. begin
  3835. inherited create;
  3836. CObjData:=TWasmObjData;
  3837. MaxMemPos:=$FFFFFFFF;
  3838. FFuncTypes:=TWasmFuncTypeTable.Create;
  3839. end;
  3840. destructor TWasmExeOutput.destroy;
  3841. var
  3842. i: TWasmSectionID;
  3843. begin
  3844. for i in TWasmSectionID do
  3845. FWasmSections[i].Free;
  3846. FFuncTypes.Free;
  3847. inherited destroy;
  3848. end;
  3849. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  3850. var
  3851. i, j: Integer;
  3852. ImportLibrary: TImportLibrary;
  3853. ImportSymbol: TImportSymbol;
  3854. exesym: TExeSymbol;
  3855. begin
  3856. { Here map import symbols to exe symbols and create necessary sections.
  3857. Actual import generation is done after unused sections (and symbols) are removed. }
  3858. FImports:=ImportLibraryList;
  3859. for i:=0 to ImportLibraryList.Count-1 do
  3860. begin
  3861. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  3862. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  3863. begin
  3864. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  3865. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  3866. if assigned(exesym) and
  3867. (exesym.State<>symstate_defined) then
  3868. begin
  3869. ImportSymbol.CachedExeSymbol:=exesym;
  3870. exesym.State:=symstate_defined;
  3871. end;
  3872. end;
  3873. end;
  3874. PackUnresolvedExeSymbols('after module imports');
  3875. end;
  3876. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  3877. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  3878. begin
  3879. if assigned(exemap) then
  3880. exemap.Add(' Importing Function ' + symname + functype.ToString);
  3881. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  3882. Result:=High(FFunctionImports);
  3883. with FFunctionImports[Result] do
  3884. begin
  3885. ModName:=libname;
  3886. Name:=symname;
  3887. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  3888. end;
  3889. end;
  3890. var
  3891. i, j: Integer;
  3892. ImportLibrary: TImportLibrary;
  3893. ImportSymbol: TImportSymbol;
  3894. exesym: TExeSymbol;
  3895. newdll: Boolean;
  3896. begin
  3897. for i:=0 to FImports.Count-1 do
  3898. begin
  3899. ImportLibrary:=TImportLibrary(FImports[i]);
  3900. newdll:=False;
  3901. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  3902. begin
  3903. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  3904. exesym:=ImportSymbol.CachedExeSymbol;
  3905. if assigned(exesym) and
  3906. exesym.Used then
  3907. begin
  3908. if (not newdll) and assigned(exemap) then
  3909. begin
  3910. exemap.Add('');
  3911. exemap.Add('Importing from module '+ImportLibrary.Name);
  3912. end;
  3913. newdll:=True;
  3914. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  3915. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  3916. end;
  3917. end;
  3918. end;
  3919. end;
  3920. {****************************************************************************
  3921. TWasmAssembler
  3922. ****************************************************************************}
  3923. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  3924. begin
  3925. inherited;
  3926. CObjOutput:=TWasmObjOutput;
  3927. end;
  3928. {*****************************************************************************
  3929. Initialize
  3930. *****************************************************************************}
  3931. {$ifdef wasm32}
  3932. const
  3933. as_wasm32_wasm_info : tasminfo =
  3934. (
  3935. id : as_wasm32_wasm;
  3936. idtxt : 'WASM';
  3937. asmbin : '';
  3938. asmcmd : '';
  3939. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  3940. flags : [af_outputbinary,af_smartlink_sections];
  3941. labelprefix : '..@';
  3942. labelmaxlen : -1;
  3943. comment : '; ';
  3944. dollarsign: '$';
  3945. );
  3946. {$endif wasm32}
  3947. initialization
  3948. {$ifdef wasm32}
  3949. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  3950. {$endif wasm32}
  3951. end.