ogwasm.pas 195 KB

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