2
0

ogwasm.pas 209 KB

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