ogwasm.pas 224 KB

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