ogwasm.pas 238 KB

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