ogwasm.pas 156 KB

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