ogwasm.pas 220 KB

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