ogwasm.pas 199 KB

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