ogwasm.pas 215 KB

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