ogwasm.pas 196 KB

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