ogwasm.pas 205 KB

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