ogwasm.pas 215 KB

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