ogwasm.pas 236 KB

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