ogwasm.pas 218 KB

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