ogwasm.pas 180 KB

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