ogwasm.pas 196 KB

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