ogwasm.pas 198 KB

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