ogwasm.pas 237 KB

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