ogwasm.pas 169 KB

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