ogwasm.pas 226 KB

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