ogwasm.pas 222 KB

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