ogwasm.pas 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818
  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. procedure WriteExportSection;
  4192. const
  4193. ExportsCount=1;
  4194. begin
  4195. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4196. { export 0 }
  4197. WriteName(FWasmSections[wsiExport],'memory');
  4198. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4199. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4200. end;
  4201. begin
  4202. result:=false;
  4203. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4204. WriteImportSection;
  4205. WriteCodeSegments;
  4206. WriteDataSegments;
  4207. WriteTableAndElemSections;
  4208. WriteGlobalSection;
  4209. WriteExportSection;
  4210. WriteUleb(FWasmSections[wsiMemory],1);
  4211. WriteByte(FWasmSections[wsiMemory],0);
  4212. WriteUleb(FWasmSections[wsiMemory],2); { todo: fill min memory (pages) }
  4213. {...}
  4214. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4215. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4216. WriteWasmSection(wsiType);
  4217. WriteWasmSection(wsiImport);
  4218. WriteWasmSection(wsiFunction);
  4219. WriteWasmSection(wsiTable);
  4220. WriteWasmSection(wsiMemory);
  4221. WriteWasmSection(wsiGlobal);
  4222. WriteWasmSection(wsiExport);
  4223. WriteWasmSection(wsiElement);
  4224. WriteWasmSection(wsiDataCount);
  4225. WriteWasmSection(wsiCode);
  4226. WriteWasmSection(wsiData);
  4227. result := true;
  4228. end;
  4229. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4230. procedure writeUInt32LE(v: uint32);
  4231. begin
  4232. {$ifdef FPC_BIG_ENDIAN}
  4233. v:=SwapEndian(v);
  4234. {$endif FPC_BIG_ENDIAN}
  4235. objsec.data.write(v,4);
  4236. end;
  4237. var
  4238. i: Integer;
  4239. objreloc: TWasmObjRelocation;
  4240. objsym: TWasmObjSymbol;
  4241. begin
  4242. for i:=0 to objsec.ObjRelocations.Count-1 do
  4243. begin
  4244. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4245. if assigned(objreloc.symbol) then
  4246. begin
  4247. objsym:=TWasmObjSymbol(objreloc.symbol);
  4248. case objreloc.typ of
  4249. RELOC_FUNCTION_INDEX_LEB:
  4250. begin
  4251. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4252. internalerror(2024010103);
  4253. objsec.Data.seek(objreloc.DataOffset);
  4254. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4255. end;
  4256. RELOC_ABSOLUTE:
  4257. begin
  4258. case objsym.typ of
  4259. AT_FUNCTION:
  4260. begin
  4261. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4262. internalerror(2024010103);
  4263. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4264. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4265. objsec.Data.seek(objreloc.DataOffset);
  4266. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4267. end;
  4268. AT_DATA:
  4269. begin
  4270. objsec.Data.seek(objreloc.DataOffset);
  4271. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4272. end;
  4273. else
  4274. internalerror(2024010108);
  4275. end;
  4276. end;
  4277. RELOC_MEMORY_ADDR_LEB:
  4278. begin
  4279. if objsym.typ<>AT_DATA then
  4280. internalerror(2024010109);
  4281. objsec.Data.seek(objreloc.DataOffset);
  4282. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4283. end;
  4284. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  4285. begin
  4286. case objsym.typ of
  4287. AT_FUNCTION:
  4288. begin
  4289. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4290. internalerror(2024010103);
  4291. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4292. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4293. objsec.Data.seek(objreloc.DataOffset);
  4294. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4295. end;
  4296. AT_DATA:
  4297. begin
  4298. objsec.Data.seek(objreloc.DataOffset);
  4299. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4300. end;
  4301. else
  4302. internalerror(2024010110);
  4303. end;
  4304. end;
  4305. RELOC_GLOBAL_INDEX_LEB:
  4306. begin
  4307. if objsym.typ<>AT_WASM_GLOBAL then
  4308. internalerror(2024010111);
  4309. objsec.Data.seek(objreloc.DataOffset);
  4310. WriteUleb5(objsec.Data,UInt32(objsym.offset));
  4311. end;
  4312. else
  4313. Writeln('Symbol relocation not yet implemented! ', objreloc.typ);
  4314. end;
  4315. end
  4316. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  4317. begin
  4318. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  4319. objsec.Data.seek(objreloc.DataOffset);
  4320. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  4321. end
  4322. else
  4323. Writeln('Non-symbol relocation not yet implemented! ', objreloc.typ);
  4324. end;
  4325. end;
  4326. constructor TWasmExeOutput.create;
  4327. var
  4328. i: TWasmSectionID;
  4329. begin
  4330. inherited create;
  4331. CObjData:=TWasmObjData;
  4332. MaxMemPos:=$FFFFFFFF;
  4333. FFuncTypes:=TWasmFuncTypeTable.Create;
  4334. for i in TWasmSectionID do
  4335. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  4336. SetLength(FIndirectFunctionTable,1);
  4337. FIndirectFunctionTable[0].FuncIdx:=-1;
  4338. end;
  4339. destructor TWasmExeOutput.destroy;
  4340. var
  4341. i: TWasmSectionID;
  4342. begin
  4343. for i in TWasmSectionID do
  4344. FWasmSections[i].Free;
  4345. FFuncTypes.Free;
  4346. inherited destroy;
  4347. end;
  4348. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4349. var
  4350. i, j: Integer;
  4351. ImportLibrary: TImportLibrary;
  4352. ImportSymbol: TImportSymbol;
  4353. exesym: TExeSymbol;
  4354. begin
  4355. { Here map import symbols to exe symbols and create necessary sections.
  4356. Actual import generation is done after unused sections (and symbols) are removed. }
  4357. FImports:=ImportLibraryList;
  4358. for i:=0 to ImportLibraryList.Count-1 do
  4359. begin
  4360. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  4361. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4362. begin
  4363. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4364. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4365. if assigned(exesym) and
  4366. (exesym.State<>symstate_defined) then
  4367. begin
  4368. ImportSymbol.CachedExeSymbol:=exesym;
  4369. exesym.State:=symstate_defined;
  4370. end;
  4371. end;
  4372. end;
  4373. PackUnresolvedExeSymbols('after module imports');
  4374. end;
  4375. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  4376. begin
  4377. PrepareImports;
  4378. PrepareFunctions;
  4379. end;
  4380. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  4381. begin
  4382. { WebAssembly is a Harvard architecture.
  4383. Data lives in a separate address space, so start addressing back from 0. }
  4384. if aname='.rodata' then
  4385. CurrMemPos:=0;
  4386. inherited MemPos_ExeSection(aname);
  4387. end;
  4388. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  4389. const
  4390. StackPointerSymStr='__stack_pointer';
  4391. var
  4392. objsym: TWasmObjSymbol;
  4393. begin
  4394. if aname=StackPointerSymStr then
  4395. begin
  4396. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  4397. objsym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  4398. objsym.size:=1;
  4399. objsym.ObjSection.WriteZeros(1);
  4400. TWasmObjSection(objsym.ObjSection).MainFuncSymbol:=objsym;
  4401. objsym.LinkingData.GlobalType:=wbt_i32;
  4402. objsym.LinkingData.GlobalIsMutable:=True;
  4403. objsym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  4404. objsym.LinkingData.GlobalInitializer.init_i32:=0;
  4405. end
  4406. else
  4407. inherited;
  4408. end;
  4409. procedure TWasmExeOutput.PrepareImports;
  4410. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  4411. begin
  4412. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  4413. Result:=High(FFunctionImports);
  4414. if assigned(exemap) then
  4415. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  4416. with FFunctionImports[Result] do
  4417. begin
  4418. ModName:=libname;
  4419. Name:=symname;
  4420. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  4421. end;
  4422. end;
  4423. var
  4424. i, j: Integer;
  4425. ImportLibrary: TImportLibrary;
  4426. ImportSymbol: TImportSymbol;
  4427. exesym: TExeSymbol;
  4428. newdll: Boolean;
  4429. begin
  4430. for i:=0 to FImports.Count-1 do
  4431. begin
  4432. ImportLibrary:=TImportLibrary(FImports[i]);
  4433. newdll:=False;
  4434. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4435. begin
  4436. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4437. exesym:=ImportSymbol.CachedExeSymbol;
  4438. if assigned(exesym) and
  4439. exesym.Used then
  4440. begin
  4441. if (not newdll) and assigned(exemap) then
  4442. begin
  4443. exemap.Add('');
  4444. exemap.Add('Importing from module '+ImportLibrary.Name);
  4445. end;
  4446. newdll:=True;
  4447. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  4448. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  4449. end;
  4450. end;
  4451. end;
  4452. end;
  4453. procedure TWasmExeOutput.PrepareFunctions;
  4454. var
  4455. i, j: Integer;
  4456. exesec: TExeSection;
  4457. objsec: TWasmObjSection;
  4458. fsym: TWasmObjSymbol;
  4459. objdata: TObjData;
  4460. begin
  4461. if assigned(exemap) then
  4462. begin
  4463. exemap.Add('');
  4464. exemap.Add('Functions, defined in this module:');
  4465. end;
  4466. exesec:=FindExeSection('.text');
  4467. if not assigned(exesec) then
  4468. internalerror(2023123106);
  4469. for i:=0 to exesec.ObjSectionList.Count-1 do
  4470. begin
  4471. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4472. fsym:=objsec.MainFuncSymbol;
  4473. if not assigned(fsym) then
  4474. internalerror(2023123107);
  4475. if not assigned(fsym.LinkingData.FuncType) then
  4476. internalerror(2023123108);
  4477. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  4478. internalerror(2023123109);
  4479. if fsym.LinkingData.ExeTypeIndex<>-1 then
  4480. internalerror(2023123109);
  4481. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  4482. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  4483. if assigned(exemap) then
  4484. begin
  4485. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  4486. end;
  4487. end;
  4488. { set ExeFunctionIndex to the alias symbols as well }
  4489. for i:=0 to ObjDataList.Count-1 do
  4490. begin
  4491. objdata:=TObjData(ObjDataList[i]);
  4492. for j:=0 to objdata.ObjSymbolList.Count-1 do
  4493. begin
  4494. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  4495. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  4496. begin
  4497. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  4498. if fsym.LinkingData.ExeFunctionIndex=-1 then
  4499. internalerror(2024010102);
  4500. end;
  4501. end;
  4502. end;
  4503. end;
  4504. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  4505. var
  4506. i: Integer;
  4507. begin
  4508. for i:=1 to length(FIndirectFunctionTable)-1 do
  4509. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  4510. begin
  4511. Result:=i;
  4512. exit;
  4513. end;
  4514. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  4515. Result:=High(FIndirectFunctionTable);
  4516. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  4517. end;
  4518. {****************************************************************************
  4519. TWasmAssembler
  4520. ****************************************************************************}
  4521. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  4522. begin
  4523. inherited;
  4524. CObjOutput:=TWasmObjOutput;
  4525. end;
  4526. {*****************************************************************************
  4527. Initialize
  4528. *****************************************************************************}
  4529. {$ifdef wasm32}
  4530. const
  4531. as_wasm32_wasm_info : tasminfo =
  4532. (
  4533. id : as_wasm32_wasm;
  4534. idtxt : 'WASM';
  4535. asmbin : '';
  4536. asmcmd : '';
  4537. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  4538. flags : [af_outputbinary,af_smartlink_sections];
  4539. labelprefix : '..@';
  4540. labelmaxlen : -1;
  4541. comment : '; ';
  4542. dollarsign: '$';
  4543. );
  4544. {$endif wasm32}
  4545. initialization
  4546. {$ifdef wasm32}
  4547. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  4548. {$endif wasm32}
  4549. end.