ogwasm.pas 211 KB

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