ogwasm.pas 171 KB

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