ogwasm.pas 230 KB

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