ogwasm.pas 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050
  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. DebugSectionIndex: array [TWasmCustomDebugSectionType] of Integer = (-1,-1,-1,-1,-1,-1,-1);
  2196. FuncTypes: array of record
  2197. IsImport: Boolean;
  2198. ImportName: ansistring;
  2199. ImportModName: ansistring;
  2200. typidx: uint32;
  2201. IsExported: Boolean;
  2202. ExportName: ansistring;
  2203. end;
  2204. FuncTypeImportsCount: uint32;
  2205. TableTypes: array of record
  2206. IsImport: Boolean;
  2207. ImportName: ansistring;
  2208. ImportModName: ansistring;
  2209. reftype: TWasmBAsicType;
  2210. limits: TLimits;
  2211. IsExported: Boolean;
  2212. ExportName: ansistring;
  2213. end;
  2214. TableTypeImportsCount: uint32;
  2215. MemTypes: array of record
  2216. IsImport: Boolean;
  2217. ImportName: ansistring;
  2218. ImportModName: ansistring;
  2219. limits: TLimits;
  2220. IsExported: Boolean;
  2221. ExportName: ansistring;
  2222. end;
  2223. MemTypeImportsCount: uint32;
  2224. GlobalTypes: array of record
  2225. IsImport: Boolean;
  2226. ImportName: ansistring;
  2227. ImportModName: ansistring;
  2228. valtype: TWasmBasicType;
  2229. IsMutable: Boolean;
  2230. IsExported: Boolean;
  2231. ExportName: ansistring;
  2232. GlobalInit: TGlobalInitializer;
  2233. end;
  2234. GlobalTypeImportsCount: uint32;
  2235. CodeSegments: array of record
  2236. CodeSectionOffset: uint32;
  2237. CodeSize: uint32;
  2238. DataPos: LongInt;
  2239. SegName: ansistring;
  2240. SegIsExported: Boolean;
  2241. end;
  2242. DataSegments: array of record
  2243. DataSectionOffset: uint32;
  2244. Active: Boolean;
  2245. MemIdx: uint32;
  2246. Len: uint32;
  2247. Offset: int32;
  2248. DataPos: LongInt;
  2249. SegName: ansistring;
  2250. SegAlignment: uint32;
  2251. SegFlags: uint32;
  2252. end;
  2253. SymbolTable: array of record
  2254. SymFlags: uint32;
  2255. TargetSection: uint32;
  2256. SymIndex: uint32;
  2257. SymOffset: uint32;
  2258. SymSize: uint32;
  2259. SymKind: TWasmSymbolType;
  2260. SymName: ansistring;
  2261. ObjSym: TWasmObjSymbol;
  2262. ObjSec: TWasmObjSection;
  2263. end;
  2264. { meaning of first index: }
  2265. { table 0 is code relocs }
  2266. { table 1 is data relocs }
  2267. { tables 2.. are custom section relocs for debug sections }
  2268. RelocationTable: array of array of record
  2269. RelocType: TWasmRelocationType;
  2270. RelocOffset: uint32;
  2271. RelocIndex: uint32;
  2272. RelocAddend: int32;
  2273. end;
  2274. function ReadSection: Boolean;
  2275. function read(out b;len:longint):boolean;
  2276. begin
  2277. result:=false;
  2278. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2279. result:=AReader.read(b,len)
  2280. else
  2281. begin
  2282. { trying to read beyond the end of the section }
  2283. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2284. result:=false;
  2285. end;
  2286. end;
  2287. function ReadUleb(out v: uint64): boolean;
  2288. var
  2289. b: byte;
  2290. shift:integer;
  2291. begin
  2292. result:=false;
  2293. b:=0;
  2294. v:=0;
  2295. shift:=0;
  2296. repeat
  2297. if not read(b,1) then
  2298. exit;
  2299. v:=v or (uint64(b and 127) shl shift);
  2300. inc(shift,7);
  2301. until (b and 128)=0;
  2302. result:=true;
  2303. end;
  2304. function ReadUleb32(out v: uint32): boolean;
  2305. var
  2306. vv: uint64;
  2307. begin
  2308. result:=false;
  2309. v:=default(uint32);
  2310. if not ReadUleb(vv) then
  2311. exit;
  2312. if vv>high(uint32) then
  2313. exit;
  2314. v:=vv;
  2315. result:=true;
  2316. end;
  2317. function ReadSleb(out v: int64): boolean;
  2318. var
  2319. b: byte;
  2320. shift:integer;
  2321. begin
  2322. result:=false;
  2323. b:=0;
  2324. v:=0;
  2325. shift:=0;
  2326. repeat
  2327. if not read(b,1) then
  2328. exit;
  2329. v:=v or (uint64(b and 127) shl shift);
  2330. inc(shift,7);
  2331. until (b and 128)=0;
  2332. {$ifopt Q+}
  2333. {$define overflowon}
  2334. {$Q-}
  2335. {$endif}
  2336. {$ifopt R+}
  2337. {$define rangeon}
  2338. {$R-}
  2339. {$endif}
  2340. if (b and 64)<>0 then
  2341. v:=v or (high(uint64) shl shift);
  2342. result:=true;
  2343. end;
  2344. {$ifdef overflowon}
  2345. {$Q+}
  2346. {$undef overflowon}
  2347. {$endif}
  2348. {$ifdef rangeon}
  2349. {$R+}
  2350. {$undef rangeon}
  2351. {$endif}
  2352. function ReadSleb32(out v: int32): boolean;
  2353. var
  2354. vv: int64;
  2355. begin
  2356. result:=false;
  2357. v:=default(int32);
  2358. if not ReadSleb(vv) then
  2359. exit;
  2360. if (vv>high(int32)) or (vv<low(int32)) then
  2361. exit;
  2362. v:=vv;
  2363. result:=true;
  2364. end;
  2365. function ReadName(out v: ansistring): boolean;
  2366. var
  2367. len: uint32;
  2368. begin
  2369. result:=false;
  2370. if not ReadUleb32(len) then
  2371. exit;
  2372. SetLength(v,len);
  2373. if len>0 then
  2374. result:=read(v[1],len)
  2375. else
  2376. result:=true;
  2377. end;
  2378. function ReadCustomSection: Boolean;
  2379. function ReadRelocationSection: Boolean;
  2380. var
  2381. TargetSection, RelocCount: uint32;
  2382. i: Integer;
  2383. RelocTableIndex: Integer;
  2384. ds: TWasmCustomDebugSectionType;
  2385. begin
  2386. Result:=False;
  2387. if not ReadUleb32(TargetSection) then
  2388. begin
  2389. InputError('Error reading the index of the target section of a relocation section');
  2390. exit;
  2391. end;
  2392. if TargetSection=CodeSectionIndex then
  2393. RelocTableIndex:=0
  2394. else if TargetSection=DataSectionIndex then
  2395. RelocTableIndex:=1
  2396. else
  2397. begin
  2398. RelocTableIndex:=-1;
  2399. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  2400. if DebugSectionIndex[ds]=TargetSection then
  2401. begin
  2402. RelocTableIndex:=2+(Ord(ds)-Ord(Low(TWasmCustomDebugSectionType)));
  2403. break;
  2404. end;
  2405. if RelocTableIndex=-1 then
  2406. begin
  2407. InputError('Relocation found for a custom section, that is not supported');
  2408. exit;
  2409. end;
  2410. end;
  2411. if not ReadUleb32(RelocCount) then
  2412. begin
  2413. InputError('Error reading the relocation entries count from a relocation section');
  2414. exit;
  2415. end;
  2416. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2417. for i:=0 to RelocCount-1 do
  2418. with RelocationTable[RelocTableIndex,i] do
  2419. begin
  2420. if not Read(RelocType,1) then
  2421. begin
  2422. InputError('Error reading the relocation type of a relocation entry');
  2423. exit;
  2424. end;
  2425. if not (RelocType in [R_WASM_FUNCTION_INDEX_LEB,
  2426. R_WASM_MEMORY_ADDR_LEB,
  2427. R_WASM_TABLE_INDEX_SLEB,
  2428. R_WASM_MEMORY_ADDR_SLEB,
  2429. R_WASM_SECTION_OFFSET_I32,
  2430. R_WASM_TABLE_INDEX_I32,
  2431. R_WASM_FUNCTION_OFFSET_I32,
  2432. R_WASM_MEMORY_ADDR_I32,
  2433. R_WASM_TYPE_INDEX_LEB,
  2434. R_WASM_GLOBAL_INDEX_LEB,
  2435. R_WASM_TAG_INDEX_LEB]) then
  2436. begin
  2437. InputError('Unsupported relocation type: ' + tostr(Ord(RelocType)));
  2438. exit;
  2439. end;
  2440. if not ReadUleb32(RelocOffset) then
  2441. begin
  2442. InputError('Error reading the relocation offset of a relocation entry');
  2443. exit;
  2444. end;
  2445. if not ReadUleb32(RelocIndex) then
  2446. begin
  2447. InputError('Error reading the relocation index of a relocation entry');
  2448. exit;
  2449. end;
  2450. if 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
  2451. begin
  2452. if not ReadSleb32(RelocAddend) then
  2453. begin
  2454. InputError('Error reading the relocation addend of a relocation entry');
  2455. exit;
  2456. end;
  2457. end;
  2458. if (RelocType in [
  2459. R_WASM_SECTION_OFFSET_I32,
  2460. R_WASM_FUNCTION_INDEX_LEB,
  2461. R_WASM_TABLE_INDEX_SLEB,
  2462. R_WASM_TABLE_INDEX_I32,
  2463. R_WASM_MEMORY_ADDR_LEB,
  2464. R_WASM_MEMORY_ADDR_SLEB,
  2465. R_WASM_MEMORY_ADDR_I32,
  2466. R_WASM_FUNCTION_OFFSET_I32,
  2467. R_WASM_GLOBAL_INDEX_LEB]) and (RelocIndex>High(SymbolTable)) then
  2468. begin
  2469. InputError('Relocation index outside the bounds of the symbol table');
  2470. exit;
  2471. end;
  2472. if (RelocType=R_WASM_TYPE_INDEX_LEB) and (RelocIndex>High(FFuncTypes)) then
  2473. begin
  2474. InputError('Relocation index of R_WASM_TYPE_INDEX_LEB outside the bounds of the func types, defined in the func section of the module');
  2475. exit;
  2476. end;
  2477. if (RelocType=R_WASM_SECTION_OFFSET_I32) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_SECTION) then
  2478. begin
  2479. InputError('R_WASM_SECTION_OFFSET_I32 must point to a SYMTAB_SECTION symbol');
  2480. exit;
  2481. end;
  2482. if (RelocType in [
  2483. R_WASM_FUNCTION_INDEX_LEB,
  2484. R_WASM_TABLE_INDEX_SLEB,
  2485. R_WASM_TABLE_INDEX_I32,
  2486. R_WASM_FUNCTION_OFFSET_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_FUNCTION) then
  2487. begin
  2488. InputError('Relocation must point to a SYMTAB_FUNCTION symbol');
  2489. exit;
  2490. end;
  2491. if (RelocType in [
  2492. R_WASM_MEMORY_ADDR_LEB,
  2493. R_WASM_MEMORY_ADDR_SLEB,
  2494. R_WASM_MEMORY_ADDR_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_DATA) then
  2495. begin
  2496. InputError('Relocation must point to a SYMTAB_DATA symbol');
  2497. exit;
  2498. end;
  2499. end;
  2500. if AReader.Pos<>(SectionStart+SectionSize) then
  2501. begin
  2502. InputError('Unexpected relocation section size');
  2503. exit;
  2504. end;
  2505. Result:=True;
  2506. end;
  2507. function ReadLinkingSection: Boolean;
  2508. function ReadSegmentInfo: Boolean;
  2509. var
  2510. SegmentCount: uint32;
  2511. i: Integer;
  2512. begin
  2513. Result:=False;
  2514. if SegmentInfoSectionRead then
  2515. begin
  2516. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2517. exit;
  2518. end;
  2519. SegmentInfoSectionRead:=True;
  2520. if not ReadUleb32(SegmentCount) then
  2521. begin
  2522. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2523. exit;
  2524. end;
  2525. if SegmentCount<>Length(DataSegments) then
  2526. begin
  2527. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2528. exit;
  2529. end;
  2530. for i:=0 to SegmentCount-1 do
  2531. with DataSegments[i] do
  2532. begin
  2533. if not ReadName(SegName) then
  2534. begin
  2535. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2536. exit;
  2537. end;
  2538. if not ReadUleb32(SegAlignment) then
  2539. begin
  2540. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2541. exit;
  2542. end;
  2543. if not ReadUleb32(SegFlags) then
  2544. begin
  2545. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2546. exit;
  2547. end;
  2548. end;
  2549. if AReader.Pos<>(SectionStart+SectionSize) then
  2550. begin
  2551. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2552. exit;
  2553. end;
  2554. Result:=True;
  2555. end;
  2556. function ReadSymbolTable: Boolean;
  2557. var
  2558. SymCount: uint32;
  2559. i: Integer;
  2560. SymKindName: string;
  2561. SymKindB: Byte;
  2562. begin
  2563. Result:=False;
  2564. if SymbolTableSectionRead then
  2565. begin
  2566. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2567. exit;
  2568. end;
  2569. SymbolTableSectionRead:=True;
  2570. if not ReadUleb32(SymCount) then
  2571. begin
  2572. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2573. exit;
  2574. end;
  2575. SetLength(SymbolTable,SymCount);
  2576. for i:=0 to SymCount-1 do
  2577. with SymbolTable[i] do
  2578. begin
  2579. if not Read(SymKindB,1) then
  2580. begin
  2581. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2582. exit;
  2583. end;
  2584. if (SymKindB<Low(Ord(TWasmSymbolType))) or (SymKindB>High(Ord(TWasmSymbolType))) then
  2585. begin
  2586. InputError('Unsupported symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2587. exit;
  2588. end;
  2589. SymKind:=TWasmSymbolType(SymKindB);
  2590. if not ReadUleb32(SymFlags) then
  2591. begin
  2592. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2593. exit;
  2594. end;
  2595. case SymKind of
  2596. SYMTAB_FUNCTION,
  2597. SYMTAB_GLOBAL,
  2598. SYMTAB_EVENT,
  2599. SYMTAB_TABLE:
  2600. begin
  2601. WriteStr(SymKindName, SymKind);
  2602. if not ReadUleb32(SymIndex) then
  2603. begin
  2604. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2605. exit;
  2606. end;
  2607. if ((SymKind=SYMTAB_FUNCTION) and (SymIndex>high(FuncTypes))) then
  2608. begin
  2609. InputError('Symbol index too high');
  2610. exit;
  2611. end;
  2612. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2613. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2614. begin
  2615. if not ReadName(SymName) then
  2616. begin
  2617. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2618. exit;
  2619. end;
  2620. end;
  2621. end;
  2622. SYMTAB_DATA:
  2623. begin
  2624. if not ReadName(SymName) then
  2625. begin
  2626. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2627. exit;
  2628. end;
  2629. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2630. begin
  2631. if not ReadUleb32(SymIndex) then
  2632. begin
  2633. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2634. exit;
  2635. end;
  2636. if SymIndex>high(DataSegments) then
  2637. begin
  2638. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2639. exit;
  2640. end;
  2641. if not ReadUleb32(SymOffset) then
  2642. begin
  2643. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2644. exit;
  2645. end;
  2646. if not ReadUleb32(SymSize) then
  2647. begin
  2648. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2649. exit;
  2650. end;
  2651. end;
  2652. end;
  2653. SYMTAB_SECTION:
  2654. begin
  2655. if not ReadUleb32(TargetSection) then
  2656. begin
  2657. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2658. exit;
  2659. end;
  2660. end;
  2661. else
  2662. begin
  2663. InputError('Unsupported symbol kind: ' + tostr(Ord(SymKind)));
  2664. exit;
  2665. end;
  2666. end;
  2667. end;
  2668. if AReader.Pos<>(SectionStart+SectionSize) then
  2669. begin
  2670. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2671. exit;
  2672. end;
  2673. Result:=True;
  2674. end;
  2675. const
  2676. ExpectedVersion = 2;
  2677. var
  2678. Version, SubsectionSize, SaveSectionSize: uint32;
  2679. SubsectionType: Byte;
  2680. SaveSectionStart: LongInt;
  2681. begin
  2682. Result:=False;
  2683. if not ReadUleb32(Version) then
  2684. begin
  2685. InputError('Error reading the version of the ''linking'' section');
  2686. exit;
  2687. end;
  2688. if Version<>ExpectedVersion then
  2689. begin
  2690. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2691. exit;
  2692. end;
  2693. while AReader.Pos<(SectionStart+SectionSize) do
  2694. begin
  2695. if not read(SubsectionType, 1) then
  2696. begin
  2697. InputError('Error reading subsection type in the ''linking'' section');
  2698. exit;
  2699. end;
  2700. if not ReadUleb32(SubsectionSize) then
  2701. begin
  2702. InputError('Error reading subsection size in the ''linking'' section');
  2703. exit;
  2704. end;
  2705. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2706. begin
  2707. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2708. exit;
  2709. end;
  2710. SaveSectionStart:=SectionStart;
  2711. SaveSectionSize:=SectionSize;
  2712. SectionStart:=AReader.Pos;
  2713. SectionSize:=SubsectionSize;
  2714. case SubsectionType of
  2715. Byte(WASM_SEGMENT_INFO):
  2716. if not ReadSegmentInfo then
  2717. begin
  2718. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2719. exit;
  2720. end;
  2721. Byte(WASM_SYMBOL_TABLE):
  2722. if not ReadSymbolTable then
  2723. begin
  2724. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2725. exit;
  2726. end;
  2727. else
  2728. begin
  2729. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2730. exit;
  2731. end;
  2732. end;
  2733. AReader.Seek(SectionStart+SectionSize);
  2734. SectionStart:=SaveSectionStart;
  2735. SectionSize:=SaveSectionSize;
  2736. end;
  2737. result:=True;
  2738. end;
  2739. function ReadProducersSection: Boolean;
  2740. begin
  2741. Result:=False;
  2742. end;
  2743. function ReadTargetFeaturesSection: Boolean;
  2744. begin
  2745. Result:=False;
  2746. end;
  2747. function ReadDebugSection(const SectionName: string; SectionType: TWasmCustomDebugSectionType): Boolean;
  2748. var
  2749. ObjSec: TObjSection;
  2750. begin
  2751. Result:=False;
  2752. if DebugSectionIndex[SectionType]<>-1 then
  2753. begin
  2754. InputError('Duplicated debug section: ' + SectionName);
  2755. exit;
  2756. end;
  2757. DebugSectionIndex[SectionType]:=SectionIndex;
  2758. ObjSec:=ObjData.createsection(SectionName,1,[oso_Data,oso_debug],false);
  2759. ObjSec.DataPos:=AReader.Pos;
  2760. ObjSec.Size:=SectionStart+SectionSize-AReader.Pos;
  2761. Result:=True;
  2762. end;
  2763. const
  2764. RelocationSectionPrefix = 'reloc.';
  2765. var
  2766. SectionName: ansistring;
  2767. begin
  2768. Result:=False;
  2769. ReadName(SectionName);
  2770. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2771. begin
  2772. if not ReadRelocationSection then
  2773. begin
  2774. InputError('Error reading the relocation section ''' + SectionName + '''');
  2775. exit;
  2776. end;
  2777. end
  2778. else
  2779. case SectionName of
  2780. 'linking':
  2781. if not ReadLinkingSection then
  2782. begin
  2783. InputError('Error reading the ''linking'' section');
  2784. exit;
  2785. end;
  2786. 'producers':
  2787. Result:=ReadProducersSection;
  2788. 'target_features':
  2789. Result:=ReadTargetFeaturesSection;
  2790. '.debug_frame':
  2791. if not ReadDebugSection(SectionName, wcstDebugFrame) then
  2792. begin
  2793. InputError('Error reading section ' + SectionName);
  2794. exit;
  2795. end;
  2796. '.debug_info':
  2797. if not ReadDebugSection(SectionName, wcstDebugInfo) then
  2798. begin
  2799. InputError('Error reading section ' + SectionName);
  2800. exit;
  2801. end;
  2802. '.debug_line':
  2803. if not ReadDebugSection(SectionName, wcstDebugLine) then
  2804. begin
  2805. InputError('Error reading section ' + SectionName);
  2806. exit;
  2807. end;
  2808. '.debug_abbrev':
  2809. if not ReadDebugSection(SectionName, wcstDebugAbbrev) then
  2810. begin
  2811. InputError('Error reading section ' + SectionName);
  2812. exit;
  2813. end;
  2814. '.debug_aranges':
  2815. if not ReadDebugSection(SectionName, wcstDebugAranges) then
  2816. begin
  2817. InputError('Error reading section ' + SectionName);
  2818. exit;
  2819. end;
  2820. '.debug_ranges':
  2821. if not ReadDebugSection(SectionName, wcstDebugRanges) then
  2822. begin
  2823. InputError('Error reading section ' + SectionName);
  2824. exit;
  2825. end;
  2826. '.debug_str':
  2827. if not ReadDebugSection(SectionName, wcstDebugStr) then
  2828. begin
  2829. InputError('Error reading section ' + SectionName);
  2830. exit;
  2831. end;
  2832. else
  2833. InputError('Unsupported custom section: ''' + SectionName + '''');
  2834. end;
  2835. Result:=True;
  2836. end;
  2837. function ReadTypeSection: Boolean;
  2838. var
  2839. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2840. FuncTypeId, WasmTypeId: Byte;
  2841. i, j: Integer;
  2842. wbt: TWasmBasicType;
  2843. begin
  2844. Result:=False;
  2845. if TypeSectionRead then
  2846. begin
  2847. InputError('Type section is duplicated');
  2848. exit;
  2849. end;
  2850. TypeSectionRead:=True;
  2851. if not ReadUleb32(FuncTypesCount) then
  2852. begin
  2853. InputError('Error reading the func types count');
  2854. exit;
  2855. end;
  2856. SetLength(FFuncTypes,FuncTypesCount);
  2857. for i:=0 to FuncTypesCount - 1 do
  2858. begin
  2859. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2860. if not AReader.read(FuncTypeId,1) then
  2861. begin
  2862. InputError('Error reading the function type identifier');
  2863. exit;
  2864. end;
  2865. if FuncTypeId<>$60 then
  2866. begin
  2867. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2868. exit;
  2869. end;
  2870. if not ReadUleb32(ParamsCount) then
  2871. begin
  2872. InputError('Error reading the function parameters count');
  2873. exit;
  2874. end;
  2875. for j:=0 to ParamsCount-1 do
  2876. begin
  2877. if not AReader.read(WasmTypeId,1) then
  2878. begin
  2879. InputError('Error reading a function parameter basic type');
  2880. exit;
  2881. end;
  2882. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2883. begin
  2884. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2885. exit;
  2886. end;
  2887. FFuncTypes[i].add_param(wbt);
  2888. end;
  2889. if not ReadUleb32(ResultsCount) then
  2890. begin
  2891. InputError('Error reading the function results count');
  2892. exit;
  2893. end;
  2894. for j:=0 to ResultsCount-1 do
  2895. begin
  2896. if not AReader.read(WasmTypeId,1) then
  2897. begin
  2898. InputError('Error reading a function result basic type');
  2899. exit;
  2900. end;
  2901. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2902. begin
  2903. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2904. exit;
  2905. end;
  2906. FFuncTypes[i].add_result(wbt);
  2907. end;
  2908. end;
  2909. if AReader.Pos<>(SectionStart+SectionSize) then
  2910. begin
  2911. InputError('Unexpected type section size');
  2912. exit;
  2913. end;
  2914. Result:=true;
  2915. end;
  2916. function ReadImportSection: Boolean;
  2917. var
  2918. ImportsCount: uint32;
  2919. i: Integer;
  2920. ModName, Name: ansistring;
  2921. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2922. GlobalType, GlobalMutabilityType: Byte;
  2923. begin
  2924. Result:=False;
  2925. if ImportSectionRead then
  2926. begin
  2927. InputError('Import section is duplicated');
  2928. exit;
  2929. end;
  2930. ImportSectionRead:=True;
  2931. if not ReadUleb32(ImportsCount) then
  2932. begin
  2933. InputError('Error reading the imports count');
  2934. exit;
  2935. end;
  2936. for i:=0 to ImportsCount-1 do
  2937. begin
  2938. if not ReadName(ModName) then
  2939. begin
  2940. InputError('Error reading import module name');
  2941. exit;
  2942. end;
  2943. if not ReadName(Name) then
  2944. begin
  2945. InputError('Error import name');
  2946. exit;
  2947. end;
  2948. if not AReader.Read(ImportType,1) then
  2949. begin
  2950. InputError('Error reading import type');
  2951. exit;
  2952. end;
  2953. case ImportType of
  2954. $00: { func }
  2955. begin
  2956. Inc(FuncTypeImportsCount);
  2957. SetLength(FuncTypes,FuncTypeImportsCount);
  2958. with FuncTypes[FuncTypeImportsCount-1] do
  2959. begin
  2960. IsImport:=True;
  2961. ImportName:=Name;
  2962. ImportModName:=ModName;
  2963. if not ReadUleb32(typidx) then
  2964. begin
  2965. InputError('Error reading type index for func import');
  2966. exit;
  2967. end;
  2968. if typidx>high(FFuncTypes) then
  2969. begin
  2970. InputError('Type index in func import exceeds bounds of the types table');
  2971. exit;
  2972. end;
  2973. end;
  2974. end;
  2975. $01: { table }
  2976. begin
  2977. Inc(TableTypeImportsCount);
  2978. SetLength(TableTypes,TableTypeImportsCount);
  2979. with TableTypes[TableTypeImportsCount-1] do
  2980. begin
  2981. IsImport:=True;
  2982. ImportName:=Name;
  2983. ImportModName:=ModName;
  2984. if not AReader.read(TableElemTyp,1) then
  2985. begin
  2986. InputError('Error reading table element type for table import');
  2987. exit;
  2988. end;
  2989. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  2990. begin
  2991. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2992. exit;
  2993. end;
  2994. if not (reftype in WasmReferenceTypes) then
  2995. begin
  2996. InputError('Table element type for table import must be a reference type');
  2997. exit;
  2998. end;
  2999. if not AReader.read(TableLimitsKind,1) then
  3000. begin
  3001. InputError('Error reading table limits kind for table import');
  3002. exit;
  3003. end;
  3004. case TableLimitsKind of
  3005. $00:
  3006. begin
  3007. limits.HasMax:=False;
  3008. limits.Max:=high(limits.Max);
  3009. if not ReadUleb32(limits.min) then
  3010. begin
  3011. InputError('Error reading table limits min for table import');
  3012. exit;
  3013. end;
  3014. end;
  3015. $01:
  3016. begin
  3017. limits.HasMax:=True;
  3018. if not ReadUleb32(limits.min) then
  3019. begin
  3020. InputError('Error reading table limits min for table import');
  3021. exit;
  3022. end;
  3023. if not ReadUleb32(limits.max) then
  3024. begin
  3025. InputError('Error reading table limits max for table import');
  3026. exit;
  3027. end;
  3028. if limits.min>limits.max then
  3029. begin
  3030. InputError('Table limits min exceed table limits max in table import');
  3031. exit;
  3032. end;
  3033. end;
  3034. else
  3035. begin
  3036. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  3037. exit;
  3038. end;
  3039. end;
  3040. end;
  3041. end;
  3042. $02: { mem }
  3043. begin
  3044. Inc(MemTypeImportsCount);
  3045. SetLength(MemTypes,MemTypeImportsCount);
  3046. with MemTypes[MemTypeImportsCount-1] do
  3047. begin
  3048. IsImport:=True;
  3049. ImportName:=Name;
  3050. ImportModName:=ModName;
  3051. if not AReader.read(MemoryLimitsKind,1) then
  3052. begin
  3053. InputError('Error reading memory limits kind for memory import');
  3054. exit;
  3055. end;
  3056. case MemoryLimitsKind of
  3057. $00:
  3058. begin
  3059. limits.HasMax:=False;
  3060. limits.Max:=high(limits.Max);
  3061. if not ReadUleb32(limits.min) then
  3062. begin
  3063. InputError('Error reading memory limits min for memory import');
  3064. exit;
  3065. end;
  3066. end;
  3067. $01:
  3068. begin
  3069. limits.HasMax:=True;
  3070. if not ReadUleb32(limits.min) then
  3071. begin
  3072. InputError('Error reading memory limits min for memory import');
  3073. exit;
  3074. end;
  3075. if not ReadUleb32(limits.max) then
  3076. begin
  3077. InputError('Error reading memory limits max for memory import');
  3078. exit;
  3079. end;
  3080. if limits.Min>limits.Max then
  3081. begin
  3082. InputError('Memory limits min exceed memory limits max in memory import');
  3083. exit;
  3084. end;
  3085. end;
  3086. else
  3087. begin
  3088. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  3089. exit;
  3090. end;
  3091. end;
  3092. end;
  3093. end;
  3094. $03: { global }
  3095. begin
  3096. Inc(GlobalTypeImportsCount);
  3097. SetLength(GlobalTypes,GlobalTypeImportsCount);
  3098. with GlobalTypes[GlobalTypeImportsCount-1] do
  3099. begin
  3100. IsImport:=True;
  3101. ImportName:=Name;
  3102. ImportModName:=ModName;
  3103. if not AReader.read(GlobalType,1) then
  3104. begin
  3105. InputError('Error reading global type for global import');
  3106. exit;
  3107. end;
  3108. if not decode_wasm_basic_type(GlobalType,valtype) then
  3109. begin
  3110. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  3111. exit;
  3112. end;
  3113. if not AReader.read(GlobalMutabilityType,1) then
  3114. begin
  3115. InputError('Error reading global mutability flag for global import');
  3116. exit;
  3117. end;
  3118. case GlobalMutabilityType of
  3119. $00:
  3120. IsMutable:=False;
  3121. $01:
  3122. IsMutable:=True;
  3123. else
  3124. begin
  3125. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  3126. exit;
  3127. end;
  3128. end;
  3129. end;
  3130. end;
  3131. else
  3132. begin
  3133. InputError('Unknown import type: $' + HexStr(ImportType,2));
  3134. exit;
  3135. end;
  3136. end;
  3137. end;
  3138. if AReader.Pos<>(SectionStart+SectionSize) then
  3139. begin
  3140. InputError('Unexpected import section size');
  3141. exit;
  3142. end;
  3143. Result:=true;
  3144. end;
  3145. function ReadFunctionSection: Boolean;
  3146. var
  3147. FunctionsCount: uint32;
  3148. i: Integer;
  3149. begin
  3150. Result:=False;
  3151. if FunctionSectionRead then
  3152. begin
  3153. InputError('Function section is duplicated');
  3154. exit;
  3155. end;
  3156. FunctionSectionRead:=True;
  3157. if not ReadUleb32(FunctionsCount) then
  3158. begin
  3159. InputError('Error reading the functions count');
  3160. exit;
  3161. end;
  3162. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  3163. for i:=0 to FunctionsCount-1 do
  3164. with FuncTypes[i + FuncTypeImportsCount] do
  3165. begin
  3166. IsImport:=False;
  3167. if not ReadUleb32(typidx) then
  3168. begin
  3169. InputError('Error reading type index for function');
  3170. exit;
  3171. end;
  3172. if typidx>high(FFuncTypes) then
  3173. begin
  3174. InputError('Type index in the function section exceeds bounds of the types table');
  3175. exit;
  3176. end;
  3177. end;
  3178. if AReader.Pos<>(SectionStart+SectionSize) then
  3179. begin
  3180. InputError('Unexpected function section size');
  3181. exit;
  3182. end;
  3183. Result:=true;
  3184. end;
  3185. function ReadGlobalSection: Boolean;
  3186. function ParseExpr(out Init: TGlobalInitializer): Boolean;
  3187. var
  3188. B, B2: Byte;
  3189. tmpU32: UInt32;
  3190. tmpU64: UInt64;
  3191. begin
  3192. Result:=False;
  3193. repeat
  3194. if not Read(B, 1) then
  3195. exit;
  3196. case B of
  3197. $0B: { end }
  3198. ;
  3199. $41: { i32.const }
  3200. begin
  3201. Init.typ:=wbt_i32;
  3202. if not ReadSleb32(Init.init_i32) then
  3203. exit;
  3204. end;
  3205. $42: { i64.const }
  3206. begin
  3207. Init.typ:=wbt_i64;
  3208. if not ReadSleb(Init.init_i64) then
  3209. exit;
  3210. end;
  3211. $43: { f32.const }
  3212. begin
  3213. Init.typ:=wbt_f32;
  3214. if not Read(tmpU32, 4) then
  3215. exit;
  3216. {$ifdef FPC_BIG_ENDIAN}
  3217. tmpU32:=SwapEndian(tmpU32);
  3218. {$endif FPC_BIG_ENDIAN}
  3219. Move(tmpU32,Init.init_f32,4);
  3220. end;
  3221. $44: { f64.const }
  3222. begin
  3223. Init.typ:=wbt_f64;
  3224. if not Read(tmpU64, 8) then
  3225. exit;
  3226. {$ifdef FPC_BIG_ENDIAN}
  3227. tmpU64:=SwapEndian(tmpU64);
  3228. {$endif FPC_BIG_ENDIAN}
  3229. Move(tmpU64,Init.init_f64,8);
  3230. end;
  3231. $D0: { ref.null }
  3232. begin
  3233. if not Read(B2, 1) then
  3234. exit;
  3235. if not decode_wasm_basic_type(B2, Init.typ) then
  3236. exit;
  3237. if not (Init.typ in WasmReferenceTypes) then
  3238. exit;
  3239. end;
  3240. else
  3241. begin
  3242. InputError('Unsupported opcode in global initializer');
  3243. exit;
  3244. end;
  3245. end;
  3246. until b = $0B;
  3247. Result:=True;
  3248. end;
  3249. var
  3250. GlobalsCount: uint32;
  3251. i: Integer;
  3252. vt: Byte;
  3253. mut: Byte;
  3254. begin
  3255. Result:=False;
  3256. if GlobalSectionRead then
  3257. begin
  3258. InputError('Global section is duplicated');
  3259. exit;
  3260. end;
  3261. GlobalSectionRead:=True;
  3262. if not ReadUleb32(GlobalsCount) then
  3263. begin
  3264. InputError('Error reading the globals count from the global section');
  3265. exit;
  3266. end;
  3267. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3268. for i:=0 to GlobalsCount-1 do
  3269. with GlobalTypes[i + GlobalTypeImportsCount] do
  3270. begin
  3271. if not read(vt,1) then
  3272. begin
  3273. InputError('Error reading the type of a global from the global section');
  3274. exit;
  3275. end;
  3276. if not decode_wasm_basic_type(vt,valtype) then
  3277. begin
  3278. InputError('Unsupported type of global in the global section');
  3279. exit;
  3280. end;
  3281. if not read(mut,1) then
  3282. begin
  3283. InputError('Error reading the mutability flag of a global in the global section');
  3284. exit;
  3285. end;
  3286. case mut of
  3287. $00:
  3288. IsMutable:=False;
  3289. $01:
  3290. IsMutable:=True;
  3291. else
  3292. begin
  3293. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3294. exit;
  3295. end;
  3296. end;
  3297. if not ParseExpr(GlobalInit) then
  3298. begin
  3299. InputError('Error parsing the global initializer expression in the global section');
  3300. exit;
  3301. end;
  3302. if GlobalInit.typ<>valtype then
  3303. begin
  3304. InputError('Initializer expression for global produces a type, which does not match the type of the global');
  3305. exit;
  3306. end;
  3307. end;
  3308. if AReader.Pos<>(SectionStart+SectionSize) then
  3309. begin
  3310. InputError('Unexpected global section size');
  3311. exit;
  3312. end;
  3313. Result:=True;
  3314. end;
  3315. function ReadExportSection: Boolean;
  3316. var
  3317. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx: uint32;
  3318. i: Integer;
  3319. Name: ansistring;
  3320. ExportType: Byte;
  3321. begin
  3322. Result:=False;
  3323. if ExportSectionRead then
  3324. begin
  3325. InputError('Export section is duplicated');
  3326. exit;
  3327. end;
  3328. ExportSectionRead:=True;
  3329. if not ReadUleb32(ExportsCount) then
  3330. begin
  3331. InputError('Error reading the exports count from the export section');
  3332. exit;
  3333. end;
  3334. for i:=0 to ExportsCount-1 do
  3335. begin
  3336. if not ReadName(Name) then
  3337. begin
  3338. InputError('Error reading an export name from the export section');
  3339. exit;
  3340. end;
  3341. if not Read(ExportType,1) then
  3342. begin
  3343. InputError('Error reading an export type from the export section');
  3344. exit;
  3345. end;
  3346. case ExportType of
  3347. $00: { func }
  3348. begin
  3349. if not ReadUleb32(FuncIdx) then
  3350. begin
  3351. InputError('Error reading a func index from the export section');
  3352. exit;
  3353. end;
  3354. if FuncIdx>high(FuncTypes) then
  3355. begin
  3356. InputError('Func index too high in the export section');
  3357. exit;
  3358. end;
  3359. with FuncTypes[FuncIdx] do
  3360. begin
  3361. IsExported:=True;
  3362. ExportName:=Name;
  3363. end;
  3364. end;
  3365. $01: { table }
  3366. begin
  3367. if not ReadUleb32(TableIdx) then
  3368. begin
  3369. InputError('Error reading a table index from the export section');
  3370. exit;
  3371. end;
  3372. if TableIdx>high(TableTypes) then
  3373. begin
  3374. InputError('Table index too high in the export section');
  3375. exit;
  3376. end;
  3377. with TableTypes[TableIdx] do
  3378. begin
  3379. IsExported:=True;
  3380. ExportName:=Name;
  3381. end;
  3382. end;
  3383. $02: { mem }
  3384. begin
  3385. if not ReadUleb32(MemIdx) then
  3386. begin
  3387. InputError('Error reading a mem index from the export section');
  3388. exit;
  3389. end;
  3390. if MemIdx>high(MemTypes) then
  3391. begin
  3392. InputError('Mem index too high in the export section');
  3393. exit;
  3394. end;
  3395. with MemTypes[MemIdx] do
  3396. begin
  3397. IsExported:=True;
  3398. ExportName:=Name;
  3399. end;
  3400. end;
  3401. $03: { global }
  3402. begin
  3403. if not ReadUleb32(GlobalIdx) then
  3404. begin
  3405. InputError('Error reading a global index from the export section');
  3406. exit;
  3407. end;
  3408. if GlobalIdx>high(GlobalTypes) then
  3409. begin
  3410. InputError('Global index too high in the export section');
  3411. exit;
  3412. end;
  3413. with GlobalTypes[GlobalIdx] do
  3414. begin
  3415. IsExported:=True;
  3416. ExportName:=Name;
  3417. end;
  3418. end;
  3419. else
  3420. begin
  3421. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3422. exit;
  3423. end;
  3424. end;
  3425. end;
  3426. if AReader.Pos<>(SectionStart+SectionSize) then
  3427. begin
  3428. InputError('Unexpected export section size');
  3429. exit;
  3430. end;
  3431. Result:=True;
  3432. end;
  3433. function ReadCodeSection: Boolean;
  3434. var
  3435. CodeEntriesCount: uint32;
  3436. i: Integer;
  3437. begin
  3438. Result:=False;
  3439. if CodeSectionRead then
  3440. begin
  3441. InputError('Code section is duplicated');
  3442. exit;
  3443. end;
  3444. CodeSectionRead:=True;
  3445. CodeSectionIndex:=SectionIndex;
  3446. if not ReadUleb32(CodeEntriesCount) then
  3447. begin
  3448. InputError('Error reading the code entries cound from the code section');
  3449. exit;
  3450. end;
  3451. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3452. begin
  3453. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3454. exit;
  3455. end;
  3456. SetLength(CodeSegments,CodeEntriesCount);
  3457. for i:=0 to CodeEntriesCount-1 do
  3458. with CodeSegments[i] do
  3459. begin
  3460. if not ReadUleb32(CodeSize) then
  3461. begin
  3462. InputError('Error reading the code size of an entry in the code section');
  3463. exit;
  3464. end;
  3465. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3466. begin
  3467. InputError('Code segment exceeds the bounds of the code section');
  3468. exit;
  3469. end;
  3470. DataPos:=AReader.Pos;
  3471. CodeSectionOffset:=AReader.Pos-SectionStart;
  3472. AReader.Seek(AReader.Pos+CodeSize);
  3473. end;
  3474. if AReader.Pos<>(SectionStart+SectionSize) then
  3475. begin
  3476. InputError('Unexpected code section size');
  3477. exit;
  3478. end;
  3479. Result:=true;
  3480. end;
  3481. function ReadDataSection: Boolean;
  3482. function ReadExpr(out ExprV: int32): Boolean;
  3483. var
  3484. b: Byte;
  3485. begin
  3486. Result:=False;
  3487. if not Read(b,1) then
  3488. exit;
  3489. if b<>$41 then
  3490. begin
  3491. InputError('Only i32.const expressions supported');
  3492. exit;
  3493. end;
  3494. if not ReadSleb32(ExprV) then
  3495. exit;
  3496. if not Read(b,1) then
  3497. exit;
  3498. if b<>$0B then
  3499. begin
  3500. InputError('Only single const expressions supported');
  3501. exit;
  3502. end;
  3503. Result:=True;
  3504. end;
  3505. var
  3506. DataCount: uint32;
  3507. DataType: Byte;
  3508. i: Integer;
  3509. begin
  3510. Result:=False;
  3511. if DataSectionRead then
  3512. begin
  3513. InputError('Data section is duplicated');
  3514. exit;
  3515. end;
  3516. DataSectionRead:=True;
  3517. DataSectionIndex:=SectionIndex;
  3518. if not ReadUleb32(DataCount) then
  3519. begin
  3520. InputError('Error reading the data entries count from the data section');
  3521. exit;
  3522. end;
  3523. if DataCountSectionRead then
  3524. begin
  3525. if Length(DataSegments)<>DataCount then
  3526. begin
  3527. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3528. exit;
  3529. end;
  3530. end
  3531. else
  3532. SetLength(DataSegments,DataCount);
  3533. for i:=0 to DataCount-1 do
  3534. with DataSegments[i] do
  3535. begin
  3536. if not read(DataType, 1) then
  3537. begin
  3538. InputError('Error reading data type of segment from the data section');
  3539. exit;
  3540. end;
  3541. case DataType of
  3542. 0:
  3543. begin
  3544. Active:=True;
  3545. MemIdx:=0;
  3546. if not ReadExpr(Offset) then
  3547. begin
  3548. InputError('Error reading memory offset of segment from the data section');
  3549. exit;
  3550. end;
  3551. end;
  3552. 1:
  3553. Active:=False;
  3554. 2:
  3555. begin
  3556. Active:=True;
  3557. if not ReadUleb32(MemIdx) then
  3558. begin
  3559. InputError('Error reading MemIdx of segment from the data section');
  3560. exit;
  3561. end;
  3562. if not ReadExpr(Offset) then
  3563. begin
  3564. InputError('Error reading memory offset of segment from the data section');
  3565. exit;
  3566. end;
  3567. end;
  3568. else
  3569. begin
  3570. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3571. exit;
  3572. end;
  3573. end;
  3574. if MemIdx<>0 then
  3575. begin
  3576. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3577. exit;
  3578. end;
  3579. if not Active then
  3580. begin
  3581. InputError('Passive memory segments not supported');
  3582. exit;
  3583. end;
  3584. if not ReadUleb32(Len) then
  3585. begin
  3586. InputError('Error reading data segment length');
  3587. exit;
  3588. end;
  3589. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3590. begin
  3591. InputError('Data segment exceeds the bounds of the data section');
  3592. exit;
  3593. end;
  3594. DataPos:=AReader.Pos;
  3595. DataSectionOffset:=AReader.Pos-SectionStart;
  3596. AReader.Seek(AReader.Pos+Len);
  3597. end;
  3598. if AReader.Pos<>(SectionStart+SectionSize) then
  3599. begin
  3600. InputError('Unexpected data section size');
  3601. exit;
  3602. end;
  3603. Result:=true;
  3604. end;
  3605. function ReadDataCountSection: Boolean;
  3606. var
  3607. DataCount: uint32;
  3608. begin
  3609. Result:=False;
  3610. if DataCountSectionRead then
  3611. begin
  3612. InputError('Data count section is duplicated');
  3613. exit;
  3614. end;
  3615. DataCountSectionRead:=True;
  3616. if DataSectionRead then
  3617. begin
  3618. InputError('The data count section must occur before the data section');
  3619. exit;
  3620. end;
  3621. if not ReadUleb32(DataCount) then
  3622. begin
  3623. InputError('Error reading the data count from the data count section');
  3624. exit;
  3625. end;
  3626. if AReader.Pos<>(SectionStart+SectionSize) then
  3627. begin
  3628. InputError('Unexpected data count section size');
  3629. exit;
  3630. end;
  3631. SetLength(DataSegments, DataCount);
  3632. Result:=true;
  3633. end;
  3634. begin
  3635. Result:=False;
  3636. Inc(SectionIndex);
  3637. if not AReader.read(SectionId,1) then
  3638. begin
  3639. InputError('Error reading section ID');
  3640. exit;
  3641. end;
  3642. CheckSectionBounds:=false;
  3643. if not ReadUleb32(SectionSize) then
  3644. begin
  3645. InputError('Error reading section size');
  3646. exit;
  3647. end;
  3648. if (AReader.Pos+SectionSize)>AReader.size then
  3649. begin
  3650. InputError('Section exceeds beyond the end of file');
  3651. exit;
  3652. end;
  3653. SectionStart:=AReader.Pos;
  3654. CheckSectionBounds:=true;
  3655. case SectionId of
  3656. Byte(wsiCustom):
  3657. if not ReadCustomSection then
  3658. begin
  3659. InputError('Error encountered, while reading a custom section');
  3660. exit;
  3661. end;
  3662. Byte(wsiType):
  3663. if not ReadTypeSection then
  3664. begin
  3665. InputError('Error reading the type section');
  3666. exit;
  3667. end;
  3668. Byte(wsiImport):
  3669. if not ReadImportSection then
  3670. begin
  3671. InputError('Error reading the import section');
  3672. exit;
  3673. end;
  3674. Byte(wsiFunction):
  3675. if not ReadFunctionSection then
  3676. begin
  3677. InputError('Error reading the function section');
  3678. exit;
  3679. end;
  3680. Byte(wsiGlobal):
  3681. if not ReadGlobalSection then
  3682. begin
  3683. InputError('Error reading the global section');
  3684. exit;
  3685. end;
  3686. Byte(wsiExport):
  3687. if not ReadExportSection then
  3688. begin
  3689. InputError('Error reading the export section');
  3690. exit;
  3691. end;
  3692. Byte(wsiCode):
  3693. if not ReadCodeSection then
  3694. begin
  3695. InputError('Error reading the code section');
  3696. exit;
  3697. end;
  3698. Byte(wsiData):
  3699. if not ReadDataSection then
  3700. begin
  3701. InputError('Error reading the data section');
  3702. exit;
  3703. end;
  3704. Byte(wsiDataCount):
  3705. begin
  3706. if not ReadDataCountSection then
  3707. begin
  3708. InputError('Error reading the data count section');
  3709. exit;
  3710. end;
  3711. end
  3712. else
  3713. begin
  3714. InputError('Unknown section: ' + ToStr(SectionId));
  3715. exit;
  3716. end;
  3717. end;
  3718. if SectionSize>0 then
  3719. AReader.seek(SectionStart+SectionSize);
  3720. Result:=True;
  3721. end;
  3722. function FindCodeSegment(Ofs: uint32): Integer;
  3723. var
  3724. L, R, M: Integer;
  3725. begin
  3726. L:=Low(CodeSegments);
  3727. R:=High(CodeSegments);
  3728. while L<=R do
  3729. begin
  3730. M:=(L+R) div 2;
  3731. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  3732. L:=M+1
  3733. else if CodeSegments[M].CodeSectionOffset > Ofs then
  3734. R:=M-1
  3735. else
  3736. begin
  3737. Result:=M;
  3738. exit;
  3739. end;
  3740. end;
  3741. Result:=-1;
  3742. end;
  3743. function FindDataSegment(Ofs: uint32): Integer;
  3744. var
  3745. L, R, M: Integer;
  3746. begin
  3747. L:=Low(DataSegments);
  3748. R:=High(DataSegments);
  3749. while L<=R do
  3750. begin
  3751. M:=(L+R) div 2;
  3752. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  3753. L:=M+1
  3754. else if DataSegments[M].DataSectionOffset > Ofs then
  3755. R:=M-1
  3756. else
  3757. begin
  3758. Result:=M;
  3759. exit;
  3760. end;
  3761. end;
  3762. Result:=-1;
  3763. end;
  3764. var
  3765. ModuleMagic: array [0..3] of Byte;
  3766. ModuleVersion: array [0..3] of Byte;
  3767. i, j, FirstCodeSegmentIdx, FirstDataSegmentIdx, SegI: Integer;
  3768. CurrSec, ObjSec: TObjSection;
  3769. BaseSectionOffset: UInt32;
  3770. ObjReloc: TWasmObjRelocation;
  3771. ds: TWasmCustomDebugSectionType;
  3772. begin
  3773. FReader:=AReader;
  3774. InputFileName:=AReader.FileName;
  3775. objdata:=CObjData.Create(InputFileName);
  3776. result:=false;
  3777. CodeSegments:=nil;
  3778. DataSegments:=nil;
  3779. SymbolTable:=nil;
  3780. RelocationTable:=nil;
  3781. SetLength(RelocationTable,2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))+1));
  3782. FuncTypes:=nil;
  3783. FuncTypeImportsCount:=0;
  3784. TableTypes:=nil;
  3785. TableTypeImportsCount:=0;
  3786. MemTypes:=nil;
  3787. MemTypeImportsCount:=0;
  3788. GlobalTypes:=nil;
  3789. GlobalTypeImportsCount:=0;
  3790. if not AReader.read(ModuleMagic,4) then
  3791. exit;
  3792. for i:=0 to 3 do
  3793. if ModuleMagic[i]<>WasmModuleMagic[i] then
  3794. exit;
  3795. if not AReader.read(ModuleVersion,4) then
  3796. exit;
  3797. for i:=0 to 3 do
  3798. if ModuleVersion[i]<>WasmVersion[i] then
  3799. exit;
  3800. while AReader.Pos<AReader.size do
  3801. if not ReadSection then
  3802. exit;
  3803. { fill the code segment names }
  3804. for i:=low(SymbolTable) to high(SymbolTable) do
  3805. with SymbolTable[i] do
  3806. if (SymKind=SYMTAB_FUNCTION) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  3807. begin
  3808. if FuncTypes[SymIndex].IsImport then
  3809. begin
  3810. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  3811. exit;
  3812. end;
  3813. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3814. begin
  3815. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  3816. begin
  3817. SegName:='.text.n_'+SymName;
  3818. SegIsExported:=FuncTypes[SymIndex].IsExported;
  3819. end;
  3820. end;
  3821. end;
  3822. { create segments }
  3823. FirstCodeSegmentIdx:=ObjData.ObjSectionList.Count;
  3824. for i:=low(CodeSegments) to high(CodeSegments) do
  3825. with CodeSegments[i] do
  3826. begin
  3827. if SegName='' then
  3828. begin
  3829. InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
  3830. exit;
  3831. end;
  3832. if SegIsExported then
  3833. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  3834. else
  3835. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  3836. CurrSec.DataPos:=DataPos;
  3837. CurrSec.Size:=CodeSize;
  3838. end;
  3839. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  3840. for i:=low(DataSegments) to high(DataSegments) do
  3841. with DataSegments[i] do
  3842. if Active then
  3843. begin
  3844. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  3845. CurrSec.DataPos:=DataPos;
  3846. CurrSec.MemPos:=Offset;
  3847. CurrSec.Size:=Len;
  3848. end;
  3849. ReadSectionContent(ObjData);
  3850. for i:=low(SymbolTable) to high(SymbolTable) do
  3851. with SymbolTable[i] do
  3852. case SymKind of
  3853. SYMTAB_DATA:
  3854. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3855. begin
  3856. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3857. objsym.bind:=AB_EXTERNAL;
  3858. objsym.typ:=AT_DATA;
  3859. objsym.objsection:=nil;
  3860. objsym.offset:=0;
  3861. objsym.size:=0;
  3862. end
  3863. else
  3864. begin
  3865. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3866. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  3867. objsym.bind:=AB_LOCAL
  3868. else
  3869. objsym.bind:=AB_GLOBAL;
  3870. objsym.typ:=AT_DATA;
  3871. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  3872. objsym.offset:=SymOffset;
  3873. objsym.size:=SymSize;
  3874. end;
  3875. SYMTAB_FUNCTION:
  3876. begin
  3877. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3878. begin
  3879. if not FuncTypes[SymIndex].IsImport then
  3880. begin
  3881. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  3882. exit;
  3883. end;
  3884. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3885. begin
  3886. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3887. objsym.bind:=AB_EXTERNAL;
  3888. objsym.typ:=AT_FUNCTION;
  3889. objsym.objsection:=nil;
  3890. objsym.offset:=0;
  3891. objsym.size:=0;
  3892. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  3893. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  3894. end
  3895. else
  3896. begin
  3897. if FuncTypes[SymIndex].ImportModName = 'env' then
  3898. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  3899. else
  3900. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  3901. objsym.bind:=AB_EXTERNAL;
  3902. objsym.typ:=AT_FUNCTION;
  3903. objsym.objsection:=nil;
  3904. objsym.offset:=0;
  3905. objsym.size:=0;
  3906. end;
  3907. end
  3908. else
  3909. begin
  3910. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3911. objsym.bind:=AB_GLOBAL;
  3912. objsym.typ:=AT_FUNCTION;
  3913. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]);
  3914. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3915. TWasmObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
  3916. objsym.offset:=0;
  3917. objsym.size:=objsym.objsection.Size;
  3918. end;
  3919. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  3920. objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
  3921. objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
  3922. end;
  3923. SYMTAB_GLOBAL:
  3924. begin
  3925. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3926. begin
  3927. if not GlobalTypes[SymIndex].IsImport then
  3928. begin
  3929. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
  3930. exit;
  3931. end;
  3932. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3933. begin
  3934. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3935. objsym.bind:=AB_EXTERNAL;
  3936. objsym.typ:=AT_WASM_GLOBAL;
  3937. objsym.objsection:=nil;
  3938. objsym.offset:=0;
  3939. objsym.size:=1;
  3940. objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
  3941. objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
  3942. end
  3943. else
  3944. begin
  3945. if GlobalTypes[SymIndex].ImportModName = 'env' then
  3946. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  3947. else
  3948. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  3949. objsym.bind:=AB_EXTERNAL;
  3950. objsym.typ:=AT_WASM_GLOBAL;
  3951. objsym.objsection:=nil;
  3952. objsym.offset:=0;
  3953. objsym.size:=1;
  3954. end;
  3955. end
  3956. else
  3957. begin
  3958. if GlobalTypes[SymIndex].IsImport then
  3959. begin
  3960. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
  3961. exit;
  3962. end;
  3963. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3964. objsym.bind:=AB_GLOBAL;
  3965. objsym.typ:=AT_WASM_GLOBAL;
  3966. objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
  3967. if objsym.objsection.Size=0 then
  3968. objsym.objsection.WriteZeros(1);
  3969. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3970. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  3971. objsym.offset:=0;
  3972. objsym.size:=1;
  3973. objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
  3974. end;
  3975. objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
  3976. objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
  3977. objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
  3978. objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
  3979. end;
  3980. SYMTAB_SECTION:
  3981. begin
  3982. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  3983. if DebugSectionIndex[ds]=TargetSection then
  3984. begin
  3985. ObjSec:=TWasmObjSection(ObjData.findsection(WasmCustomSectionName[ds]));
  3986. break;
  3987. end;
  3988. if ObjSec=nil then
  3989. begin
  3990. InputError('SYMTAB_SECTION entry points to an unsupported section');
  3991. exit;
  3992. end;
  3993. end;
  3994. SYMTAB_EVENT,
  3995. SYMTAB_TABLE:
  3996. {TODO};
  3997. end;
  3998. for j:=0 to high(RelocationTable) do
  3999. for i:=0 to high(RelocationTable[j]) do
  4000. with RelocationTable[j,i] do
  4001. begin
  4002. case j of
  4003. 0:
  4004. begin
  4005. SegI:=FindCodeSegment(RelocOffset);
  4006. if SegI=-1 then
  4007. begin
  4008. InputError('Relocation offset not found in code segment');
  4009. Exit;
  4010. end;
  4011. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  4012. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SegI]);
  4013. end;
  4014. 1:
  4015. begin
  4016. SegI:=FindDataSegment(RelocOffset);
  4017. if SegI=-1 then
  4018. begin
  4019. InputError('Relocation offset not found in data segment');
  4020. Exit;
  4021. end;
  4022. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  4023. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  4024. end;
  4025. 2..2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))):
  4026. begin
  4027. BaseSectionOffset:=0;
  4028. ObjSec:=ObjData.findsection(WasmCustomSectionName[TWasmCustomSectionType((j-2)+Ord(Low(TWasmCustomDebugSectionType)))]);
  4029. end;
  4030. else
  4031. internalerror(2023122801);
  4032. end;
  4033. case RelocType of
  4034. R_WASM_FUNCTION_INDEX_LEB:
  4035. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB));
  4036. R_WASM_TABLE_INDEX_SLEB:
  4037. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB));
  4038. R_WASM_TABLE_INDEX_I32:
  4039. begin
  4040. if SymbolTable[RelocIndex].ObjSym.typ<>AT_FUNCTION then
  4041. begin
  4042. InputError('R_WASM_TABLE_INDEX_I32 relocation must point to a function symbol');
  4043. exit;
  4044. end;
  4045. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE));
  4046. end;
  4047. R_WASM_MEMORY_ADDR_LEB:
  4048. begin
  4049. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  4050. ObjReloc.Addend:=RelocAddend;
  4051. ObjSec.ObjRelocations.Add(ObjReloc);
  4052. end;
  4053. R_WASM_MEMORY_ADDR_SLEB:
  4054. begin
  4055. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  4056. ObjReloc.Addend:=RelocAddend;
  4057. ObjSec.ObjRelocations.Add(ObjReloc);
  4058. end;
  4059. R_WASM_MEMORY_ADDR_I32:
  4060. begin
  4061. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4062. ObjReloc.Addend:=RelocAddend;
  4063. ObjSec.ObjRelocations.Add(ObjReloc);
  4064. end;
  4065. R_WASM_TYPE_INDEX_LEB:
  4066. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
  4067. R_WASM_FUNCTION_OFFSET_I32:
  4068. begin
  4069. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4070. ObjReloc.Addend:=RelocAddend;
  4071. ObjSec.ObjRelocations.Add(ObjReloc);
  4072. end;
  4073. R_WASM_SECTION_OFFSET_I32:
  4074. begin
  4075. ObjReloc:=TWasmObjRelocation.CreateSection(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSec,RELOC_ABSOLUTE);
  4076. ObjReloc.Addend:=RelocAddend;
  4077. ObjSec.ObjRelocations.Add(ObjReloc);
  4078. end;
  4079. R_WASM_GLOBAL_INDEX_LEB:
  4080. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB));
  4081. R_WASM_TAG_INDEX_LEB:
  4082. begin
  4083. InputError('R_WASM_TAG_INDEX_LEB relocations not yet implemented');
  4084. exit;
  4085. end;
  4086. else
  4087. internalerror(2023122802);
  4088. end;
  4089. end;
  4090. Result:=True;
  4091. end;
  4092. {****************************************************************************
  4093. TWasmExeOutput
  4094. ****************************************************************************}
  4095. procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
  4096. var
  4097. b: byte;
  4098. begin
  4099. b:=ord(wsid);
  4100. Writer.write(b,1);
  4101. WriteUleb(Writer,FWasmSections[wsid].size);
  4102. Writer.writearray(FWasmSections[wsid]);
  4103. end;
  4104. procedure TWasmExeOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  4105. var
  4106. b: byte;
  4107. begin
  4108. b:=0;
  4109. Writer.write(b,1);
  4110. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  4111. Writer.writearray(FWasmCustomSections[wcst]);
  4112. end;
  4113. function TWasmExeOutput.writeData: boolean;
  4114. procedure WriteImportSection;
  4115. var
  4116. imports_count: SizeInt;
  4117. i: Integer;
  4118. begin
  4119. imports_count:=Length(FFunctionImports);
  4120. WriteUleb(FWasmSections[wsiImport],imports_count);
  4121. for i:=0 to Length(FFunctionImports)-1 do
  4122. with FFunctionImports[i] do
  4123. begin
  4124. WriteName(FWasmSections[wsiImport],ModName);
  4125. WriteName(FWasmSections[wsiImport],Name);
  4126. WriteByte(FWasmSections[wsiImport],$00);
  4127. WriteUleb(FWasmSections[wsiImport],TypeIdx);
  4128. end;
  4129. end;
  4130. procedure WriteCodeSegments;
  4131. var
  4132. i: Integer;
  4133. exesec: TExeSection;
  4134. objsec: TWasmObjSection;
  4135. begin
  4136. exesec:=FindExeSection('.text');
  4137. if not assigned(exesec) then
  4138. internalerror(2023123102);
  4139. if not (oso_Data in exesec.SecOptions) then
  4140. internalerror(2023123103);
  4141. WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
  4142. WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
  4143. for i:=0 to exesec.ObjSectionList.Count-1 do
  4144. begin
  4145. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4146. if not (oso_data in objsec.secoptions) then
  4147. internalerror(2023123104);
  4148. if not assigned(objsec.data) then
  4149. internalerror(2023123105);
  4150. if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
  4151. internalerror(2024010101);
  4152. WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4153. WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
  4154. objsec.Data.seek(0);
  4155. CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
  4156. end;
  4157. end;
  4158. procedure WriteDataSegments;
  4159. procedure WriteExeSection(exesec: TExeSection);
  4160. var
  4161. i: Integer;
  4162. objsec: TObjSection;
  4163. exesecdatapos: LongWord;
  4164. dpos, pad: QWord;
  4165. begin
  4166. WriteByte(FWasmSections[wsiData],0);
  4167. WriteByte(FWasmSections[wsiData],$41); { i32.const }
  4168. WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
  4169. WriteByte(FWasmSections[wsiData],$0B); { end }
  4170. WriteUleb(FWasmSections[wsiData],exesec.Size);
  4171. exesecdatapos:=FWasmSections[wsiData].size;
  4172. for i:=0 to exesec.ObjSectionList.Count-1 do
  4173. begin
  4174. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4175. if not (oso_data in objsec.secoptions) then
  4176. internalerror(2024010104);
  4177. if not assigned(objsec.data) then
  4178. internalerror(2024010105);
  4179. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4180. pad:=dpos-FWasmSections[wsiData].size;
  4181. { objsection must be within SecAlign bytes from the previous one }
  4182. if (dpos<FWasmSections[wsiData].Size) or
  4183. (pad>=max(objsec.SecAlign,1)) then
  4184. internalerror(2024010106);
  4185. writeZeros(FWasmSections[wsiData],pad);
  4186. objsec.data.seek(0);
  4187. CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
  4188. end;
  4189. if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
  4190. internalerror(2024010107);
  4191. end;
  4192. var
  4193. DataCount: Integer;
  4194. begin
  4195. DataCount:=2;
  4196. WriteUleb(FWasmSections[wsiDataCount],DataCount);
  4197. WriteUleb(FWasmSections[wsiData],DataCount);
  4198. WriteExeSection(FindExeSection('.rodata'));
  4199. WriteExeSection(FindExeSection('.data'));
  4200. end;
  4201. procedure WriteTableAndElemSections;
  4202. const
  4203. TableCount=1;
  4204. var
  4205. i: Integer;
  4206. begin
  4207. { Table section }
  4208. WriteUleb(FWasmSections[wsiTable],TableCount);
  4209. { table 0 }
  4210. { table type }
  4211. WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
  4212. { table limits }
  4213. WriteByte(FWasmSections[wsiTable],$01); { has min & max }
  4214. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
  4215. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
  4216. { Elem section }
  4217. WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
  4218. { element segment 0 }
  4219. WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
  4220. { e:expr }
  4221. WriteByte(FWasmSections[wsiElement],$41); { i32.const }
  4222. WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
  4223. WriteByte(FWasmSections[wsiElement],$0B); { end }
  4224. { y*:vec(funcidx) }
  4225. WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
  4226. for i:=1 to Length(FIndirectFunctionTable)-1 do
  4227. WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
  4228. end;
  4229. procedure WriteGlobalSection;
  4230. var
  4231. exesec: TExeSection;
  4232. globals_count, i: Integer;
  4233. objsec: TWasmObjSection;
  4234. begin
  4235. exesec:=FindExeSection('.wasm_globals');
  4236. if not assigned(exesec) then
  4237. internalerror(2024010112);
  4238. globals_count:=exesec.ObjSectionList.Count;
  4239. if globals_count<>exesec.Size then
  4240. internalerror(2024010113);
  4241. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  4242. for i:=0 to exesec.ObjSectionList.Count-1 do
  4243. begin
  4244. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4245. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
  4246. if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
  4247. WriteByte(FWasmSections[wsiGlobal],1)
  4248. else
  4249. WriteByte(FWasmSections[wsiGlobal],0);
  4250. { initializer expr }
  4251. with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
  4252. case typ of
  4253. wbt_i32:
  4254. begin
  4255. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  4256. WriteSleb(FWasmSections[wsiGlobal],init_i32);
  4257. end;
  4258. wbt_i64:
  4259. begin
  4260. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  4261. WriteSleb(FWasmSections[wsiGlobal],init_i64);
  4262. end;
  4263. wbt_f32:
  4264. begin
  4265. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  4266. WriteF32LE(FWasmSections[wsiGlobal],init_f32);
  4267. end;
  4268. wbt_f64:
  4269. begin
  4270. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  4271. WriteF64LE(FWasmSections[wsiGlobal],init_f64);
  4272. end;
  4273. wbt_funcref,
  4274. wbt_externref:
  4275. begin
  4276. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
  4277. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
  4278. end;
  4279. else
  4280. internalerror(2024010114);
  4281. end;
  4282. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  4283. end;
  4284. end;
  4285. procedure WriteExportSection;
  4286. const
  4287. MemoryExportsCount=1;
  4288. var
  4289. FunctionExportsCount: Integer;
  4290. ExportsCount: Integer;
  4291. textsec: TExeSection;
  4292. i: Integer;
  4293. objsec: TWasmObjSection;
  4294. begin
  4295. FunctionExportsCount:=0;
  4296. textsec:=FindExeSection('.text');
  4297. if not assigned(textsec) then
  4298. internalerror(2024010115);
  4299. for i:=0 to textsec.ObjSectionList.Count-1 do
  4300. begin
  4301. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4302. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4303. Inc(FunctionExportsCount)
  4304. end;
  4305. ExportsCount:=MemoryExportsCount+FunctionExportsCount;
  4306. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4307. { export 0 }
  4308. WriteName(FWasmSections[wsiExport],'memory');
  4309. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4310. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4311. for i:=0 to textsec.ObjSectionList.Count-1 do
  4312. begin
  4313. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4314. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4315. begin
  4316. WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
  4317. WriteByte(FWasmSections[wsiExport],$00); { func }
  4318. WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
  4319. end;
  4320. end;
  4321. end;
  4322. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  4323. var
  4324. exesec: TExeSection;
  4325. begin
  4326. exesec:=FindExeSection(WasmCustomSectionName[st]);
  4327. if assigned(exesec) then
  4328. begin
  4329. WriteExeSectionToDynArray(exesec,FWasmCustomSections[st]);
  4330. WriteWasmCustomSection(st);
  4331. end;
  4332. end;
  4333. var
  4334. cust_sec: TWasmCustomSectionType;
  4335. begin
  4336. result:=false;
  4337. { each custom sections starts with its name }
  4338. for cust_sec in TWasmCustomSectionType do
  4339. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  4340. SetStackPointer;
  4341. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4342. WriteImportSection;
  4343. WriteCodeSegments;
  4344. WriteDataSegments;
  4345. WriteTableAndElemSections;
  4346. WriteGlobalSection;
  4347. WriteExportSection;
  4348. WriteUleb(FWasmSections[wsiMemory],1);
  4349. WriteByte(FWasmSections[wsiMemory],0);
  4350. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4351. {...}
  4352. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4353. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4354. WriteWasmSection(wsiType);
  4355. WriteWasmSection(wsiImport);
  4356. WriteWasmSection(wsiFunction);
  4357. WriteWasmSection(wsiTable);
  4358. WriteWasmSection(wsiMemory);
  4359. WriteWasmSection(wsiGlobal);
  4360. WriteWasmSection(wsiExport);
  4361. WriteWasmSection(wsiElement);
  4362. WriteWasmSection(wsiDataCount);
  4363. WriteWasmSection(wsiCode);
  4364. WriteWasmSection(wsiData);
  4365. MaybeWriteDebugSection(wcstDebugAbbrev);
  4366. MaybeWriteDebugSection(wcstDebugInfo);
  4367. MaybeWriteDebugSection(wcstDebugStr);
  4368. MaybeWriteDebugSection(wcstDebugLine);
  4369. MaybeWriteDebugSection(wcstDebugFrame);
  4370. MaybeWriteDebugSection(wcstDebugAranges);
  4371. MaybeWriteDebugSection(wcstDebugRanges);
  4372. result := true;
  4373. end;
  4374. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4375. procedure writeUInt32LE(v: uint32);
  4376. begin
  4377. {$ifdef FPC_BIG_ENDIAN}
  4378. v:=SwapEndian(v);
  4379. {$endif FPC_BIG_ENDIAN}
  4380. objsec.data.write(v,4);
  4381. end;
  4382. var
  4383. i: Integer;
  4384. objreloc: TWasmObjRelocation;
  4385. objsym: TWasmObjSymbol;
  4386. begin
  4387. for i:=0 to objsec.ObjRelocations.Count-1 do
  4388. begin
  4389. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4390. if assigned(objreloc.symbol) then
  4391. begin
  4392. objsym:=TWasmObjSymbol(objreloc.symbol);
  4393. case objreloc.typ of
  4394. RELOC_FUNCTION_INDEX_LEB:
  4395. begin
  4396. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4397. internalerror(2024010103);
  4398. objsec.Data.seek(objreloc.DataOffset);
  4399. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4400. end;
  4401. RELOC_ABSOLUTE:
  4402. begin
  4403. case objsym.typ of
  4404. AT_FUNCTION:
  4405. begin
  4406. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4407. internalerror(2024010103);
  4408. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4409. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4410. objsec.Data.seek(objreloc.DataOffset);
  4411. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4412. end;
  4413. AT_DATA:
  4414. begin
  4415. objsec.Data.seek(objreloc.DataOffset);
  4416. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4417. end;
  4418. else
  4419. internalerror(2024010108);
  4420. end;
  4421. end;
  4422. RELOC_MEMORY_ADDR_LEB:
  4423. begin
  4424. if objsym.typ<>AT_DATA then
  4425. internalerror(2024010109);
  4426. objsec.Data.seek(objreloc.DataOffset);
  4427. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4428. end;
  4429. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  4430. begin
  4431. case objsym.typ of
  4432. AT_FUNCTION:
  4433. begin
  4434. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4435. internalerror(2024010103);
  4436. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4437. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4438. objsec.Data.seek(objreloc.DataOffset);
  4439. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4440. end;
  4441. AT_DATA:
  4442. begin
  4443. objsec.Data.seek(objreloc.DataOffset);
  4444. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4445. end;
  4446. else
  4447. internalerror(2024010110);
  4448. end;
  4449. end;
  4450. RELOC_GLOBAL_INDEX_LEB:
  4451. begin
  4452. if objsym.typ<>AT_WASM_GLOBAL then
  4453. internalerror(2024010111);
  4454. objsec.Data.seek(objreloc.DataOffset);
  4455. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  4456. end;
  4457. else
  4458. Writeln('Symbol relocation not yet implemented! ', objreloc.typ);
  4459. end;
  4460. end
  4461. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  4462. begin
  4463. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  4464. objsec.Data.seek(objreloc.DataOffset);
  4465. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  4466. end
  4467. else
  4468. Writeln('Non-symbol relocation not yet implemented! ', objreloc.typ);
  4469. end;
  4470. end;
  4471. constructor TWasmExeOutput.create;
  4472. var
  4473. i: TWasmSectionID;
  4474. j: TWasmCustomSectionType;
  4475. begin
  4476. inherited create;
  4477. CObjData:=TWasmObjData;
  4478. MaxMemPos:=$FFFFFFFF;
  4479. FFuncTypes:=TWasmFuncTypeTable.Create;
  4480. for i in TWasmSectionID do
  4481. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  4482. for j in TWasmCustomSectionType do
  4483. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  4484. SetLength(FIndirectFunctionTable,1);
  4485. FIndirectFunctionTable[0].FuncIdx:=-1;
  4486. end;
  4487. destructor TWasmExeOutput.destroy;
  4488. var
  4489. i: TWasmSectionID;
  4490. j: TWasmCustomSectionType;
  4491. begin
  4492. for i in TWasmSectionID do
  4493. FWasmSections[i].Free;
  4494. for j in TWasmCustomSectionType do
  4495. FWasmCustomSections[j].Free;
  4496. FFuncTypes.Free;
  4497. inherited destroy;
  4498. end;
  4499. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4500. var
  4501. i, j: Integer;
  4502. ImportLibrary: TImportLibrary;
  4503. ImportSymbol: TImportSymbol;
  4504. exesym: TExeSymbol;
  4505. begin
  4506. { Here map import symbols to exe symbols and create necessary sections.
  4507. Actual import generation is done after unused sections (and symbols) are removed. }
  4508. FImports:=ImportLibraryList;
  4509. for i:=0 to ImportLibraryList.Count-1 do
  4510. begin
  4511. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  4512. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4513. begin
  4514. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4515. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4516. if assigned(exesym) and
  4517. (exesym.State<>symstate_defined) then
  4518. begin
  4519. ImportSymbol.CachedExeSymbol:=exesym;
  4520. exesym.State:=symstate_defined;
  4521. end;
  4522. end;
  4523. end;
  4524. PackUnresolvedExeSymbols('after module imports');
  4525. end;
  4526. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  4527. begin
  4528. PrepareImports;
  4529. PrepareFunctions;
  4530. end;
  4531. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  4532. var
  4533. ExeSec: TExeSection;
  4534. i: Integer;
  4535. objsec: TObjSection;
  4536. begin
  4537. { WebAssembly is a Harvard architecture.
  4538. Data lives in a separate address space, so start addressing back from 0
  4539. (the LLVM leaves the first 1024 bytes in the data segment empty, so we
  4540. start at 1024). }
  4541. if aname='.rodata' then
  4542. begin
  4543. CurrMemPos:=1024;
  4544. inherited;
  4545. end
  4546. else if aname='.text' then
  4547. begin
  4548. CurrMemPos:=0;
  4549. ExeSec:=FindExeSection(aname);
  4550. if not assigned(ExeSec) then
  4551. exit;
  4552. exesec.MemPos:=CurrMemPos;
  4553. CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
  4554. { set position of object ObjSections }
  4555. for i:=0 to exesec.ObjSectionList.Count-1 do
  4556. begin
  4557. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4558. CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
  4559. CurrMemPos:=objsec.setmempos(CurrMemPos);
  4560. end;
  4561. { calculate size of the section }
  4562. exesec.Size:=CurrMemPos-exesec.MemPos;
  4563. end
  4564. else
  4565. inherited;
  4566. end;
  4567. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  4568. begin
  4569. if aname=StackPointerSymStr then
  4570. begin
  4571. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  4572. FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  4573. FStackPointerSym.size:=1;
  4574. FStackPointerSym.ObjSection.WriteZeros(1);
  4575. TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
  4576. FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
  4577. FStackPointerSym.LinkingData.GlobalIsMutable:=True;
  4578. FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  4579. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
  4580. end
  4581. else
  4582. inherited;
  4583. end;
  4584. procedure TWasmExeOutput.PrepareImports;
  4585. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  4586. begin
  4587. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  4588. Result:=High(FFunctionImports);
  4589. if assigned(exemap) then
  4590. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  4591. with FFunctionImports[Result] do
  4592. begin
  4593. ModName:=libname;
  4594. Name:=symname;
  4595. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  4596. end;
  4597. end;
  4598. var
  4599. i, j: Integer;
  4600. ImportLibrary: TImportLibrary;
  4601. ImportSymbol: TImportSymbol;
  4602. exesym: TExeSymbol;
  4603. newdll: Boolean;
  4604. begin
  4605. for i:=0 to FImports.Count-1 do
  4606. begin
  4607. ImportLibrary:=TImportLibrary(FImports[i]);
  4608. newdll:=False;
  4609. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4610. begin
  4611. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4612. exesym:=ImportSymbol.CachedExeSymbol;
  4613. if assigned(exesym) and
  4614. exesym.Used then
  4615. begin
  4616. if (not newdll) and assigned(exemap) then
  4617. begin
  4618. exemap.Add('');
  4619. exemap.Add('Importing from module '+ImportLibrary.Name);
  4620. end;
  4621. newdll:=True;
  4622. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  4623. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  4624. end;
  4625. end;
  4626. end;
  4627. end;
  4628. procedure TWasmExeOutput.PrepareFunctions;
  4629. var
  4630. i, j: Integer;
  4631. exesec: TExeSection;
  4632. objsec: TWasmObjSection;
  4633. fsym: TWasmObjSymbol;
  4634. objdata: TObjData;
  4635. begin
  4636. if assigned(exemap) then
  4637. begin
  4638. exemap.Add('');
  4639. exemap.Add('Functions, defined in this module:');
  4640. end;
  4641. exesec:=FindExeSection('.text');
  4642. if not assigned(exesec) then
  4643. internalerror(2023123106);
  4644. for i:=0 to exesec.ObjSectionList.Count-1 do
  4645. begin
  4646. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4647. fsym:=objsec.MainFuncSymbol;
  4648. if not assigned(fsym) then
  4649. internalerror(2023123107);
  4650. if not assigned(fsym.LinkingData.FuncType) then
  4651. internalerror(2023123108);
  4652. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  4653. internalerror(2023123109);
  4654. if fsym.LinkingData.ExeTypeIndex<>-1 then
  4655. internalerror(2023123109);
  4656. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  4657. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  4658. if assigned(exemap) then
  4659. begin
  4660. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  4661. end;
  4662. end;
  4663. { set ExeFunctionIndex to the alias symbols as well }
  4664. for i:=0 to ObjDataList.Count-1 do
  4665. begin
  4666. objdata:=TObjData(ObjDataList[i]);
  4667. for j:=0 to objdata.ObjSymbolList.Count-1 do
  4668. begin
  4669. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  4670. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  4671. begin
  4672. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  4673. if fsym.LinkingData.ExeFunctionIndex=-1 then
  4674. internalerror(2024010102);
  4675. end;
  4676. end;
  4677. end;
  4678. end;
  4679. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  4680. var
  4681. i: Integer;
  4682. begin
  4683. for i:=1 to length(FIndirectFunctionTable)-1 do
  4684. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  4685. begin
  4686. Result:=i;
  4687. exit;
  4688. end;
  4689. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  4690. Result:=High(FIndirectFunctionTable);
  4691. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  4692. end;
  4693. procedure TWasmExeOutput.SetStackPointer;
  4694. var
  4695. BssSec: TExeSection;
  4696. StackStart, InitialStackPtrAddr: QWord;
  4697. begin
  4698. BssSec:=FindExeSection('.bss');
  4699. InitialStackPtrAddr := (BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15);
  4700. FMinMemoryPages := (InitialStackPtrAddr+65535) shr 16;
  4701. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32(InitialStackPtrAddr);
  4702. end;
  4703. procedure TWasmExeOutput.WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
  4704. var
  4705. exesecdatapos: LongWord;
  4706. i: Integer;
  4707. objsec: TObjSection;
  4708. dpos, pad: QWord;
  4709. begin
  4710. exesecdatapos:=dynarr.size;
  4711. for i:=0 to exesec.ObjSectionList.Count-1 do
  4712. begin
  4713. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4714. if not (oso_data in objsec.secoptions) then
  4715. internalerror(2024010104);
  4716. if not assigned(objsec.data) then
  4717. internalerror(2024010105);
  4718. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4719. pad:=dpos-dynarr.size;
  4720. { objsection must be within SecAlign bytes from the previous one }
  4721. if (dpos<dynarr.Size) or
  4722. (pad>=max(objsec.SecAlign,1)) then
  4723. internalerror(2024010106);
  4724. writeZeros(dynarr,pad);
  4725. objsec.data.seek(0);
  4726. CopyDynamicArray(objsec.data,dynarr,objsec.data.size);
  4727. end;
  4728. if (dynarr.size-exesecdatapos)<>exesec.Size then
  4729. internalerror(2024010107);
  4730. end;
  4731. {****************************************************************************
  4732. TWasmAssembler
  4733. ****************************************************************************}
  4734. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  4735. begin
  4736. inherited;
  4737. CObjOutput:=TWasmObjOutput;
  4738. end;
  4739. {*****************************************************************************
  4740. Initialize
  4741. *****************************************************************************}
  4742. {$ifdef wasm32}
  4743. const
  4744. as_wasm32_wasm_info : tasminfo =
  4745. (
  4746. id : as_wasm32_wasm;
  4747. idtxt : 'WASM';
  4748. asmbin : '';
  4749. asmcmd : '';
  4750. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  4751. flags : [af_outputbinary,af_smartlink_sections];
  4752. labelprefix : '..@';
  4753. labelmaxlen : -1;
  4754. comment : '; ';
  4755. dollarsign: '$';
  4756. );
  4757. {$endif wasm32}
  4758. initialization
  4759. {$ifdef wasm32}
  4760. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  4761. {$endif wasm32}
  4762. end.