ogwasm.pas 232 KB

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