ogwasm.pas 180 KB

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