ogwasm.pas 186 KB

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