ogwasm.pas 166 KB

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