ogwasm.pas 161 KB

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