ogwasm.pas 175 KB

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