ogwasm.pas 158 KB

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