ogwasm.pas 188 KB

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