ogwasm.pas 236 KB

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