ogomf.pas 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945
  1. {
  2. Copyright (c) 2015 by Nikolay Nikolov
  3. Contains the binary Relocatable Object Module Format (OMF) reader and writer
  4. This is the object format used on the i8086-msdos platform.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit ogomf;
  19. {$i fpcdefs.inc}
  20. {$PackSet 1}
  21. interface
  22. uses
  23. { common }
  24. cclasses,globtype,
  25. { target }
  26. systems,
  27. { assembler }
  28. cpuinfo,cpubase,aasmbase,assemble,link,
  29. { OMF definitions }
  30. omfbase,
  31. { output }
  32. ogbase,
  33. owbase;
  34. type
  35. { TOmfObjSymbol }
  36. TOmfObjSymbol = class(TObjSymbol)
  37. public
  38. { string representation for the linker map file }
  39. function AddressStr(AImageBase: qword): string;override;
  40. end;
  41. { TOmfRelocation }
  42. TOmfRelocation = class(TObjRelocation)
  43. private
  44. FFrameGroup: string;
  45. FOmfFixup: TOmfSubRecord_FIXUP;
  46. public
  47. destructor Destroy; override;
  48. procedure BuildOmfFixup;
  49. property FrameGroup: string read FFrameGroup write FFrameGroup;
  50. property OmfFixup: TOmfSubRecord_FIXUP read FOmfFixup;
  51. end;
  52. TMZExeUnifiedLogicalSegment=class;
  53. { TOmfObjSection }
  54. TOmfObjSection = class(TObjSection)
  55. private
  56. FClassName: string;
  57. FOverlayName: string;
  58. FFirstSym: TObjSymbol;
  59. FCombination: TOmfSegmentCombination;
  60. FUse: TOmfSegmentUse;
  61. FPrimaryGroup: TObjSectionGroup;
  62. FSortOrder: Integer;
  63. FMZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment;
  64. FLinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList;
  65. function GetOmfAlignment: TOmfSegmentAlignment;
  66. protected
  67. function GetAltName: string; override;
  68. public
  69. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  70. destructor destroy;override;
  71. function MemPosStr(AImageBase: qword): string;override;
  72. property ClassName: string read FClassName;
  73. property OverlayName: string read FOverlayName;
  74. property OmfAlignment: TOmfSegmentAlignment read GetOmfAlignment;
  75. property Combination: TOmfSegmentCombination read FCombination;
  76. property Use: TOmfSegmentUse read FUse;
  77. property PrimaryGroup: TObjSectionGroup read FPrimaryGroup;
  78. property SortOrder: Integer read FSortOrder write FSortOrder;
  79. property MZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment read FMZExeUnifiedLogicalSegment write FMZExeUnifiedLogicalSegment;
  80. property LinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList read FLinNumEntries;
  81. end;
  82. { TOmfObjExportedSymbol }
  83. TOmfObjExportedSymbol = class(TFPHashObject)
  84. private
  85. FExportByOrdinal: Boolean;
  86. FResidentName: Boolean;
  87. FNoData: Boolean;
  88. FParmCount: Integer;
  89. FExportedName: string;
  90. FInternalName: string;
  91. FExportOrdinal: Word;
  92. public
  93. property ExportByOrdinal: Boolean read FExportByOrdinal write FExportByOrdinal;
  94. property ResidentName: Boolean read FResidentName write FResidentName;
  95. property NoData: Boolean read FNoData write FNoData;
  96. property ParmCount: Integer read FParmCount write FParmCount;
  97. property ExportedName: string read FExportedName write FExportedName;
  98. property InternalName: string read FInternalName write FInternalName;
  99. property ExportOrdinal: Word read FExportOrdinal write FExportOrdinal;
  100. end;
  101. { TOmfObjData }
  102. TOmfObjData = class(TObjData)
  103. private
  104. FMainSource: TPathStr;
  105. FImportLibraryList:TFPHashObjectList;
  106. FExportedSymbolList:TFPHashObjectList;
  107. class function CodeSectionName(const aname:string): string;
  108. public
  109. constructor create(const n:string);override;
  110. destructor destroy;override;
  111. function sectiontype2align(atype:TAsmSectiontype):longint;override;
  112. class function sectiontype2class(atype:TAsmSectiontype):string;
  113. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  114. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;override;
  115. function reffardatasection:TObjSection;
  116. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  117. procedure AddImportSymbol(const libname,symname,symmangledname:TCmdStr;OrdNr: longint;isvar:boolean);
  118. procedure AddExportSymbol(aExportByOrdinal,aResidentName,aNoData:Boolean;aParmCount:Integer;aExportedName,aInternalName:string;aExportOrdinal:Word);
  119. property MainSource: TPathStr read FMainSource;
  120. property ImportLibraryList:TFPHashObjectList read FImportLibraryList;
  121. property ExportedSymbolList:TFPHashObjectList read FExportedSymbolList;
  122. end;
  123. { TOmfObjOutput }
  124. TOmfObjOutput = class(tObjOutput)
  125. private
  126. FLNames: TOmfOrderedNameCollection;
  127. FSegments: TFPHashObjectList;
  128. FGroups: TFPHashObjectList;
  129. procedure AddSegment(const name,segclass,ovlname: string;
  130. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  131. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  132. procedure AddGroup(group: TObjSectionGroup);
  133. procedure WriteSections(Data:TObjData);
  134. procedure WriteSectionContentAndFixups(sec: TObjSection);
  135. procedure WriteLinNumRecords(sec: TOmfObjSection);
  136. procedure section_count_sections(p:TObject;arg:pointer);
  137. procedure group_count_groups(p:TObject;arg:pointer);
  138. procedure WritePUBDEFs(Data: TObjData);
  139. procedure WriteEXTDEFs(Data: TObjData);
  140. property LNames: TOmfOrderedNameCollection read FLNames;
  141. property Segments: TFPHashObjectList read FSegments;
  142. property Groups: TFPHashObjectList read FGroups;
  143. protected
  144. function writeData(Data:TObjData):boolean;override;
  145. public
  146. constructor create(AWriter:TObjectWriter);override;
  147. destructor Destroy;override;
  148. procedure WriteDllImport(const dllname,afuncname,mangledname:string;ordnr:longint;isvar:boolean);
  149. end;
  150. { TOmfObjInput }
  151. TOmfObjInput = class(TObjInput)
  152. private
  153. FLNames: TOmfOrderedNameCollection;
  154. FExtDefs: TFPHashObjectList;
  155. FPubDefs: TFPHashObjectList;
  156. FFixupThreads: TOmfThreads;
  157. FRawRecord: TOmfRawRecord;
  158. FCOMENTRecord: TOmfRecord_COMENT;
  159. FCaseSensitiveSegments: Boolean;
  160. FCaseSensitiveSymbols: Boolean;
  161. function PeekNextRecordType: Byte;
  162. function ReadLNames(RawRec: TOmfRawRecord): Boolean;
  163. function ReadSegDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  164. function ReadGrpDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  165. function ReadExtDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  166. function ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  167. function ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  168. function ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  169. function ReadImpDef(Rec: TOmfRecord_COMENT; objdata:TObjData): Boolean;
  170. function ReadExpDef(Rec: TOmfRecord_COMENT; objdata:TObjData): Boolean;
  171. function ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  172. property LNames: TOmfOrderedNameCollection read FLNames;
  173. property ExtDefs: TFPHashObjectList read FExtDefs;
  174. property PubDefs: TFPHashObjectList read FPubDefs;
  175. { Specifies whether we're case sensitive in regards to segment, class, overlay and group names. }
  176. property CaseSensitiveSegments: Boolean read FCaseSensitiveSegments write FCaseSensitiveSegments;
  177. { Specifies whether symbol names (in EXTDEF and PUBDEF records) are case sensitive. }
  178. property CaseSensitiveSymbols: Boolean read FCaseSensitiveSymbols write FCaseSensitiveSymbols;
  179. public
  180. constructor create;override;
  181. destructor destroy;override;
  182. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  183. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  184. end;
  185. { TMZExeRelocation }
  186. TMZExeRelocation = record
  187. offset: Word;
  188. segment: Word;
  189. end;
  190. TMZExeRelocations = array of TMZExeRelocation;
  191. TMZExeExtraHeaderData = array of Byte;
  192. { TMZExeHeader }
  193. TMZExeHeader = class
  194. private
  195. FChecksum: Word;
  196. FExtraHeaderData: TMZExeExtraHeaderData;
  197. FHeaderSizeAlignment: Integer;
  198. FInitialCS: Word;
  199. FInitialIP: Word;
  200. FInitialSP: Word;
  201. FInitialSS: Word;
  202. FLoadableImageSize: DWord;
  203. FMaxExtraParagraphs: Word;
  204. FMinExtraParagraphs: Word;
  205. FOverlayNumber: Word;
  206. FRelocations: TMZExeRelocations;
  207. procedure SetHeaderSizeAlignment(AValue: Integer);
  208. public
  209. constructor Create;
  210. procedure WriteTo(aWriter: TObjectWriter);
  211. procedure AddRelocation(aSegment,aOffset: Word);
  212. property HeaderSizeAlignment: Integer read FHeaderSizeAlignment write SetHeaderSizeAlignment; {default=16, must be multiple of 16}
  213. property Relocations: TMZExeRelocations read FRelocations write FRelocations;
  214. property ExtraHeaderData: TMZExeExtraHeaderData read FExtraHeaderData write FExtraHeaderData;
  215. property LoadableImageSize: DWord read FLoadableImageSize write FLoadableImageSize;
  216. property MinExtraParagraphs: Word read FMinExtraParagraphs write FMinExtraParagraphs;
  217. property MaxExtraParagraphs: Word read FMaxExtraParagraphs write FMaxExtraParagraphs;
  218. property InitialSS: Word read FInitialSS write FInitialSS;
  219. property InitialSP: Word read FInitialSP write FInitialSP;
  220. property Checksum: Word read FChecksum write FChecksum;
  221. property InitialIP: Word read FInitialIP write FInitialIP;
  222. property InitialCS: Word read FInitialCS write FInitialCS;
  223. property OverlayNumber: Word read FOverlayNumber write FOverlayNumber;
  224. end;
  225. { TMZExeSection }
  226. TMZExeSection=class(TExeSection)
  227. public
  228. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  229. end;
  230. { TMZExeUnifiedLogicalSegment }
  231. TMZExeUnifiedLogicalSegment=class(TFPHashObject)
  232. private
  233. FObjSectionList: TFPObjectList;
  234. FSegName: TSymStr;
  235. FSegClass: TSymStr;
  236. FPrimaryGroup: string;
  237. public
  238. Size,
  239. MemPos,
  240. MemBasePos: qword;
  241. IsStack: Boolean;
  242. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  243. destructor destroy;override;
  244. procedure AddObjSection(ObjSec: TOmfObjSection);
  245. procedure CalcMemPos;
  246. function MemPosStr:string;
  247. property ObjSectionList: TFPObjectList read FObjSectionList;
  248. property SegName: TSymStr read FSegName;
  249. property SegClass: TSymStr read FSegClass;
  250. property PrimaryGroup: string read FPrimaryGroup write FPrimaryGroup;
  251. end;
  252. { TMZExeUnifiedLogicalGroup }
  253. TMZExeUnifiedLogicalGroup=class(TFPHashObject)
  254. private
  255. FSegmentList: TFPHashObjectList;
  256. public
  257. Size,
  258. MemPos: qword;
  259. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  260. destructor destroy;override;
  261. procedure CalcMemPos;
  262. function MemPosStr:string;
  263. procedure AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  264. property SegmentList: TFPHashObjectList read FSegmentList;
  265. end;
  266. { TMZExeOutput }
  267. TMZExeOutput = class(TExeOutput)
  268. private
  269. FMZFlatContentSection: TMZExeSection;
  270. FExeUnifiedLogicalSegments: TFPHashObjectList;
  271. FExeUnifiedLogicalGroups: TFPHashObjectList;
  272. FDwarfUnifiedLogicalSegments: TFPHashObjectList;
  273. FHeader: TMZExeHeader;
  274. function GetMZFlatContentSection: TMZExeSection;
  275. procedure CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  276. procedure CalcExeUnifiedLogicalSegments;
  277. procedure CalcExeGroups;
  278. procedure CalcSegments_MemBasePos;
  279. procedure WriteMap_SegmentsAndGroups;
  280. procedure WriteMap_HeaderData;
  281. function FindStackSegment: TMZExeUnifiedLogicalSegment;
  282. procedure FillLoadableImageSize;
  283. procedure FillMinExtraParagraphs;
  284. procedure FillMaxExtraParagraphs;
  285. procedure FillStartAddress;
  286. procedure FillStackAddress;
  287. procedure FillHeaderData;
  288. function writeExe:boolean;
  289. function writeCom:boolean;
  290. function writeDebugElf:boolean;
  291. property ExeUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  292. property ExeUnifiedLogicalGroups: TFPHashObjectList read FExeUnifiedLogicalGroups;
  293. property DwarfUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  294. property Header: TMZExeHeader read FHeader;
  295. protected
  296. procedure DoRelocationFixup(objsec:TObjSection);override;
  297. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  298. function writeData:boolean;override;
  299. public
  300. constructor create;override;
  301. destructor destroy;override;
  302. procedure Load_Symbol(const aname:string);override;
  303. procedure MemPos_EndExeSection;override;
  304. procedure MemPos_ExeSection(const aname:string);override;
  305. property MZFlatContentSection: TMZExeSection read GetMZFlatContentSection;
  306. end;
  307. const
  308. NewExeHeaderSize = $40;
  309. NewExeSegmentHeaderSize = 8;
  310. NewExeRelocationRecordSize = 8;
  311. type
  312. TNewExeHeaderFlag = (
  313. nehfSingleData, { bit 0 }
  314. nehfMultipleData, { bit 1 }
  315. { 'Global initialization' according to BP7's TDUMP.EXE }
  316. nehfRealMode, { bit 2 }
  317. nehfProtectedModeOnly, { bit 3 }
  318. { 'EMSDIRECT' according to OpenWatcom's wdump }
  319. { '8086 instructions' according to Ralf Brown's Interrupt List }
  320. nehfReserved4, { bit 4 }
  321. { 'EMSBANK' according to OpenWatcom's wdump }
  322. { '80286 instructions' according to Ralf Brown's Interrupt List }
  323. nehfReserved5, { bit 5 }
  324. { 'EMSGLOBAL' according to OpenWatcom's wdump }
  325. { '80386 instructions' according to Ralf Brown's Interrupt List }
  326. nehfReserved6, { bit 6 }
  327. nehfNeedsFPU, { bit 7 }
  328. { Not compatible with windowing API }
  329. nehfNotWindowAPICompatible, { bit 8 }
  330. { Compatible with windowing API }
  331. { (NotWindowAPICompatible + WindowAPICompatible) = Uses windowing API }
  332. nehfWindowAPICompatible, { bit 9 }
  333. { Family Application (OS/2) according to Ralf Brown's Interrupt List }
  334. nehfReserved10, { bit 10 }
  335. nehfSelfLoading, { bit 11 }
  336. nehfReserved12, { bit 12 }
  337. nehfLinkErrors, { bit 13 }
  338. nehfReserved14, { bit 14 }
  339. nehfIsDLL); { bit 15 }
  340. TNewExeHeaderFlags = set of TNewExeHeaderFlag;
  341. TNewExeAdditionalHeaderFlag = (
  342. neahfLFNSupport, { bit 0 }
  343. neahfWindows2ProtectedMode, { bit 1 }
  344. neahfWindows2ProportionalFonts, { bit 2 }
  345. neahfHasGangloadArea); { bit 3 }
  346. TNewExeAdditionalHeaderFlags = set of TNewExeAdditionalHeaderFlag;
  347. TNewExeTargetOS = (
  348. netoUnknown = $00,
  349. netoOS2 = $01,
  350. netoWindows = $02,
  351. netoMultitaskingMsDos4 = $03,
  352. netoWindows386 = $04,
  353. netoBorlandOperatingSystemServices = $05,
  354. netoPharLap286DosExtenderOS2 = $81,
  355. netoPharLap286DosExtenderWindows = $82);
  356. TNewExeSegmentFlag = (
  357. nesfData, { bit 0 }
  358. nesfLoaderAllocatedMemory, { bit 1 }
  359. nesfLoaded, { bit 2 }
  360. nesfReserved3, { bit 3 }
  361. nesfMovable, { bit 4 }
  362. nesfShareable, { bit 5 }
  363. nesfPreload, { bit 6 }
  364. nesfExecuteOnlyCodeOrReadOnlyData, { bit 7 }
  365. nesfHasRelocationData, { bit 8 }
  366. nesfReserved9, { bit 9 }
  367. nesfReserved10, { bit 10 }
  368. nesfReserved11, { bit 11 }
  369. nesfDiscardable, { bit 12 }
  370. nesfReserved13, { bit 13 }
  371. nesfReserved14, { bit 14 }
  372. nesfReserved15); { bit 15 }
  373. TNewExeSegmentFlags = set of TNewExeSegmentFlag;
  374. TNewExeMsDosStub = array of byte;
  375. { TNewExeHeader }
  376. TNewExeHeader = class
  377. private
  378. FMsDosStub: TNewExeMsDosStub;
  379. FLinkerVersion: Byte;
  380. FLinkerRevision: Byte;
  381. FEntryTableOffset: Word;
  382. FEntryTableLength: Word;
  383. FReserved: LongWord;
  384. FFlags: TNewExeHeaderFlags;
  385. FAutoDataSegmentNumber: Word;
  386. FInitialLocalHeapSize: Word;
  387. FInitialStackSize: Word;
  388. FInitialIP: Word;
  389. FInitialCS: Word;
  390. FInitialSP: Word;
  391. FInitialSS: Word;
  392. FSegmentTableEntriesCount: Word;
  393. FModuleReferenceTableEntriesCount: Word;
  394. FNonresidentNameTableLength: Word;
  395. FSegmentTableStart: Word;
  396. FResourceTableStart: Word;
  397. FResidentNameTableStart: Word;
  398. FModuleReferenceTableStart: Word;
  399. FImportedNameTableStart: Word;
  400. FNonresidentNameTableStart: LongWord;
  401. FMovableEntryPointsCount: Word;
  402. FLogicalSectorAlignmentShiftCount: Word;
  403. FResourceSegmentsCount: Word;
  404. FTargetOS: TNewExeTargetOS;
  405. FAdditionalFlags: TNewExeAdditionalHeaderFlags;
  406. FGangLoadAreaStart: Word;
  407. FGangLoadAreaLength: Word;
  408. FReserved2: Word;
  409. FExpectedWindowsVersion: Word;
  410. public
  411. constructor Create;
  412. procedure WriteTo(aWriter: TObjectWriter);
  413. property MsDosStub: TNewExeMsDosStub read FMsDosStub write FMsDosStub;
  414. property LinkerVersion: Byte read FLinkerVersion write FLinkerVersion;
  415. property LinkerRevision: Byte read FLinkerRevision write FLinkerRevision;
  416. property EntryTableOffset: Word read FEntryTableOffset write FEntryTableOffset;
  417. property EntryTableLength: Word read FEntryTableLength write FEntryTableLength;
  418. property Reserved: LongWord read FReserved write FReserved;
  419. property Flags: TNewExeHeaderFlags read FFlags write FFlags;
  420. property AutoDataSegmentNumber: Word read FAutoDataSegmentNumber write FAutoDataSegmentNumber;
  421. property InitialLocalHeapSize: Word read FInitialLocalHeapSize write FInitialLocalHeapSize;
  422. property InitialStackSize: Word read FInitialStackSize write FInitialStackSize;
  423. property InitialIP: Word read FInitialIP write FInitialIP;
  424. property InitialCS: Word read FInitialCS write FInitialCS;
  425. property InitialSP: Word read FInitialSP write FInitialSP;
  426. property InitialSS: Word read FInitialSS write FInitialSS;
  427. property SegmentTableEntriesCount: Word read FSegmentTableEntriesCount write FSegmentTableEntriesCount;
  428. property ModuleReferenceTableEntriesCount: Word read FModuleReferenceTableEntriesCount write FModuleReferenceTableEntriesCount;
  429. property NonresidentNameTableLength: Word read FNonresidentNameTableLength write FNonresidentNameTableLength;
  430. property SegmentTableStart: Word read FSegmentTableStart write FSegmentTableStart;
  431. property ResourceTableStart: Word read FResourceTableStart write FResourceTableStart;
  432. property ResidentNameTableStart: Word read FResidentNameTableStart write FResidentNameTableStart;
  433. property ModuleReferenceTableStart: Word read FModuleReferenceTableStart write FModuleReferenceTableStart;
  434. property ImportedNameTableStart: Word read FImportedNameTableStart write FImportedNameTableStart;
  435. property NonresidentNameTableStart: LongWord read FNonresidentNameTableStart write FNonresidentNameTableStart;
  436. property MovableEntryPointsCount: Word read FMovableEntryPointsCount write FMovableEntryPointsCount;
  437. property LogicalSectorAlignmentShiftCount: Word read FLogicalSectorAlignmentShiftCount write FLogicalSectorAlignmentShiftCount;
  438. property ResourceSegmentsCount: Word read FResourceSegmentsCount write FResourceSegmentsCount;
  439. property TargetOS: TNewExeTargetOS read FTargetOS write FTargetOS;
  440. property AdditionalFlags: TNewExeAdditionalHeaderFlags read FAdditionalFlags write FAdditionalFlags;
  441. property GangLoadAreaStart: Word read FGangLoadAreaStart write FGangLoadAreaStart;
  442. property GangLoadAreaLength: Word read FGangLoadAreaLength write FGangLoadAreaLength;
  443. property Reserved2: Word read FReserved2 write FReserved2;
  444. property ExpectedWindowsVersion: Word read FExpectedWindowsVersion write FExpectedWindowsVersion;
  445. end;
  446. { TNewExeResourceTable }
  447. TNewExeResourceTable = class
  448. private
  449. FResourceDataAlignmentShiftCount: Word;
  450. function GetSize: QWord;
  451. public
  452. constructor Create;
  453. procedure WriteTo(aWriter: TObjectWriter);
  454. property ResourceDataAlignmentShiftCount: Word read FResourceDataAlignmentShiftCount write FResourceDataAlignmentShiftCount;
  455. property Size: QWord read GetSize;
  456. end;
  457. { TNewExeExportNameTableEntry }
  458. TNewExeExportNameTableEntry = class(TFPHashObject)
  459. private
  460. FOrdinalNr: Word;
  461. public
  462. constructor Create(HashObjectList:TFPHashObjectList;const s:TSymStr;OrdNr:Word);
  463. property OrdinalNr: Word read FOrdinalNr write FOrdinalNr;
  464. end;
  465. { TNewExeExportNameTable }
  466. TNewExeExportNameTable = class(TFPHashObjectList)
  467. private
  468. function GetSize: QWord;
  469. public
  470. procedure WriteTo(aWriter: TObjectWriter);
  471. property Size: QWord read GetSize;
  472. end;
  473. TNewExeImportedNameTable = class;
  474. { TNewExeModuleReferenceTableEntry }
  475. TNewExeModuleReferenceTableEntry = class(TFPHashObject)
  476. end;
  477. { TNewExeModuleReferenceTable }
  478. TNewExeModuleReferenceTable = class(TFPHashObjectList)
  479. private
  480. function GetSize: QWord;
  481. public
  482. procedure AddModuleReference(const dllname:TSymStr);
  483. procedure WriteTo(aWriter: TObjectWriter;imptbl:TNewExeImportedNameTable);
  484. property Size: QWord read GetSize;
  485. end;
  486. { TNewExeImportedNameTableEntry }
  487. TNewExeImportedNameTableEntry = class(TFPHashObject)
  488. private
  489. FTableOffset: Word;
  490. public
  491. property TableOffset: Word read FTableOffset write FTableOffset;
  492. end;
  493. { TNewExeImportedNameTable }
  494. TNewExeImportedNameTable = class(TFPHashObjectList)
  495. private
  496. function GetSize: QWord;
  497. public
  498. procedure AddImportedName(const name:TSymStr);
  499. procedure CalcTableOffsets;
  500. procedure WriteTo(aWriter: TObjectWriter);
  501. property Size: QWord read GetSize;
  502. end;
  503. TNewExeEntryPointFlag = (
  504. neepfMovableSegment,
  505. neepfExported,
  506. neepfSingleData
  507. );
  508. TNewExeEntryPointFlags = set of TNewExeEntryPointFlag;
  509. { TNewExeEntryPoint }
  510. TNewExeEntryPoint = class
  511. private
  512. FFlags: TNewExeEntryPointFlags;
  513. FSegment: Byte;
  514. FOffset: Word;
  515. FParmCount: Integer;
  516. function GetFlagsByte: Byte;
  517. public
  518. property Flags: TNewExeEntryPointFlags read FFlags write FFlags;
  519. property Segment: Byte read FSegment write FSegment;
  520. property Offset: Word read FOffset write FOffset;
  521. property ParmCount: Integer read FParmCount write FParmCount;
  522. property FlagsByte: Byte read GetFlagsByte;
  523. end;
  524. { TNewExeEntryTable }
  525. TNewExeEntryTable = class
  526. strict private
  527. FItems: array of TNewExeEntryPoint;
  528. function GetCount: Word;
  529. function GetItems(i: Integer): TNewExeEntryPoint;
  530. function GetSize: QWord;
  531. procedure SetItems(i: Integer; AValue: TNewExeEntryPoint);
  532. function CanBeInSameBundle(i,j:Integer):Boolean;
  533. function BundleSize(StartingElement:Integer): Byte;
  534. public
  535. destructor Destroy;override;
  536. procedure WriteTo(aWriter: TObjectWriter);
  537. procedure GrowTo(aNewCount: Word);
  538. property Size: QWord read GetSize;
  539. property Count: Word read GetCount;
  540. property Items[i: Integer]: TNewExeEntryPoint read GetItems write SetItems;default;
  541. end;
  542. { These are fake "meta sections" used by the linker script. The actual
  543. NewExe sections are segments, limited to 64kb, which means there can be
  544. multiple code segments, etc. These are created manually as object
  545. sections are added. If they fit the current segment, without exceeding
  546. 64kb, they are added to the current segment, otherwise a new segment is
  547. created. The current "meta sections" tells what kind of new segment to
  548. create (e.g. nemsCode means that a new code segment will be created). }
  549. TNewExeMetaSection = (
  550. nemsNone,
  551. nemsCode,
  552. nemsData);
  553. const
  554. NewExeMetaSection2String: array [TNewExeMetaSection] of string[9] = (
  555. '',
  556. 'Code',
  557. 'Data');
  558. type
  559. TNewExeRelocationAddressType = (
  560. neratLoByte = 0, { low 8 bits of 16-bit offset }
  561. neratSelector = 2, { 16-bit selector }
  562. neratFarPointer = 3, { 16-bit selector:16-bit offset }
  563. neratOffset = 5, { 16-bit offset }
  564. neratFarPointer48 = 11, { 16-bit selector:32-bit offset }
  565. neratOffset32 = 13); { 32-bit offset }
  566. TNewExeRelocationType = (
  567. nertInternalRef,
  568. nertImportName,
  569. nertImportOrdinal,
  570. nertOsFixup);
  571. TNewExeOsFixupType = (
  572. neoftFIARQQ_FJARQQ = 1,
  573. neoftFISRQQ_FJSRQQ = 2,
  574. neoftFICRQQ_FJCRQQ = 3,
  575. neoftFIERQQ = 4,
  576. neoftFIDRQQ = 5,
  577. neoftFIWRQQ = 6);
  578. TNewExeInternalRefSegmentType = (
  579. neirstFixed,
  580. neirstMovable);
  581. { TNewExeRelocation }
  582. TNewExeRelocation=class
  583. private
  584. FAddressType: TNewExeRelocationAddressType;
  585. FRelocationType: TNewExeRelocationType;
  586. FIsAdditive: Boolean;
  587. FInternalRefSegmentType: TNewExeInternalRefSegmentType;
  588. FOsFixupType: TNewExeOsFixupType;
  589. FOffset: Word;
  590. FImportModuleIndex: Word;
  591. FImportNameIndex: Word;
  592. FImportOrdinal: Word;
  593. FInternalRefFixedSegmentNumber: Byte;
  594. FInternalRefFixedSegmentOffset: Word;
  595. FInternalRefMovableSegmentEntryTableIndex: Word;
  596. public
  597. procedure EncodeTo(dest: PByte);
  598. property AddressType: TNewExeRelocationAddressType read FAddressType write FAddressType;
  599. property RelocationType: TNewExeRelocationType read FRelocationType write FRelocationType;
  600. property IsAdditive: Boolean read FIsAdditive write FIsAdditive;
  601. property InternalRefSegmentType: TNewExeInternalRefSegmentType read FInternalRefSegmentType write FInternalRefSegmentType;
  602. property OsFixupType: TNewExeOsFixupType read FOsFixupType write FOsFixupType;
  603. property Offset: Word read FOffset write FOffset;
  604. property ImportModuleIndex: Word read FImportModuleIndex write FImportModuleIndex;
  605. property ImportNameIndex: Word read FImportNameIndex write FImportNameIndex;
  606. property ImportOrdinal: Word read FImportOrdinal write FImportOrdinal;
  607. property InternalRefFixedSegmentNumber: Byte read FInternalRefFixedSegmentNumber write FInternalRefFixedSegmentNumber;
  608. property InternalRefFixedSegmentOffset: Word read FInternalRefFixedSegmentOffset write FInternalRefFixedSegmentOffset;
  609. property InternalRefMovableSegmentEntryTableIndex: Word read FInternalRefMovableSegmentEntryTableIndex write FInternalRefMovableSegmentEntryTableIndex;
  610. end;
  611. { TNewExeRelocationList }
  612. TNewExeRelocationList=class
  613. private
  614. FInternalList: TFPObjectList;
  615. function GetCount: Integer;
  616. function GetItem(Index: Integer): TNewExeRelocation;
  617. function GetSize: QWord;
  618. procedure SetCount(AValue: Integer);
  619. procedure SetItem(Index: Integer; AValue: TNewExeRelocation);
  620. public
  621. constructor Create;
  622. destructor Destroy; override;
  623. procedure WriteTo(aWriter: TObjectWriter);
  624. function Add(AObject: TNewExeRelocation): Integer;
  625. property Size: QWord read GetSize;
  626. property Count: Integer read GetCount write SetCount;
  627. property Items[Index: Integer]: TNewExeRelocation read GetItem write SetItem; default;
  628. end;
  629. { TNewExeSection }
  630. TNewExeSection=class(TExeSection)
  631. private
  632. FEarlySize: QWord;
  633. FStackSize: QWord;
  634. FExeMetaSec: TNewExeMetaSection;
  635. FMemBasePos: Word;
  636. FDataPosSectors: Word;
  637. FNewExeSegmentFlags: TNewExeSegmentFlags;
  638. FSizeInFile: QWord;
  639. FRelocations: TNewExeRelocationList;
  640. function GetMinAllocSize: QWord;
  641. function GetNewExeSegmentFlags: TNewExeSegmentFlags;
  642. public
  643. constructor create(AList:TFPHashObjectList;const AName:string);override;
  644. destructor destroy;override;
  645. procedure WriteHeaderTo(aWriter: TObjectWriter);
  646. function MemPosStr(AImageBase: qword): string;override;
  647. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  648. function CanAddObjSection(objsec:TObjSection;ExeSectionLimit:QWord):boolean;
  649. property EarlySize: QWord read FEarlySize write FEarlySize;
  650. property StackSize: QWord read FStackSize write FStackSize;
  651. property ExeMetaSec: TNewExeMetaSection read FExeMetaSec write FExeMetaSec;
  652. property MemBasePos: Word read FMemBasePos write FMemBasePos;
  653. property DataPosSectors: Word read FDataPosSectors write FDataPosSectors;
  654. property MinAllocSize: QWord read GetMinAllocSize;
  655. property SizeInFile: QWord read FSizeInFile write FSizeInFile;
  656. property NewExeSegmentFlags: TNewExeSegmentFlags read GetNewExeSegmentFlags write FNewExeSegmentFlags;
  657. property Relocations: TNewExeRelocationList read FRelocations;
  658. end;
  659. { TNewExeOutput }
  660. TNewExeOutput = class(TExeOutput)
  661. private
  662. FHeader: TNewExeHeader;
  663. FImports: TFPHashObjectList;
  664. FCurrExeMetaSec: TNewExeMetaSection;
  665. FResourceTable: TNewExeResourceTable;
  666. FResidentNameTable: TNewExeExportNameTable;
  667. FNonresidentNameTable: TNewExeExportNameTable;
  668. FModuleReferenceTable: TNewExeModuleReferenceTable;
  669. FImportedNameTable: TNewExeImportedNameTable;
  670. FEntryTable: TNewExeEntryTable;
  671. procedure AddImportSymbol(const libname,symname,symmangledname:TCmdStr;OrdNr: longint;isvar:boolean);
  672. procedure AddImportLibrariesExtractedFromObjectModules;
  673. procedure AddNewExeSection;
  674. function WriteNewExe:boolean;
  675. procedure FillImportedNameAndModuleReferenceTable;
  676. function GetHighestExportSymbolOrdinal: Word;
  677. procedure AssignOrdinalsToAllExportSymbols;
  678. procedure AddEntryPointsForAllExportSymbols;
  679. procedure AddExportedNames;
  680. property Header: TNewExeHeader read FHeader;
  681. property CurrExeMetaSec: TNewExeMetaSection read FCurrExeMetaSec write FCurrExeMetaSec;
  682. property ResourceTable: TNewExeResourceTable read FResourceTable;
  683. property ResidentNameTable: TNewExeExportNameTable read FResidentNameTable;
  684. property NonresidentNameTable: TNewExeExportNameTable read FNonresidentNameTable;
  685. property ModuleReferenceTable: TNewExeModuleReferenceTable read FModuleReferenceTable;
  686. property ImportedNameTable: TNewExeImportedNameTable read FImportedNameTable;
  687. property EntryTable: TNewExeEntryTable read FEntryTable;
  688. protected
  689. procedure DoRelocationFixup(objsec:TObjSection);override;
  690. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  691. public
  692. constructor create;override;
  693. destructor destroy;override;
  694. procedure Order_ExeSection(const aname:string);override;
  695. procedure Order_EndExeSection;override;
  696. procedure Order_ObjSection(const aname:string);override;
  697. procedure MemPos_Start;override;
  698. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  699. function writeData:boolean;override;
  700. end;
  701. TOmfAssembler = class(tinternalassembler)
  702. constructor create(info: pasminfo; smart:boolean);override;
  703. end;
  704. function StripDllExt(const DllName:TSymStr):TSymStr;
  705. function MaybeAddDllExt(const DllName:TSymStr):TSymStr;
  706. implementation
  707. uses
  708. SysUtils,
  709. cutils,verbose,globals,fpchash,
  710. fmodule,aasmtai,aasmdata,
  711. ogmap,owomflib,elfbase,
  712. version
  713. ;
  714. const win16stub : array[0..255] of byte=(
  715. $4d,$5a,$00,$01,$01,$00,$00,$00,$08,$00,$10,$00,$ff,$ff,$08,$00,
  716. $00,$01,$00,$00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,
  717. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  718. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,
  719. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  720. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  721. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  722. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  723. $ba,$10,$00,$0e,$1f,$b4,$09,$cd,$21,$b8,$01,$4c,$cd,$21,$90,$90,
  724. $54,$68,$69,$73,$20,$70,$72,$6f,$67,$72,$61,$6d,$20,$72,$65,$71,
  725. $75,$69,$72,$65,$73,$20,$4d,$69,$63,$72,$6f,$73,$6f,$66,$74,$20,
  726. $57,$69,$6e,$64,$6f,$77,$73,$2e,$0d,$0a,$24,$20,$20,$20,$20,$20,
  727. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  728. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  729. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  730. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20);
  731. {****************************************************************************
  732. TTISTrailer
  733. ****************************************************************************}
  734. const
  735. TIS_TRAILER_SIGNATURE: array[1..4] of char='TIS'#0;
  736. TIS_TRAILER_VENDOR_TIS=0;
  737. TIS_TRAILER_TYPE_TIS_DWARF=0;
  738. type
  739. TTISTrailer=record
  740. tis_signature: array[1..4] of char;
  741. tis_vendor,
  742. tis_type,
  743. tis_size: LongWord;
  744. end;
  745. procedure MayBeSwapTISTrailer(var h: TTISTrailer);
  746. begin
  747. if source_info.endian<>target_info.endian then
  748. with h do
  749. begin
  750. tis_vendor:=swapendian(tis_vendor);
  751. tis_type:=swapendian(tis_type);
  752. tis_size:=swapendian(tis_size);
  753. end;
  754. end;
  755. {****************************************************************************
  756. TOmfObjSymbol
  757. ****************************************************************************}
  758. function TOmfObjSymbol.AddressStr(AImageBase: qword): string;
  759. var
  760. base: qword;
  761. begin
  762. if assigned(objsection.ExeSection) and (objsection.ExeSection is TNewExeSection) then
  763. Result:=HexStr(TNewExeSection(objsection.ExeSection).MemBasePos,4)+':'+HexStr(address,4)
  764. else
  765. begin
  766. if assigned(TOmfObjSection(objsection).MZExeUnifiedLogicalSegment) then
  767. base:=TOmfObjSection(objsection).MZExeUnifiedLogicalSegment.MemBasePos
  768. else
  769. base:=(address shr 4) shl 4;
  770. Result:=HexStr(base shr 4,4)+':'+HexStr(address-base,4);
  771. end;
  772. end;
  773. {****************************************************************************
  774. TOmfRelocation
  775. ****************************************************************************}
  776. destructor TOmfRelocation.Destroy;
  777. begin
  778. FOmfFixup.Free;
  779. inherited Destroy;
  780. end;
  781. procedure TOmfRelocation.BuildOmfFixup;
  782. begin
  783. FreeAndNil(FOmfFixup);
  784. FOmfFixup:=TOmfSubRecord_FIXUP.Create;
  785. if ObjSection<>nil then
  786. begin
  787. FOmfFixup.LocationOffset:=DataOffset;
  788. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  789. FOmfFixup.LocationType:=fltOffset
  790. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  791. FOmfFixup.LocationType:=fltOffset32
  792. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  793. FOmfFixup.LocationType:=fltBase
  794. else
  795. internalerror(2015041501);
  796. FOmfFixup.FrameDeterminedByThread:=False;
  797. FOmfFixup.TargetDeterminedByThread:=False;
  798. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  799. FOmfFixup.Mode:=fmSegmentRelative
  800. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  801. FOmfFixup.Mode:=fmSelfRelative
  802. else
  803. internalerror(2015041408);
  804. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_RELATIVE16,RELOC_RELATIVE32] then
  805. begin
  806. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  807. FOmfFixup.TargetDatum:=ObjSection.Index;
  808. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  809. begin
  810. FOmfFixup.FrameMethod:=ffmGroupIndex;
  811. FOmfFixup.FrameDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  812. end
  813. else
  814. FOmfFixup.FrameMethod:=ffmTarget;
  815. end
  816. else
  817. begin
  818. FOmfFixup.FrameMethod:=ffmTarget;
  819. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  820. begin
  821. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  822. FOmfFixup.TargetDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  823. end
  824. else
  825. begin
  826. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  827. FOmfFixup.TargetDatum:=ObjSection.Index;
  828. end;
  829. end;
  830. end
  831. else if symbol<>nil then
  832. begin
  833. FOmfFixup.LocationOffset:=DataOffset;
  834. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  835. FOmfFixup.LocationType:=fltOffset
  836. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  837. FOmfFixup.LocationType:=fltOffset32
  838. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  839. FOmfFixup.LocationType:=fltBase
  840. else
  841. internalerror(2015041505);
  842. FOmfFixup.FrameDeterminedByThread:=False;
  843. FOmfFixup.TargetDeterminedByThread:=False;
  844. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  845. FOmfFixup.Mode:=fmSegmentRelative
  846. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  847. FOmfFixup.Mode:=fmSelfRelative
  848. else
  849. internalerror(2015041409);
  850. FOmfFixup.TargetMethod:=ftmExternalIndexNoDisp;
  851. FOmfFixup.TargetDatum:=symbol.symidx;
  852. FOmfFixup.FrameMethod:=ffmTarget;
  853. end
  854. else if group<>nil then
  855. begin
  856. FOmfFixup.LocationOffset:=DataOffset;
  857. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  858. FOmfFixup.LocationType:=fltOffset
  859. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  860. FOmfFixup.LocationType:=fltOffset32
  861. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  862. FOmfFixup.LocationType:=fltBase
  863. else
  864. internalerror(2015041506);
  865. FOmfFixup.FrameDeterminedByThread:=False;
  866. FOmfFixup.TargetDeterminedByThread:=False;
  867. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  868. FOmfFixup.Mode:=fmSegmentRelative
  869. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  870. FOmfFixup.Mode:=fmSelfRelative
  871. else
  872. internalerror(2015041410);
  873. FOmfFixup.FrameMethod:=ffmTarget;
  874. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  875. FOmfFixup.TargetDatum:=group.index;
  876. end
  877. else
  878. internalerror(2015040702);
  879. end;
  880. {****************************************************************************
  881. TOmfObjSection
  882. ****************************************************************************}
  883. function TOmfObjSection.GetOmfAlignment: TOmfSegmentAlignment;
  884. begin
  885. case SecAlign of
  886. 1:
  887. result:=saRelocatableByteAligned;
  888. 2:
  889. result:=saRelocatableWordAligned;
  890. 4:
  891. result:=saRelocatableDWordAligned;
  892. 16:
  893. result:=saRelocatableParaAligned;
  894. 256:
  895. result:=saRelocatablePageAligned;
  896. 4096:
  897. result:=saNotSupported;
  898. else
  899. internalerror(2015041504);
  900. end;
  901. end;
  902. function TOmfObjSection.GetAltName: string;
  903. begin
  904. if FFirstSym<>nil then
  905. result:='/'+FFirstSym.Name
  906. else
  907. result:='';
  908. end;
  909. constructor TOmfObjSection.create(AList: TFPHashObjectList;
  910. const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  911. begin
  912. inherited create(AList, Aname, Aalign, Aoptions);
  913. FCombination:=scPublic;
  914. FUse:=suUse16;
  915. FLinNumEntries:=TOmfSubRecord_LINNUM_MsLink_LineNumberList.Create;
  916. end;
  917. destructor TOmfObjSection.destroy;
  918. begin
  919. FLinNumEntries.Free;
  920. inherited destroy;
  921. end;
  922. function TOmfObjSection.MemPosStr(AImageBase: qword): string;
  923. begin
  924. if Assigned(MZExeUnifiedLogicalSegment) then
  925. Result:=HexStr(MZExeUnifiedLogicalSegment.MemBasePos shr 4,4)+':'+
  926. HexStr(MemPos-MZExeUnifiedLogicalSegment.MemBasePos,4)
  927. else if Assigned(ExeSection) and (ExeSection is TNewExeSection) then
  928. Result:=HexStr(TNewExeSection(ExeSection).MemBasePos,4)+':'+HexStr(mempos,4)
  929. else
  930. Result:=inherited;
  931. end;
  932. {****************************************************************************
  933. TOmfObjData
  934. ****************************************************************************}
  935. class function TOmfObjData.CodeSectionName(const aname: string): string;
  936. begin
  937. {$ifdef i8086}
  938. if current_settings.x86memorymodel in x86_far_code_models then
  939. begin
  940. if cs_huge_code in current_settings.moduleswitches then
  941. result:=TrimStrCRC32(aname,30) + '_TEXT'
  942. else
  943. result:=current_module.modulename^ + '_TEXT';
  944. end
  945. else
  946. {$endif}
  947. result:='_TEXT';
  948. end;
  949. constructor TOmfObjData.create(const n: string);
  950. begin
  951. inherited create(n);
  952. CObjSymbol:=TOmfObjSymbol;
  953. CObjSection:=TOmfObjSection;
  954. createsectiongroup('DGROUP');
  955. FMainSource:=current_module.mainsource;
  956. FImportLibraryList:=TFPHashObjectList.Create(true);
  957. FExportedSymbolList:=TFPHashObjectList.Create(true);
  958. end;
  959. destructor TOmfObjData.destroy;
  960. begin
  961. FExportedSymbolList.Free;
  962. FImportLibraryList.Free;
  963. inherited destroy;
  964. end;
  965. function TOmfObjData.sectiontype2align(atype: TAsmSectiontype): longint;
  966. begin
  967. Result:=omf_sectiontype2align(atype);
  968. end;
  969. class function TOmfObjData.sectiontype2class(atype: TAsmSectiontype): string;
  970. begin
  971. Result:=omf_segclass(atype);
  972. end;
  973. function TOmfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  974. var
  975. sep : string[3];
  976. secname : string;
  977. begin
  978. if (atype=sec_user) then
  979. Result:=aname
  980. else
  981. begin
  982. if omf_secnames[atype]=omf_secnames[sec_code] then
  983. secname:=CodeSectionName(aname)
  984. else if omf_segclass(atype)='FAR_DATA' then
  985. secname:=current_module.modulename^ + '_DATA'
  986. else
  987. secname:=omf_secnames[atype];
  988. if create_smartlink_sections and (aname<>'') then
  989. begin
  990. case aorder of
  991. secorder_begin :
  992. sep:='.b_';
  993. secorder_end :
  994. sep:='.z_';
  995. else
  996. sep:='.n_';
  997. end;
  998. result:=UpCase(secname+sep+aname);
  999. end
  1000. else
  1001. result:=secname;
  1002. end;
  1003. end;
  1004. function TOmfObjData.createsection(atype: TAsmSectionType; const aname: string; aorder: TAsmSectionOrder): TObjSection;
  1005. var
  1006. is_new: Boolean;
  1007. primary_group: String;
  1008. grp: TObjSectionGroup;
  1009. begin
  1010. is_new:=TObjSection(ObjSectionList.Find(sectionname(atype,aname,aorder)))=nil;
  1011. Result:=inherited createsection(atype, aname, aorder);
  1012. if is_new then
  1013. begin
  1014. TOmfObjSection(Result).FClassName:=sectiontype2class(atype);
  1015. if atype=sec_stack then
  1016. TOmfObjSection(Result).FCombination:=scStack
  1017. else if atype in [sec_debug_frame,sec_debug_info,sec_debug_line,sec_debug_abbrev,sec_debug_aranges,sec_debug_ranges] then
  1018. begin
  1019. TOmfObjSection(Result).FUse:=suUse32;
  1020. TOmfObjSection(Result).SizeLimit:=high(longword);
  1021. end;
  1022. primary_group:=omf_section_primary_group(atype,aname);
  1023. if primary_group<>'' then
  1024. begin
  1025. { find the primary group, if it already exists, else create it }
  1026. grp:=nil;
  1027. if GroupsList<>nil then
  1028. grp:=TObjSectionGroup(GroupsList.Find(primary_group));
  1029. if grp=nil then
  1030. grp:=createsectiongroup(primary_group);
  1031. { add the current section to the group }
  1032. SetLength(grp.members,Length(grp.members)+1);
  1033. grp.members[High(grp.members)]:=Result;
  1034. TOmfObjSection(Result).FPrimaryGroup:=grp;
  1035. end;
  1036. end;
  1037. end;
  1038. function TOmfObjData.reffardatasection: TObjSection;
  1039. var
  1040. secname: string;
  1041. begin
  1042. secname:=current_module.modulename^ + '_DATA';
  1043. result:=TObjSection(ObjSectionList.Find(secname));
  1044. if not assigned(result) then
  1045. begin
  1046. result:=CObjSection.create(ObjSectionList,secname,2,[oso_Data,oso_load,oso_write]);
  1047. result.ObjData:=self;
  1048. TOmfObjSection(Result).FClassName:='FAR_DATA';
  1049. end;
  1050. end;
  1051. procedure TOmfObjData.writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  1052. var
  1053. objreloc: TOmfRelocation;
  1054. symaddr: AWord;
  1055. begin
  1056. { RELOC_FARPTR = RELOC_ABSOLUTE16+RELOC_SEG }
  1057. if Reloctype=RELOC_FARPTR then
  1058. begin
  1059. if len<>4 then
  1060. internalerror(2015041502);
  1061. writeReloc(Data,2,p,RELOC_ABSOLUTE16);
  1062. writeReloc(0,2,p,RELOC_SEG);
  1063. exit;
  1064. end
  1065. { RELOC_FARPTR48 = RELOC_ABSOLUTE16+RELOC_SEG }
  1066. else if Reloctype=RELOC_FARPTR48 then
  1067. begin
  1068. if len<>6 then
  1069. internalerror(2015041507);
  1070. writeReloc(Data,4,p,RELOC_ABSOLUTE32);
  1071. writeReloc(0,2,p,RELOC_SEG);
  1072. exit;
  1073. end;
  1074. if CurrObjSec=nil then
  1075. internalerror(2004030704);
  1076. objreloc:=nil;
  1077. if Reloctype in [RELOC_FARDATASEG,RELOC_FARDATASEGREL] then
  1078. begin
  1079. if Reloctype=RELOC_FARDATASEG then
  1080. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEG)
  1081. else
  1082. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEGREL);
  1083. CurrObjSec.ObjRelocations.Add(objreloc);
  1084. end
  1085. else if assigned(p) then
  1086. begin
  1087. { real address of the symbol }
  1088. symaddr:=p.address;
  1089. if p.bind=AB_EXTERNAL then
  1090. begin
  1091. objreloc:=TOmfRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  1092. CurrObjSec.ObjRelocations.Add(objreloc);
  1093. end
  1094. { relative relocations within the same section can be calculated directly,
  1095. without the need to emit a relocation entry }
  1096. else if (p.objsection=CurrObjSec) and
  1097. (p.bind<>AB_COMMON) and
  1098. (Reloctype=RELOC_RELATIVE) then
  1099. begin
  1100. data:=data+symaddr-len-CurrObjSec.Size;
  1101. end
  1102. else
  1103. begin
  1104. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,p.objsection,Reloctype);
  1105. CurrObjSec.ObjRelocations.Add(objreloc);
  1106. if not (Reloctype in [RELOC_SEG,RELOC_SEGREL]) then
  1107. inc(data,symaddr);
  1108. end;
  1109. end
  1110. else if Reloctype in [RELOC_DGROUP,RELOC_DGROUPREL] then
  1111. begin
  1112. if Reloctype=RELOC_DGROUP then
  1113. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEG)
  1114. else
  1115. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEGREL);
  1116. CurrObjSec.ObjRelocations.Add(objreloc);
  1117. end;
  1118. CurrObjSec.write(data,len);
  1119. end;
  1120. procedure TOmfObjData.AddImportSymbol(const libname, symname,
  1121. symmangledname: TCmdStr; OrdNr: longint; isvar: boolean);
  1122. var
  1123. ImportLibrary : TImportLibrary;
  1124. ImportSymbol : TFPHashObject;
  1125. begin
  1126. ImportLibrary:=TImportLibrary(ImportLibraryList.Find(libname));
  1127. if not assigned(ImportLibrary) then
  1128. ImportLibrary:=TImportLibrary.Create(ImportLibraryList,libname);
  1129. ImportSymbol:=TFPHashObject(ImportLibrary.ImportSymbolList.Find(symname));
  1130. if not assigned(ImportSymbol) then
  1131. ImportSymbol:=TImportSymbol.Create(ImportLibrary.ImportSymbolList,symname,symmangledname,OrdNr,isvar);
  1132. end;
  1133. procedure TOmfObjData.AddExportSymbol(aExportByOrdinal, aResidentName,
  1134. aNoData: Boolean; aParmCount: Integer; aExportedName,
  1135. aInternalName: string; aExportOrdinal: Word);
  1136. var
  1137. s: TOmfObjExportedSymbol;
  1138. begin
  1139. s:=TOmfObjExportedSymbol.Create(ExportedSymbolList,aInternalName);
  1140. with s do
  1141. begin
  1142. ExportByOrdinal:=aExportByOrdinal;
  1143. ResidentName:=aResidentName;
  1144. NoData:=aNoData;
  1145. ParmCount:=aParmCount;
  1146. ExportedName:=aExportedName;
  1147. InternalName:=aInternalName;
  1148. ExportOrdinal:=aExportOrdinal;
  1149. end;
  1150. end;
  1151. {****************************************************************************
  1152. TOmfObjOutput
  1153. ****************************************************************************}
  1154. procedure TOmfObjOutput.AddSegment(const name, segclass, ovlname: string;
  1155. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  1156. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  1157. var
  1158. s: TOmfRecord_SEGDEF;
  1159. begin
  1160. s:=TOmfRecord_SEGDEF.Create;
  1161. Segments.Add(name,s);
  1162. s.SegmentNameIndex:=LNames.Add(name);
  1163. s.ClassNameIndex:=LNames.Add(segclass);
  1164. s.OverlayNameIndex:=LNames.Add(ovlname);
  1165. s.Alignment:=Alignment;
  1166. s.Combination:=Combination;
  1167. s.Use:=Use;
  1168. s.SegmentLength:=Size;
  1169. end;
  1170. procedure TOmfObjOutput.AddGroup(group: TObjSectionGroup);
  1171. var
  1172. g: TOmfRecord_GRPDEF;
  1173. seglist: TSegmentList;
  1174. I: Integer;
  1175. begin
  1176. seglist:=nil;
  1177. g:=TOmfRecord_GRPDEF.Create;
  1178. Groups.Add(group.Name,g);
  1179. g.GroupNameIndex:=LNames.Add(group.Name);
  1180. SetLength(seglist,Length(group.members));
  1181. for I:=Low(group.members) to High(group.members) do
  1182. seglist[I]:=group.members[I].index;
  1183. g.SegmentList:=seglist;
  1184. end;
  1185. procedure TOmfObjOutput.WriteSections(Data: TObjData);
  1186. var
  1187. i:longint;
  1188. sec:TObjSection;
  1189. begin
  1190. for i:=0 to Data.ObjSectionList.Count-1 do
  1191. begin
  1192. sec:=TObjSection(Data.ObjSectionList[i]);
  1193. WriteSectionContentAndFixups(sec);
  1194. WriteLinNumRecords(TOmfObjSection(sec));
  1195. end;
  1196. end;
  1197. procedure TOmfObjOutput.WriteSectionContentAndFixups(sec: TObjSection);
  1198. const
  1199. MaxChunkSize=$3fa;
  1200. var
  1201. RawRecord: TOmfRawRecord;
  1202. ChunkStart,ChunkLen: DWord;
  1203. ChunkFixupStart,ChunkFixupEnd: Integer;
  1204. SegIndex: Integer;
  1205. NextOfs: Integer;
  1206. Is32BitLEDATA: Boolean;
  1207. I: Integer;
  1208. begin
  1209. if (oso_data in sec.SecOptions) then
  1210. begin
  1211. if sec.Data=nil then
  1212. internalerror(2004030705);
  1213. for I:=0 to sec.ObjRelocations.Count-1 do
  1214. TOmfRelocation(sec.ObjRelocations[I]).BuildOmfFixup;
  1215. SegIndex:=Segments.FindIndexOf(sec.Name);
  1216. RawRecord:=TOmfRawRecord.Create;
  1217. sec.data.seek(0);
  1218. ChunkFixupStart:=0;
  1219. ChunkFixupEnd:=-1;
  1220. ChunkStart:=0;
  1221. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  1222. while ChunkLen>0 do
  1223. begin
  1224. { find last fixup in the chunk }
  1225. while (ChunkFixupEnd<(sec.ObjRelocations.Count-1)) and
  1226. (TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd+1]).DataOffset<(ChunkStart+ChunkLen)) do
  1227. inc(ChunkFixupEnd);
  1228. { check if last chunk is crossing the chunk boundary, and trim ChunkLen if necessary }
  1229. if (ChunkFixupEnd>=ChunkFixupStart) and
  1230. ((TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset+
  1231. TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).OmfFixup.LocationSize)>(ChunkStart+ChunkLen)) then
  1232. begin
  1233. ChunkLen:=TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset-ChunkStart;
  1234. Dec(ChunkFixupEnd);
  1235. end;
  1236. { write LEDATA record }
  1237. Is32BitLEDATA:=TOmfObjSection(sec).Use=suUse32;
  1238. if Is32BitLEDATA then
  1239. RawRecord.RecordType:=RT_LEDATA32
  1240. else
  1241. RawRecord.RecordType:=RT_LEDATA;
  1242. NextOfs:=RawRecord.WriteIndexedRef(0,SegIndex);
  1243. if Is32BitLEDATA then
  1244. begin
  1245. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  1246. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  1247. RawRecord.RawData[NextOfs+2]:=Byte(ChunkStart shr 16);
  1248. RawRecord.RawData[NextOfs+3]:=Byte(ChunkStart shr 24);
  1249. Inc(NextOfs,4);
  1250. end
  1251. else
  1252. begin
  1253. if ChunkStart>$ffff then
  1254. internalerror(2018052201);
  1255. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  1256. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  1257. Inc(NextOfs,2);
  1258. end;
  1259. sec.data.read(RawRecord.RawData[NextOfs], ChunkLen);
  1260. Inc(NextOfs, ChunkLen);
  1261. RawRecord.RecordLength:=NextOfs+1;
  1262. RawRecord.CalculateChecksumByte;
  1263. RawRecord.WriteTo(FWriter);
  1264. { write FIXUPP record }
  1265. if ChunkFixupEnd>=ChunkFixupStart then
  1266. begin
  1267. RawRecord.RecordType:=RT_FIXUPP;
  1268. NextOfs:=0;
  1269. for I:=ChunkFixupStart to ChunkFixupEnd do
  1270. begin
  1271. TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.DataRecordStartOffset:=ChunkStart;
  1272. NextOfs:=TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.WriteAt(RawRecord,NextOfs);
  1273. end;
  1274. RawRecord.RecordLength:=NextOfs+1;
  1275. RawRecord.CalculateChecksumByte;
  1276. RawRecord.WriteTo(FWriter);
  1277. end;
  1278. { prepare next chunk }
  1279. Inc(ChunkStart, ChunkLen);
  1280. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  1281. ChunkFixupStart:=ChunkFixupEnd+1;
  1282. end;
  1283. RawRecord.Free;
  1284. end;
  1285. end;
  1286. procedure TOmfObjOutput.WriteLinNumRecords(sec: TOmfObjSection);
  1287. var
  1288. SegIndex: Integer;
  1289. RawRecord: TOmfRawRecord;
  1290. LinNumRec: TOmfRecord_LINNUM_MsLink;
  1291. begin
  1292. if (oso_data in sec.SecOptions) then
  1293. begin
  1294. if sec.Data=nil then
  1295. internalerror(2004030706);
  1296. if sec.LinNumEntries.Count=0 then
  1297. exit;
  1298. SegIndex:=Segments.FindIndexOf(sec.Name);
  1299. RawRecord:=TOmfRawRecord.Create;
  1300. LinNumRec:=TOmfRecord_LINNUM_MsLink.Create;
  1301. LinNumRec.BaseGroup:=0;
  1302. LinNumRec.BaseSegment:=SegIndex;
  1303. LinNumRec.LineNumberList:=sec.LinNumEntries;
  1304. while LinNumRec.NextIndex<sec.LinNumEntries.Count do
  1305. begin
  1306. LinNumRec.EncodeTo(RawRecord);
  1307. RawRecord.WriteTo(FWriter);
  1308. end;
  1309. LinNumRec.Free;
  1310. RawRecord.Free;
  1311. end;
  1312. end;
  1313. procedure TOmfObjOutput.section_count_sections(p: TObject; arg: pointer);
  1314. begin
  1315. TOmfObjSection(p).index:=pinteger(arg)^;
  1316. inc(pinteger(arg)^);
  1317. end;
  1318. procedure TOmfObjOutput.group_count_groups(p: TObject; arg: pointer);
  1319. begin
  1320. TObjSectionGroup(p).index:=pinteger(arg)^;
  1321. inc(pinteger(arg)^);
  1322. end;
  1323. procedure TOmfObjOutput.WritePUBDEFs(Data: TObjData);
  1324. var
  1325. PubNamesForSection: array of TFPHashObjectList;
  1326. i: Integer;
  1327. objsym: TObjSymbol;
  1328. PublicNameElem: TOmfPublicNameElement;
  1329. RawRecord: TOmfRawRecord;
  1330. PubDefRec: TOmfRecord_PUBDEF;
  1331. begin
  1332. PubNamesForSection:=nil;
  1333. RawRecord:=TOmfRawRecord.Create;
  1334. SetLength(PubNamesForSection,Data.ObjSectionList.Count);
  1335. for i:=0 to Data.ObjSectionList.Count-1 do
  1336. PubNamesForSection[i]:=TFPHashObjectList.Create;
  1337. for i:=0 to Data.ObjSymbolList.Count-1 do
  1338. begin
  1339. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  1340. if objsym.bind=AB_GLOBAL then
  1341. begin
  1342. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  1343. PublicNameElem.PublicOffset:=objsym.offset;
  1344. PublicNameElem.IsLocal:=False;
  1345. end
  1346. else if objsym.bind=AB_LOCAL then
  1347. begin
  1348. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  1349. PublicNameElem.PublicOffset:=objsym.offset;
  1350. PublicNameElem.IsLocal:=True;
  1351. end
  1352. end;
  1353. for i:=0 to Data.ObjSectionList.Count-1 do
  1354. if PubNamesForSection[i].Count>0 then
  1355. begin
  1356. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1357. PubDefRec.BaseSegmentIndex:=i+1;
  1358. if TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup<>nil then
  1359. PubDefRec.BaseGroupIndex:=Groups.FindIndexOf(TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup.Name)
  1360. else
  1361. PubDefRec.BaseGroupIndex:=0;
  1362. PubDefRec.PublicNames:=PubNamesForSection[i];
  1363. while PubDefRec.NextIndex<PubDefRec.PublicNames.Count do
  1364. begin
  1365. PubDefRec.EncodeTo(RawRecord);
  1366. RawRecord.WriteTo(FWriter);
  1367. end;
  1368. PubDefRec.Free;
  1369. end;
  1370. for i:=0 to Data.ObjSectionList.Count-1 do
  1371. FreeAndNil(PubNamesForSection[i]);
  1372. RawRecord.Free;
  1373. end;
  1374. procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
  1375. var
  1376. ExtNames: TFPHashObjectList;
  1377. RawRecord: TOmfRawRecord;
  1378. i,idx: Integer;
  1379. objsym: TObjSymbol;
  1380. ExtDefRec: TOmfRecord_EXTDEF;
  1381. begin
  1382. ExtNames:=TFPHashObjectList.Create;
  1383. RawRecord:=TOmfRawRecord.Create;
  1384. idx:=1;
  1385. for i:=0 to Data.ObjSymbolList.Count-1 do
  1386. begin
  1387. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  1388. if objsym.bind=AB_EXTERNAL then
  1389. begin
  1390. TOmfExternalNameElement.Create(ExtNames,objsym.Name);
  1391. objsym.symidx:=idx;
  1392. Inc(idx);
  1393. end;
  1394. end;
  1395. if ExtNames.Count>0 then
  1396. begin
  1397. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1398. ExtDefRec.ExternalNames:=ExtNames;
  1399. while ExtDefRec.NextIndex<ExtDefRec.ExternalNames.Count do
  1400. begin
  1401. ExtDefRec.EncodeTo(RawRecord);
  1402. RawRecord.WriteTo(FWriter);
  1403. end;
  1404. ExtDefRec.Free;
  1405. end;
  1406. ExtNames.Free;
  1407. RawRecord.Free;
  1408. end;
  1409. function TOmfObjOutput.writeData(Data:TObjData):boolean;
  1410. var
  1411. RawRecord: TOmfRawRecord;
  1412. Header: TOmfRecord_THEADR;
  1413. Translator_COMENT: TOmfRecord_COMENT;
  1414. DebugFormat_COMENT: TOmfRecord_COMENT;
  1415. LinkPassSeparator_COMENT: TOmfRecord_COMENT;
  1416. LNamesRec: TOmfRecord_LNAMES;
  1417. ModEnd: TOmfRecord_MODEND;
  1418. I: Integer;
  1419. SegDef: TOmfRecord_SEGDEF;
  1420. GrpDef: TOmfRecord_GRPDEF;
  1421. nsections,ngroups: Integer;
  1422. begin
  1423. { calc amount of sections we have and set their index, starting with 1 }
  1424. nsections:=1;
  1425. data.ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  1426. { calc amount of groups we have and set their index, starting with 1 }
  1427. ngroups:=1;
  1428. data.GroupsList.ForEachCall(@group_count_groups,@ngroups);
  1429. { maximum amount of sections supported in the omf format is $7fff }
  1430. if (nsections-1)>$7fff then
  1431. internalerror(2015040701);
  1432. { maximum amount of groups supported in the omf format is $7fff }
  1433. if (ngroups-1)>$7fff then
  1434. internalerror(2018062101);
  1435. { write header record }
  1436. RawRecord:=TOmfRawRecord.Create;
  1437. Header:=TOmfRecord_THEADR.Create;
  1438. if cs_debuginfo in current_settings.moduleswitches then
  1439. Header.ModuleName:=TOmfObjData(Data).MainSource
  1440. else
  1441. Header.ModuleName:=Data.Name;
  1442. Header.EncodeTo(RawRecord);
  1443. RawRecord.WriteTo(FWriter);
  1444. Header.Free;
  1445. { write translator COMENT header }
  1446. Translator_COMENT:=TOmfRecord_COMENT.Create;
  1447. Translator_COMENT.CommentClass:=CC_Translator;
  1448. Translator_COMENT.CommentString:='FPC '+full_version_string+
  1449. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  1450. Translator_COMENT.EncodeTo(RawRecord);
  1451. RawRecord.WriteTo(FWriter);
  1452. Translator_COMENT.Free;
  1453. if (target_dbg.id=dbg_codeview) or
  1454. ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
  1455. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) then
  1456. begin
  1457. DebugFormat_COMENT:=TOmfRecord_COMENT.Create;
  1458. DebugFormat_COMENT.CommentClass:=CC_NewOmfExtension;
  1459. DebugFormat_COMENT.CommentString:='';
  1460. DebugFormat_COMENT.EncodeTo(RawRecord);
  1461. RawRecord.WriteTo(FWriter);
  1462. DebugFormat_COMENT.Free;
  1463. end;
  1464. LNames.Clear;
  1465. LNames.Add(''); { insert an empty string, which has index 1 }
  1466. FSegments.Clear;
  1467. FSegments.Add('',nil);
  1468. FGroups.Clear;
  1469. FGroups.Add('',nil);
  1470. for i:=0 to Data.GroupsList.Count-1 do
  1471. AddGroup(TObjSectionGroup(Data.GroupsList[I]));
  1472. for i:=0 to Data.ObjSectionList.Count-1 do
  1473. with TOmfObjSection(Data.ObjSectionList[I]) do
  1474. AddSegment(Name,ClassName,OverlayName,OmfAlignment,Combination,Use,Size);
  1475. { write LNAMES record(s) }
  1476. LNamesRec:=TOmfRecord_LNAMES.Create;
  1477. LNamesRec.Names:=LNames;
  1478. while LNamesRec.NextIndex<=LNames.Count do
  1479. begin
  1480. LNamesRec.EncodeTo(RawRecord);
  1481. RawRecord.WriteTo(FWriter);
  1482. end;
  1483. LNamesRec.Free;
  1484. { write SEGDEF record(s) }
  1485. for I:=1 to Segments.Count-1 do
  1486. begin
  1487. SegDef:=TOmfRecord_SEGDEF(Segments[I]);
  1488. SegDef.EncodeTo(RawRecord);
  1489. RawRecord.WriteTo(FWriter);
  1490. end;
  1491. { write GRPDEF record(s) }
  1492. for I:=1 to Groups.Count-1 do
  1493. begin
  1494. GrpDef:=TOmfRecord_GRPDEF(Groups[I]);
  1495. GrpDef.EncodeTo(RawRecord);
  1496. RawRecord.WriteTo(FWriter);
  1497. end;
  1498. { write PUBDEF record(s) }
  1499. WritePUBDEFs(Data);
  1500. { write EXTDEF record(s) }
  1501. WriteEXTDEFs(Data);
  1502. { write link pass separator }
  1503. LinkPassSeparator_COMENT:=TOmfRecord_COMENT.Create;
  1504. LinkPassSeparator_COMENT.CommentClass:=CC_LinkPassSeparator;
  1505. LinkPassSeparator_COMENT.CommentString:=#1;
  1506. LinkPassSeparator_COMENT.NoList:=True;
  1507. LinkPassSeparator_COMENT.EncodeTo(RawRecord);
  1508. RawRecord.WriteTo(FWriter);
  1509. LinkPassSeparator_COMENT.Free;
  1510. { write section content, interleaved with fixups }
  1511. WriteSections(Data);
  1512. { write MODEND record }
  1513. ModEnd:=TOmfRecord_MODEND.Create;
  1514. ModEnd.EncodeTo(RawRecord);
  1515. RawRecord.WriteTo(FWriter);
  1516. ModEnd.Free;
  1517. RawRecord.Free;
  1518. result:=true;
  1519. end;
  1520. constructor TOmfObjOutput.create(AWriter:TObjectWriter);
  1521. begin
  1522. inherited create(AWriter);
  1523. cobjdata:=TOmfObjData;
  1524. FLNames:=TOmfOrderedNameCollection.Create(False);
  1525. FSegments:=TFPHashObjectList.Create;
  1526. FSegments.Add('',nil);
  1527. FGroups:=TFPHashObjectList.Create;
  1528. FGroups.Add('',nil);
  1529. end;
  1530. destructor TOmfObjOutput.Destroy;
  1531. begin
  1532. FGroups.Free;
  1533. FSegments.Free;
  1534. FLNames.Free;
  1535. inherited Destroy;
  1536. end;
  1537. procedure TOmfObjOutput.WriteDllImport(const dllname,afuncname,mangledname: string; ordnr: longint; isvar: boolean);
  1538. var
  1539. RawRecord: TOmfRawRecord;
  1540. Header: TOmfRecord_THEADR;
  1541. DllImport_COMENT: TOmfRecord_COMENT=nil;
  1542. DllImport_COMENT_IMPDEF: TOmfRecord_COMENT_IMPDEF=nil;
  1543. ModEnd: TOmfRecord_MODEND;
  1544. begin
  1545. { write header record }
  1546. RawRecord:=TOmfRawRecord.Create;
  1547. Header:=TOmfRecord_THEADR.Create;
  1548. Header.ModuleName:=mangledname;
  1549. Header.EncodeTo(RawRecord);
  1550. RawRecord.WriteTo(FWriter);
  1551. Header.Free;
  1552. { write IMPDEF record }
  1553. DllImport_COMENT_IMPDEF:=TOmfRecord_COMENT_IMPDEF.Create;
  1554. DllImport_COMENT_IMPDEF.InternalName:=mangledname;
  1555. DllImport_COMENT_IMPDEF.ModuleName:=dllname;
  1556. if ordnr <= 0 then
  1557. begin
  1558. DllImport_COMENT_IMPDEF.ImportByOrdinal:=False;
  1559. DllImport_COMENT_IMPDEF.Name:=afuncname;
  1560. end
  1561. else
  1562. begin
  1563. DllImport_COMENT_IMPDEF.ImportByOrdinal:=True;
  1564. DllImport_COMENT_IMPDEF.Ordinal:=ordnr;
  1565. end;
  1566. DllImport_COMENT:=TOmfRecord_COMENT.Create;
  1567. DllImport_COMENT_IMPDEF.EncodeTo(DllImport_COMENT);
  1568. FreeAndNil(DllImport_COMENT_IMPDEF);
  1569. DllImport_COMENT.EncodeTo(RawRecord);
  1570. FreeAndNil(DllImport_COMENT);
  1571. RawRecord.WriteTo(FWriter);
  1572. { write MODEND record }
  1573. ModEnd:=TOmfRecord_MODEND.Create;
  1574. ModEnd.EncodeTo(RawRecord);
  1575. RawRecord.WriteTo(FWriter);
  1576. ModEnd.Free;
  1577. RawRecord.Free;
  1578. end;
  1579. {****************************************************************************
  1580. TOmfObjInput
  1581. ****************************************************************************}
  1582. function TOmfObjInput.PeekNextRecordType: Byte;
  1583. var
  1584. OldPos: LongInt;
  1585. begin
  1586. OldPos:=FReader.Pos;
  1587. if not FReader.read(Result, 1) then
  1588. begin
  1589. InputError('Unexpected end of file');
  1590. Result:=0;
  1591. exit;
  1592. end;
  1593. FReader.seek(OldPos);
  1594. end;
  1595. function TOmfObjInput.ReadLNames(RawRec: TOmfRawRecord): Boolean;
  1596. var
  1597. LNamesRec: TOmfRecord_LNAMES;
  1598. begin
  1599. Result:=False;
  1600. LNamesRec:=TOmfRecord_LNAMES.Create;
  1601. LNamesRec.Names:=LNames;
  1602. LNamesRec.DecodeFrom(RawRec);
  1603. LNamesRec.Free;
  1604. Result:=True;
  1605. end;
  1606. function TOmfObjInput.ReadSegDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1607. var
  1608. SegDefRec: TOmfRecord_SEGDEF;
  1609. SegmentName,SegClassName,OverlayName: string;
  1610. SecAlign: LongInt;
  1611. secoptions: TObjSectionOptions;
  1612. objsec: TOmfObjSection;
  1613. begin
  1614. Result:=False;
  1615. SegDefRec:=TOmfRecord_SEGDEF.Create;
  1616. SegDefRec.DecodeFrom(RawRec);
  1617. if (SegDefRec.SegmentNameIndex<1) or (SegDefRec.SegmentNameIndex>LNames.Count) then
  1618. begin
  1619. InputError('Segment name index out of range');
  1620. SegDefRec.Free;
  1621. exit;
  1622. end;
  1623. SegmentName:=LNames[SegDefRec.SegmentNameIndex];
  1624. if (SegDefRec.ClassNameIndex<1) or (SegDefRec.ClassNameIndex>LNames.Count) then
  1625. begin
  1626. InputError('Segment class name index out of range');
  1627. SegDefRec.Free;
  1628. exit;
  1629. end;
  1630. SegClassName:=LNames[SegDefRec.ClassNameIndex];
  1631. if (SegDefRec.OverlayNameIndex<1) or (SegDefRec.OverlayNameIndex>LNames.Count) then
  1632. begin
  1633. InputError('Segment overlay name index out of range');
  1634. SegDefRec.Free;
  1635. exit;
  1636. end;
  1637. OverlayName:=LNames[SegDefRec.OverlayNameIndex];
  1638. SecAlign:=1; // otherwise warning prohibits compilation
  1639. case SegDefRec.Alignment of
  1640. saRelocatableByteAligned:
  1641. SecAlign:=1;
  1642. saRelocatableWordAligned:
  1643. SecAlign:=2;
  1644. saRelocatableParaAligned:
  1645. SecAlign:=16;
  1646. saRelocatableDWordAligned:
  1647. SecAlign:=4;
  1648. saRelocatablePageAligned:
  1649. SecAlign:=256;
  1650. saNotSupported:
  1651. SecAlign:=4096;
  1652. saAbsolute:
  1653. begin
  1654. InputError('Absolute segment alignment not supported');
  1655. SegDefRec.Free;
  1656. exit;
  1657. end;
  1658. saNotDefined:
  1659. begin
  1660. InputError('Invalid (unsupported/undefined) OMF segment alignment');
  1661. SegDefRec.Free;
  1662. exit;
  1663. end;
  1664. end;
  1665. if not CaseSensitiveSegments then
  1666. begin
  1667. SegmentName:=UpCase(SegmentName);
  1668. SegClassName:=UpCase(SegClassName);
  1669. OverlayName:=UpCase(OverlayName);
  1670. end;
  1671. { hack for supporting object modules, generated by Borland's BINOBJ tool }
  1672. if (SegClassName='') and (SegmentName='CODE') then
  1673. begin
  1674. SegmentName:=InputFileName;
  1675. SegClassName:='CODE';
  1676. end;
  1677. secoptions:=[];
  1678. objsec:=TOmfObjSection(objdata.createsection(SegmentName+'||'+SegClassName,SecAlign,secoptions,false));
  1679. objsec.FClassName:=SegClassName;
  1680. objsec.FOverlayName:=OverlayName;
  1681. objsec.FCombination:=SegDefRec.Combination;
  1682. objsec.FUse:=SegDefRec.Use;
  1683. if SegDefRec.SegmentLength>High(objsec.Size) then
  1684. begin
  1685. InputError('Segment too large');
  1686. SegDefRec.Free;
  1687. exit;
  1688. end;
  1689. objsec.Size:=SegDefRec.SegmentLength;
  1690. if SegClassName='DWARF' then
  1691. objsec.SecOptions:=objsec.SecOptions+[oso_debug];
  1692. if (SegClassName='HEAP') or
  1693. (SegClassName='STACK') or (SegDefRec.Combination=scStack) or
  1694. (SegClassName='BEGDATA') or
  1695. (SegmentName='FPC') then
  1696. objsec.SecOptions:=objsec.SecOptions+[oso_keep];
  1697. SegDefRec.Free;
  1698. Result:=True;
  1699. end;
  1700. function TOmfObjInput.ReadGrpDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1701. var
  1702. GrpDefRec: TOmfRecord_GRPDEF;
  1703. GroupName: string;
  1704. SecGroup: TObjSectionGroup;
  1705. i,SegIndex: Integer;
  1706. begin
  1707. Result:=False;
  1708. GrpDefRec:=TOmfRecord_GRPDEF.Create;
  1709. GrpDefRec.DecodeFrom(RawRec);
  1710. if (GrpDefRec.GroupNameIndex<1) or (GrpDefRec.GroupNameIndex>LNames.Count) then
  1711. begin
  1712. InputError('Group name index out of range');
  1713. GrpDefRec.Free;
  1714. exit;
  1715. end;
  1716. GroupName:=LNames[GrpDefRec.GroupNameIndex];
  1717. if not CaseSensitiveSegments then
  1718. GroupName:=UpCase(GroupName);
  1719. SecGroup:=objdata.createsectiongroup(GroupName);
  1720. SetLength(SecGroup.members,Length(GrpDefRec.SegmentList));
  1721. for i:=0 to Length(GrpDefRec.SegmentList)-1 do
  1722. begin
  1723. SegIndex:=GrpDefRec.SegmentList[i];
  1724. if (SegIndex<1) or (SegIndex>objdata.ObjSectionList.Count) then
  1725. begin
  1726. InputError('Segment name index out of range in group definition');
  1727. GrpDefRec.Free;
  1728. exit;
  1729. end;
  1730. SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
  1731. end;
  1732. GrpDefRec.Free;
  1733. Result:=True;
  1734. end;
  1735. function TOmfObjInput.ReadExtDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1736. var
  1737. ExtDefRec: TOmfRecord_EXTDEF;
  1738. ExtDefElem: TOmfExternalNameElement;
  1739. OldCount,NewCount,i: Integer;
  1740. objsym: TObjSymbol;
  1741. symname: TSymStr;
  1742. begin
  1743. Result:=False;
  1744. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1745. ExtDefRec.ExternalNames:=ExtDefs;
  1746. OldCount:=ExtDefs.Count;
  1747. ExtDefRec.DecodeFrom(RawRec);
  1748. NewCount:=ExtDefs.Count;
  1749. for i:=OldCount to NewCount-1 do
  1750. begin
  1751. ExtDefElem:=TOmfExternalNameElement(ExtDefs[i]);
  1752. symname:=ExtDefElem.Name;
  1753. if not CaseSensitiveSymbols then
  1754. symname:=UpCase(symname);
  1755. objsym:=objdata.CreateSymbol(symname);
  1756. objsym.bind:=AB_EXTERNAL;
  1757. objsym.typ:=AT_FUNCTION;
  1758. objsym.objsection:=nil;
  1759. objsym.offset:=0;
  1760. objsym.size:=0;
  1761. end;
  1762. ExtDefRec.Free;
  1763. Result:=True;
  1764. end;
  1765. function TOmfObjInput.ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1766. var
  1767. PubDefRec: TOmfRecord_PUBDEF;
  1768. PubDefElem: TOmfPublicNameElement;
  1769. OldCount,NewCount,i: Integer;
  1770. basegroup: TObjSectionGroup;
  1771. objsym: TObjSymbol;
  1772. objsec: TOmfObjSection;
  1773. symname: TSymStr;
  1774. begin
  1775. Result:=False;
  1776. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1777. PubDefRec.PublicNames:=PubDefs;
  1778. OldCount:=PubDefs.Count;
  1779. PubDefRec.DecodeFrom(RawRec);
  1780. NewCount:=PubDefs.Count;
  1781. if (PubDefRec.BaseGroupIndex<0) or (PubDefRec.BaseGroupIndex>objdata.GroupsList.Count) then
  1782. begin
  1783. InputError('Public symbol''s group name index out of range');
  1784. PubDefRec.Free;
  1785. exit;
  1786. end;
  1787. if PubDefRec.BaseGroupIndex<>0 then
  1788. basegroup:=TObjSectionGroup(objdata.GroupsList[PubDefRec.BaseGroupIndex-1])
  1789. else
  1790. basegroup:=nil;
  1791. if (PubDefRec.BaseSegmentIndex<0) or (PubDefRec.BaseSegmentIndex>objdata.ObjSectionList.Count) then
  1792. begin
  1793. InputError('Public symbol''s segment name index out of range');
  1794. PubDefRec.Free;
  1795. exit;
  1796. end;
  1797. if PubDefRec.BaseSegmentIndex=0 then
  1798. begin
  1799. InputError('Public symbol uses absolute addressing, which is not supported by this linker');
  1800. PubDefRec.Free;
  1801. exit;
  1802. end;
  1803. objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
  1804. for i:=OldCount to NewCount-1 do
  1805. begin
  1806. PubDefElem:=TOmfPublicNameElement(PubDefs[i]);
  1807. symname:=PubDefElem.Name;
  1808. if not CaseSensitiveSymbols then
  1809. symname:=UpCase(symname);
  1810. objsym:=objdata.CreateSymbol(symname);
  1811. if PubDefElem.IsLocal then
  1812. objsym.bind:=AB_LOCAL
  1813. else
  1814. objsym.bind:=AB_GLOBAL;
  1815. objsym.typ:=AT_FUNCTION;
  1816. objsym.group:=basegroup;
  1817. objsym.objsection:=objsec;
  1818. objsym.offset:=PubDefElem.PublicOffset;
  1819. objsym.size:=0;
  1820. if (objsym.bind=AB_GLOBAL) and (objsec.FFirstSym=nil) then
  1821. objsec.FFirstSym:=objsym;
  1822. end;
  1823. PubDefRec.Free;
  1824. Result:=True;
  1825. end;
  1826. function TOmfObjInput.ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1827. var
  1828. ModEndRec: TOmfRecord_MODEND;
  1829. objsym: TObjSymbol;
  1830. objsec: TOmfObjSection;
  1831. basegroup: TObjSectionGroup;
  1832. begin
  1833. Result:=False;
  1834. ModEndRec:=TOmfRecord_MODEND.Create;
  1835. ModEndRec.DecodeFrom(RawRec);
  1836. if ModEndRec.HasStartAddress then
  1837. begin
  1838. if not ModEndRec.LogicalStartAddress then
  1839. begin
  1840. InputError('Physical start address not supported');
  1841. ModEndRec.Free;
  1842. exit;
  1843. end;
  1844. if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
  1845. begin
  1846. InputError('Target method for start address other than "Segment Index" is not supported');
  1847. ModEndRec.Free;
  1848. exit;
  1849. end;
  1850. if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
  1851. begin
  1852. InputError('Segment name index for start address out of range');
  1853. ModEndRec.Free;
  1854. exit;
  1855. end;
  1856. case ModEndRec.FrameMethod of
  1857. ffmSegmentIndex:
  1858. begin
  1859. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.ObjSectionList.Count) then
  1860. begin
  1861. InputError('Frame segment name index for start address out of range');
  1862. ModEndRec.Free;
  1863. exit;
  1864. end;
  1865. if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
  1866. begin
  1867. InputError('Frame segment different than target segment is not supported supported for start address');
  1868. ModEndRec.Free;
  1869. exit;
  1870. end;
  1871. basegroup:=nil;
  1872. end;
  1873. ffmGroupIndex:
  1874. begin
  1875. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.GroupsList.Count) then
  1876. begin
  1877. InputError('Frame group name index for start address out of range');
  1878. ModEndRec.Free;
  1879. exit;
  1880. end;
  1881. basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
  1882. end;
  1883. else
  1884. begin
  1885. InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
  1886. ModEndRec.Free;
  1887. exit;
  1888. end;
  1889. end;
  1890. objsec:=TOmfObjSection(objdata.ObjSectionList[ModEndRec.TargetDatum-1]);
  1891. objsym:=objdata.CreateSymbol('..start');
  1892. objsym.bind:=AB_GLOBAL;
  1893. objsym.typ:=AT_FUNCTION;
  1894. objsym.group:=basegroup;
  1895. objsym.objsection:=objsec;
  1896. objsym.offset:=ModEndRec.TargetDisplacement;
  1897. objsym.size:=0;
  1898. end;
  1899. ModEndRec.Free;
  1900. Result:=True;
  1901. end;
  1902. function TOmfObjInput.ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1903. var
  1904. Is32Bit: Boolean;
  1905. NextOfs: Integer;
  1906. SegmentIndex: Integer;
  1907. EnumeratedDataOffset: DWord;
  1908. BlockLength: Integer;
  1909. objsec: TOmfObjSection;
  1910. FixupRawRec: TOmfRawRecord=nil;
  1911. Fixup: TOmfSubRecord_FIXUP;
  1912. Thread: TOmfSubRecord_THREAD;
  1913. FixuppWithoutLeOrLiData: Boolean=False;
  1914. begin
  1915. objsec:=nil;
  1916. EnumeratedDataOffset:=0;
  1917. Result:=False;
  1918. case RawRec.RecordType of
  1919. RT_LEDATA,RT_LEDATA32:
  1920. begin
  1921. Is32Bit:=RawRec.RecordType=RT_LEDATA32;
  1922. NextOfs:=RawRec.ReadIndexedRef(0,SegmentIndex);
  1923. if Is32Bit then
  1924. begin
  1925. if (NextOfs+3)>=RawRec.RecordLength then
  1926. internalerror(2015040512);
  1927. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1928. (RawRec.RawData[NextOfs+1] shl 8)+
  1929. (RawRec.RawData[NextOfs+2] shl 16)+
  1930. (RawRec.RawData[NextOfs+3] shl 24);
  1931. Inc(NextOfs,4);
  1932. end
  1933. else
  1934. begin
  1935. if (NextOfs+1)>=RawRec.RecordLength then
  1936. internalerror(2015040513);
  1937. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1938. (RawRec.RawData[NextOfs+1] shl 8);
  1939. Inc(NextOfs,2);
  1940. end;
  1941. BlockLength:=RawRec.RecordLength-NextOfs-1;
  1942. if BlockLength<0 then
  1943. internalerror(2015060501);
  1944. if BlockLength>1024 then
  1945. begin
  1946. InputError('LEDATA contains more than 1024 bytes of data');
  1947. exit;
  1948. end;
  1949. if (SegmentIndex<1) or (SegmentIndex>objdata.ObjSectionList.Count) then
  1950. begin
  1951. InputError('Segment index in LEDATA field is out of range');
  1952. exit;
  1953. end;
  1954. objsec:=TOmfObjSection(objdata.ObjSectionList[SegmentIndex-1]);
  1955. objsec.SecOptions:=objsec.SecOptions+[oso_Data];
  1956. if (objsec.Data.Size>EnumeratedDataOffset) then
  1957. begin
  1958. InputError('LEDATA enumerated data offset field out of sequence');
  1959. exit;
  1960. end;
  1961. if (EnumeratedDataOffset+BlockLength)>objsec.Size then
  1962. begin
  1963. InputError('LEDATA goes beyond the segment size declared in the SEGDEF record');
  1964. exit;
  1965. end;
  1966. objsec.Data.seek(EnumeratedDataOffset);
  1967. objsec.Data.write(RawRec.RawData[NextOfs],BlockLength);
  1968. end;
  1969. RT_LIDATA,RT_LIDATA32:
  1970. begin
  1971. InputError('LIDATA records are not supported');
  1972. exit;
  1973. end;
  1974. RT_FIXUPP,RT_FIXUPP32:
  1975. begin
  1976. FixuppWithoutLeOrLiData:=True;
  1977. { a hack, used to indicate, that we must process this record }
  1978. { (RawRec) first in the FIXUPP record processing loop that follows }
  1979. FixupRawRec:=RawRec;
  1980. end;
  1981. else
  1982. internalerror(2015040316);
  1983. end;
  1984. { also read all the FIXUPP records that may follow; }
  1985. { (FixupRawRec=RawRec) indicates that we must process RawRec first, but }
  1986. { without freeing it }
  1987. while (FixupRawRec=RawRec) or (PeekNextRecordType in [RT_FIXUPP,RT_FIXUPP32]) do
  1988. begin
  1989. if FixupRawRec<>RawRec then
  1990. begin
  1991. FixupRawRec:=TOmfRawRecord.Create;
  1992. FixupRawRec.ReadFrom(FReader);
  1993. if not FRawRecord.VerifyChecksumByte then
  1994. begin
  1995. InputError('Invalid checksum in OMF record');
  1996. FixupRawRec.Free;
  1997. exit;
  1998. end;
  1999. end;
  2000. NextOfs:=0;
  2001. Thread:=TOmfSubRecord_THREAD.Create;
  2002. Fixup:=TOmfSubRecord_FIXUP.Create;
  2003. Fixup.Is32Bit:=FixupRawRec.RecordType=RT_FIXUPP32;
  2004. Fixup.DataRecordStartOffset:=EnumeratedDataOffset;
  2005. while NextOfs<(FixupRawRec.RecordLength-1) do
  2006. begin
  2007. if (FixupRawRec.RawData[NextOfs] and $80)<>0 then
  2008. begin
  2009. { FIXUP subrecord }
  2010. if FixuppWithoutLeOrLiData then
  2011. begin
  2012. InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
  2013. Fixup.Free;
  2014. Thread.Free;
  2015. if FixupRawRec<>RawRec then
  2016. FixupRawRec.Free;
  2017. exit;
  2018. end;
  2019. NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
  2020. Fixup.ResolveByThread(FFixupThreads);
  2021. ImportOmfFixup(objdata,objsec,Fixup);
  2022. end
  2023. else
  2024. begin
  2025. { THREAD subrecord }
  2026. NextOfs:=Thread.ReadAt(FixupRawRec,NextOfs);
  2027. Thread.ApplyTo(FFixupThreads);
  2028. end;
  2029. end;
  2030. Fixup.Free;
  2031. Thread.Free;
  2032. if FixupRawRec<>RawRec then
  2033. FixupRawRec.Free;
  2034. { always set it to null, so that we read the next record on the next }
  2035. { loop iteration (this ensures that FixupRawRec<>RawRec, without }
  2036. { freeing RawRec) }
  2037. FixupRawRec:=nil;
  2038. end;
  2039. Result:=True;
  2040. end;
  2041. function TOmfObjInput.ReadImpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
  2042. var
  2043. ImpDefRec: TOmfRecord_COMENT_IMPDEF;
  2044. SymName: string;
  2045. begin
  2046. ImpDefRec:=TOmfRecord_COMENT_IMPDEF.Create;
  2047. ImpDefRec.DecodeFrom(Rec);
  2048. SymName:=ImpDefRec.InternalName;
  2049. if not CaseSensitiveSymbols then
  2050. SymName:=UpCase(SymName);
  2051. if ImpDefRec.ImportByOrdinal then
  2052. TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),'',SymName,ImpDefRec.Ordinal,false)
  2053. else
  2054. TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),ImpDefRec.Name,SymName,0,false);
  2055. Result:=True;
  2056. ImpDefRec.Free;
  2057. end;
  2058. function TOmfObjInput.ReadExpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
  2059. var
  2060. ExpDefRec: TOmfRecord_COMENT_EXPDEF;
  2061. SymName: string;
  2062. begin
  2063. ExpDefRec:=TOmfRecord_COMENT_EXPDEF.Create;
  2064. ExpDefRec.DecodeFrom(Rec);
  2065. SymName:=ExpDefRec.InternalName;
  2066. if not CaseSensitiveSymbols then
  2067. SymName:=UpCase(SymName);
  2068. TOmfObjData(objdata).AddExportSymbol(
  2069. ExpDefRec.ExportByOrdinal,
  2070. ExpDefRec.ResidentName,
  2071. ExpDefRec.NoData,
  2072. ExpDefRec.ParmCount,
  2073. ExpDefRec.ExportedName,
  2074. SymName,
  2075. ExpDefRec.ExportOrdinal);
  2076. Result:=True;
  2077. ExpDefRec.Free;
  2078. end;
  2079. function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  2080. var
  2081. reloc: TOmfRelocation;
  2082. sym: TObjSymbol;
  2083. RelocType: TObjRelocationType;
  2084. target_section: TOmfObjSection;
  2085. target_group: TObjSectionGroup;
  2086. begin
  2087. Result:=False;
  2088. { range check location }
  2089. if (Fixup.LocationOffset+Fixup.LocationSize)>objsec.Size then
  2090. begin
  2091. InputError('Fixup location exceeds the current segment boundary');
  2092. exit;
  2093. end;
  2094. { range check target datum }
  2095. case Fixup.TargetMethod of
  2096. ftmSegmentIndex:
  2097. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  2098. begin
  2099. InputError('Segment name index in SI(<segment name>),<displacement> fixup target is out of range');
  2100. exit;
  2101. end;
  2102. ftmSegmentIndexNoDisp:
  2103. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  2104. begin
  2105. InputError('Segment name index in SI(<segment name>) fixup target is out of range');
  2106. exit;
  2107. end;
  2108. ftmGroupIndex:
  2109. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  2110. begin
  2111. InputError('Group name index in GI(<group name>),<displacement> fixup target is out of range');
  2112. exit;
  2113. end;
  2114. ftmGroupIndexNoDisp:
  2115. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  2116. begin
  2117. InputError('Group name index in GI(<group name>) fixup target is out of range');
  2118. exit;
  2119. end;
  2120. ftmExternalIndex:
  2121. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2122. begin
  2123. InputError('External symbol name index in EI(<symbol name>),<displacement> fixup target is out of range');
  2124. exit;
  2125. end;
  2126. ftmExternalIndexNoDisp:
  2127. begin
  2128. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2129. begin
  2130. InputError('External symbol name index in EI(<symbol name>) fixup target is out of range');
  2131. exit;
  2132. end;
  2133. end;
  2134. else
  2135. ;
  2136. end;
  2137. { range check frame datum }
  2138. case Fixup.FrameMethod of
  2139. ffmSegmentIndex:
  2140. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.ObjSectionList.Count) then
  2141. begin
  2142. InputError('Segment name index in SI(<segment name>) fixup frame is out of range');
  2143. exit;
  2144. end;
  2145. ffmGroupIndex:
  2146. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.GroupsList.Count) then
  2147. begin
  2148. InputError('Group name index in GI(<group name>) fixup frame is out of range');
  2149. exit;
  2150. end;
  2151. ffmExternalIndex:
  2152. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2153. begin
  2154. InputError('External symbol name index in EI(<symbol name>) fixup frame is out of range');
  2155. exit;
  2156. end;
  2157. else
  2158. ;
  2159. end;
  2160. if Fixup.TargetMethod in [ftmExternalIndex,ftmExternalIndexNoDisp] then
  2161. begin
  2162. sym:=objdata.symbolref(TOmfExternalNameElement(ExtDefs[Fixup.TargetDatum-1]).Name);
  2163. RelocType:=RELOC_NONE;
  2164. case Fixup.LocationType of
  2165. fltOffset:
  2166. case Fixup.Mode of
  2167. fmSegmentRelative:
  2168. RelocType:=RELOC_ABSOLUTE16;
  2169. fmSelfRelative:
  2170. RelocType:=RELOC_RELATIVE16;
  2171. end;
  2172. fltOffset32:
  2173. case Fixup.Mode of
  2174. fmSegmentRelative:
  2175. RelocType:=RELOC_ABSOLUTE32;
  2176. fmSelfRelative:
  2177. RelocType:=RELOC_RELATIVE32;
  2178. end;
  2179. fltBase:
  2180. case Fixup.Mode of
  2181. fmSegmentRelative:
  2182. RelocType:=RELOC_SEG;
  2183. fmSelfRelative:
  2184. RelocType:=RELOC_SEGREL;
  2185. end;
  2186. fltFarPointer:
  2187. case Fixup.Mode of
  2188. fmSegmentRelative:
  2189. RelocType:=RELOC_FARPTR;
  2190. fmSelfRelative:
  2191. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2192. end;
  2193. fltFarPointer48:
  2194. case Fixup.Mode of
  2195. fmSegmentRelative:
  2196. RelocType:=RELOC_FARPTR48;
  2197. fmSelfRelative:
  2198. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2199. end;
  2200. else
  2201. ;
  2202. end;
  2203. if RelocType=RELOC_NONE then
  2204. begin
  2205. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode))+' in external reference to '+sym.Name);
  2206. exit;
  2207. end;
  2208. reloc:=TOmfRelocation.CreateSymbol(Fixup.LocationOffset,sym,RelocType);
  2209. objsec.ObjRelocations.Add(reloc);
  2210. case Fixup.FrameMethod of
  2211. ffmTarget:
  2212. {nothing};
  2213. ffmGroupIndex:
  2214. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  2215. else
  2216. begin
  2217. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in external reference to '+sym.Name);
  2218. exit;
  2219. end;
  2220. end;
  2221. if Fixup.TargetDisplacement<>0 then
  2222. begin
  2223. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in external reference to '+sym.Name);
  2224. exit;
  2225. end;
  2226. end
  2227. else if Fixup.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp] then
  2228. begin
  2229. target_section:=TOmfObjSection(objdata.ObjSectionList[Fixup.TargetDatum-1]);
  2230. RelocType:=RELOC_NONE;
  2231. case Fixup.LocationType of
  2232. fltOffset:
  2233. case Fixup.Mode of
  2234. fmSegmentRelative:
  2235. RelocType:=RELOC_ABSOLUTE16;
  2236. fmSelfRelative:
  2237. RelocType:=RELOC_RELATIVE16;
  2238. end;
  2239. fltOffset32:
  2240. case Fixup.Mode of
  2241. fmSegmentRelative:
  2242. RelocType:=RELOC_ABSOLUTE32;
  2243. fmSelfRelative:
  2244. RelocType:=RELOC_RELATIVE32;
  2245. end;
  2246. fltBase:
  2247. case Fixup.Mode of
  2248. fmSegmentRelative:
  2249. RelocType:=RELOC_SEG;
  2250. fmSelfRelative:
  2251. RelocType:=RELOC_SEGREL;
  2252. end;
  2253. fltFarPointer:
  2254. case Fixup.Mode of
  2255. fmSegmentRelative:
  2256. RelocType:=RELOC_FARPTR;
  2257. fmSelfRelative:
  2258. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2259. end;
  2260. fltFarPointer48:
  2261. case Fixup.Mode of
  2262. fmSegmentRelative:
  2263. RelocType:=RELOC_FARPTR48;
  2264. fmSelfRelative:
  2265. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2266. end;
  2267. else
  2268. ;
  2269. end;
  2270. if RelocType=RELOC_NONE then
  2271. begin
  2272. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  2273. exit;
  2274. end;
  2275. reloc:=TOmfRelocation.CreateSection(Fixup.LocationOffset,target_section,RelocType);
  2276. objsec.ObjRelocations.Add(reloc);
  2277. case Fixup.FrameMethod of
  2278. ffmTarget:
  2279. {nothing};
  2280. ffmGroupIndex:
  2281. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  2282. else
  2283. begin
  2284. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to segment '+target_section.Name);
  2285. exit;
  2286. end;
  2287. end;
  2288. if Fixup.TargetDisplacement<>0 then
  2289. begin
  2290. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to segment '+target_section.Name);
  2291. exit;
  2292. end;
  2293. end
  2294. else if Fixup.TargetMethod in [ftmGroupIndex,ftmGroupIndexNoDisp] then
  2295. begin
  2296. target_group:=TObjSectionGroup(objdata.GroupsList[Fixup.TargetDatum-1]);
  2297. RelocType:=RELOC_NONE;
  2298. case Fixup.LocationType of
  2299. fltOffset:
  2300. case Fixup.Mode of
  2301. fmSegmentRelative:
  2302. RelocType:=RELOC_ABSOLUTE16;
  2303. fmSelfRelative:
  2304. RelocType:=RELOC_RELATIVE16;
  2305. end;
  2306. fltOffset32:
  2307. case Fixup.Mode of
  2308. fmSegmentRelative:
  2309. RelocType:=RELOC_ABSOLUTE32;
  2310. fmSelfRelative:
  2311. RelocType:=RELOC_RELATIVE32;
  2312. end;
  2313. fltBase:
  2314. case Fixup.Mode of
  2315. fmSegmentRelative:
  2316. RelocType:=RELOC_SEG;
  2317. fmSelfRelative:
  2318. RelocType:=RELOC_SEGREL;
  2319. end;
  2320. fltFarPointer:
  2321. case Fixup.Mode of
  2322. fmSegmentRelative:
  2323. RelocType:=RELOC_FARPTR;
  2324. fmSelfRelative:
  2325. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2326. end;
  2327. fltFarPointer48:
  2328. case Fixup.Mode of
  2329. fmSegmentRelative:
  2330. RelocType:=RELOC_FARPTR48;
  2331. fmSelfRelative:
  2332. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2333. end;
  2334. else
  2335. ;
  2336. end;
  2337. if RelocType=RELOC_NONE then
  2338. begin
  2339. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  2340. exit;
  2341. end;
  2342. reloc:=TOmfRelocation.CreateGroup(Fixup.LocationOffset,target_group,RelocType);
  2343. objsec.ObjRelocations.Add(reloc);
  2344. case Fixup.FrameMethod of
  2345. ffmTarget:
  2346. {nothing};
  2347. else
  2348. begin
  2349. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to group '+target_group.Name);
  2350. exit;
  2351. end;
  2352. end;
  2353. if Fixup.TargetDisplacement<>0 then
  2354. begin
  2355. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to group '+target_group.Name);
  2356. exit;
  2357. end;
  2358. end
  2359. else
  2360. begin
  2361. {todo: convert other fixup types as well }
  2362. InputError('Unsupported fixup target method '+IntToStr(Ord(Fixup.TargetMethod)));
  2363. exit;
  2364. end;
  2365. Result:=True;
  2366. end;
  2367. constructor TOmfObjInput.create;
  2368. begin
  2369. inherited create;
  2370. cobjdata:=TOmfObjData;
  2371. FLNames:=TOmfOrderedNameCollection.Create(True);
  2372. FExtDefs:=TFPHashObjectList.Create;
  2373. FPubDefs:=TFPHashObjectList.Create;
  2374. FFixupThreads:=TOmfThreads.Create;
  2375. FRawRecord:=TOmfRawRecord.Create;
  2376. CaseSensitiveSegments:=False;
  2377. CaseSensitiveSymbols:=True;
  2378. end;
  2379. destructor TOmfObjInput.destroy;
  2380. begin
  2381. FCOMENTRecord.Free;
  2382. FRawRecord.Free;
  2383. FFixupThreads.Free;
  2384. FPubDefs.Free;
  2385. FExtDefs.Free;
  2386. FLNames.Free;
  2387. inherited destroy;
  2388. end;
  2389. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2390. var
  2391. b: Byte;
  2392. begin
  2393. result:=false;
  2394. if AReader.Read(b,sizeof(b)) then
  2395. begin
  2396. if b=RT_THEADR then
  2397. { TODO: check additional fields }
  2398. result:=true;
  2399. end;
  2400. AReader.Seek(0);
  2401. end;
  2402. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  2403. begin
  2404. FReader:=AReader;
  2405. InputFileName:=AReader.FileName;
  2406. objdata:=CObjData.Create(InputFileName);
  2407. result:=false;
  2408. { the TOmfObjData constructor creates a group 'DGROUP', which is to be
  2409. used by the code generator, when writing files. When reading object
  2410. files, however, we need to start with an empty list of groups, so
  2411. let's clear the group list now. }
  2412. objdata.GroupsList.Clear;
  2413. LNames.Clear;
  2414. ExtDefs.Clear;
  2415. FRawRecord.ReadFrom(FReader);
  2416. if not FRawRecord.VerifyChecksumByte then
  2417. begin
  2418. InputError('Invalid checksum in OMF record');
  2419. exit;
  2420. end;
  2421. if FRawRecord.RecordType<>RT_THEADR then
  2422. begin
  2423. InputError('Can''t read OMF header');
  2424. exit;
  2425. end;
  2426. repeat
  2427. FRawRecord.ReadFrom(FReader);
  2428. if not FRawRecord.VerifyChecksumByte then
  2429. begin
  2430. InputError('Invalid checksum in OMF record');
  2431. exit;
  2432. end;
  2433. FreeAndNil(FCOMENTRecord);
  2434. case FRawRecord.RecordType of
  2435. RT_LNAMES:
  2436. if not ReadLNames(FRawRecord) then
  2437. exit;
  2438. RT_SEGDEF,RT_SEGDEF32:
  2439. if not ReadSegDef(FRawRecord,objdata) then
  2440. exit;
  2441. RT_GRPDEF:
  2442. if not ReadGrpDef(FRawRecord,objdata) then
  2443. exit;
  2444. RT_COMENT:
  2445. begin
  2446. FCOMENTRecord:=TOmfRecord_COMENT.Create;
  2447. FCOMENTRecord.DecodeFrom(FRawRecord);
  2448. case FCOMENTRecord.CommentClass of
  2449. CC_OmfExtension:
  2450. begin
  2451. if Length(FCOMENTRecord.CommentString)>=1 then
  2452. begin
  2453. case Ord(FCOMENTRecord.CommentString[1]) of
  2454. CC_OmfExtension_IMPDEF:
  2455. if not ReadImpDef(FCOMENTRecord,objdata) then
  2456. exit;
  2457. CC_OmfExtension_EXPDEF:
  2458. if not ReadExpDef(FCOMENTRecord,objdata) then
  2459. exit;
  2460. end;
  2461. end;
  2462. end;
  2463. CC_LIBMOD:
  2464. begin
  2465. {todo: do we need to read the module name here?}
  2466. end;
  2467. CC_EXESTR:
  2468. begin
  2469. InputError('EXESTR record (Executable String Record) is not supported');
  2470. exit;
  2471. end;
  2472. CC_INCERR:
  2473. begin
  2474. InputError('Invalid object file (contains indication of error encountered during incremental compilation)');
  2475. exit;
  2476. end;
  2477. CC_NOPAD:
  2478. begin
  2479. InputError('NOPAD (No Segment Padding) record is not supported');
  2480. exit;
  2481. end;
  2482. CC_WKEXT:
  2483. begin
  2484. InputError('Weak externals are not supported');
  2485. exit;
  2486. end;
  2487. CC_LZEXT:
  2488. begin
  2489. InputError('Lazy externals are not supported');
  2490. exit;
  2491. end;
  2492. else
  2493. begin
  2494. {the rest are ignored for now...}
  2495. end;
  2496. end;
  2497. end;
  2498. RT_EXTDEF:
  2499. if not ReadExtDef(FRawRecord,objdata) then
  2500. exit;
  2501. RT_LPUBDEF,RT_LPUBDEF32,
  2502. RT_PUBDEF,RT_PUBDEF32:
  2503. if not ReadPubDef(FRawRecord,objdata) then
  2504. exit;
  2505. RT_LEDATA,RT_LEDATA32,
  2506. RT_LIDATA,RT_LIDATA32,
  2507. RT_FIXUPP,RT_FIXUPP32:
  2508. if not ReadLeOrLiDataAndFixups(FRawRecord,objdata) then
  2509. exit;
  2510. RT_MODEND,RT_MODEND32:
  2511. if not ReadModEnd(FRawRecord,objdata) then
  2512. exit;
  2513. RT_LINNUM,RT_LINNUM32:
  2514. ;
  2515. else
  2516. begin
  2517. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  2518. exit;
  2519. end;
  2520. end;
  2521. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  2522. result:=true;
  2523. end;
  2524. {****************************************************************************
  2525. TMZExeHeader
  2526. ****************************************************************************}
  2527. procedure TMZExeHeader.SetHeaderSizeAlignment(AValue: Integer);
  2528. begin
  2529. if (AValue<16) or ((AValue mod 16) <> 0) then
  2530. Internalerror(2015060601);
  2531. FHeaderSizeAlignment:=AValue;
  2532. end;
  2533. constructor TMZExeHeader.Create;
  2534. begin
  2535. FHeaderSizeAlignment:=16;
  2536. end;
  2537. procedure TMZExeHeader.WriteTo(aWriter: TObjectWriter);
  2538. var
  2539. NumRelocs: Word;
  2540. HeaderSizeInBytes: DWord;
  2541. HeaderParagraphs: Word;
  2542. RelocTableOffset: Word;
  2543. BytesInLastBlock: Word;
  2544. BlocksInFile: Word;
  2545. HeaderBytes: array [0..$1B] of Byte;
  2546. RelocBytes: array [0..3] of Byte;
  2547. TotalExeSize: DWord;
  2548. i: Integer;
  2549. begin
  2550. NumRelocs:=Length(Relocations);
  2551. RelocTableOffset:=$1C+Length(ExtraHeaderData);
  2552. HeaderSizeInBytes:=Align(RelocTableOffset+4*NumRelocs,16);
  2553. HeaderParagraphs:=HeaderSizeInBytes div 16;
  2554. TotalExeSize:=HeaderSizeInBytes+LoadableImageSize;
  2555. BlocksInFile:=(TotalExeSize+511) div 512;
  2556. BytesInLastBlock:=TotalExeSize mod 512;
  2557. HeaderBytes[$00]:=$4D; { 'M' }
  2558. HeaderBytes[$01]:=$5A; { 'Z' }
  2559. HeaderBytes[$02]:=Byte(BytesInLastBlock);
  2560. HeaderBytes[$03]:=Byte(BytesInLastBlock shr 8);
  2561. HeaderBytes[$04]:=Byte(BlocksInFile);
  2562. HeaderBytes[$05]:=Byte(BlocksInFile shr 8);
  2563. HeaderBytes[$06]:=Byte(NumRelocs);
  2564. HeaderBytes[$07]:=Byte(NumRelocs shr 8);
  2565. HeaderBytes[$08]:=Byte(HeaderParagraphs);
  2566. HeaderBytes[$09]:=Byte(HeaderParagraphs shr 8);
  2567. HeaderBytes[$0A]:=Byte(MinExtraParagraphs);
  2568. HeaderBytes[$0B]:=Byte(MinExtraParagraphs shr 8);
  2569. HeaderBytes[$0C]:=Byte(MaxExtraParagraphs);
  2570. HeaderBytes[$0D]:=Byte(MaxExtraParagraphs shr 8);
  2571. HeaderBytes[$0E]:=Byte(InitialSS);
  2572. HeaderBytes[$0F]:=Byte(InitialSS shr 8);
  2573. HeaderBytes[$10]:=Byte(InitialSP);
  2574. HeaderBytes[$11]:=Byte(InitialSP shr 8);
  2575. HeaderBytes[$12]:=Byte(Checksum);
  2576. HeaderBytes[$13]:=Byte(Checksum shr 8);
  2577. HeaderBytes[$14]:=Byte(InitialIP);
  2578. HeaderBytes[$15]:=Byte(InitialIP shr 8);
  2579. HeaderBytes[$16]:=Byte(InitialCS);
  2580. HeaderBytes[$17]:=Byte(InitialCS shr 8);
  2581. HeaderBytes[$18]:=Byte(RelocTableOffset);
  2582. HeaderBytes[$19]:=Byte(RelocTableOffset shr 8);
  2583. HeaderBytes[$1A]:=Byte(OverlayNumber);
  2584. HeaderBytes[$1B]:=Byte(OverlayNumber shr 8);
  2585. aWriter.write(HeaderBytes[0],$1C);
  2586. aWriter.write(ExtraHeaderData[0],Length(ExtraHeaderData));
  2587. for i:=0 to NumRelocs-1 do
  2588. with Relocations[i] do
  2589. begin
  2590. RelocBytes[0]:=Byte(offset);
  2591. RelocBytes[1]:=Byte(offset shr 8);
  2592. RelocBytes[2]:=Byte(segment);
  2593. RelocBytes[3]:=Byte(segment shr 8);
  2594. aWriter.write(RelocBytes[0],4);
  2595. end;
  2596. { pad with zeros until the end of header (paragraph aligned) }
  2597. aWriter.WriteZeros(HeaderSizeInBytes-aWriter.Size);
  2598. end;
  2599. procedure TMZExeHeader.AddRelocation(aSegment, aOffset: Word);
  2600. begin
  2601. SetLength(FRelocations,Length(FRelocations)+1);
  2602. with FRelocations[High(FRelocations)] do
  2603. begin
  2604. segment:=aSegment;
  2605. offset:=aOffset;
  2606. end;
  2607. end;
  2608. {****************************************************************************
  2609. TMZExeSection
  2610. ****************************************************************************}
  2611. procedure TMZExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  2612. begin
  2613. { allow mixing initialized and uninitialized data in the same section
  2614. => set ignoreprops=true }
  2615. inherited AddObjSection(objsec,true);
  2616. end;
  2617. {****************************************************************************
  2618. TMZExeUnifiedLogicalSegment
  2619. ****************************************************************************}
  2620. constructor TMZExeUnifiedLogicalSegment.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2621. var
  2622. Separator: SizeInt;
  2623. begin
  2624. inherited create(HashObjectList,s);
  2625. FObjSectionList:=TFPObjectList.Create(false);
  2626. { name format is 'SegName||ClassName' }
  2627. Separator:=Pos('||',s);
  2628. if Separator>0 then
  2629. begin
  2630. FSegName:=Copy(s,1,Separator-1);
  2631. FSegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  2632. end
  2633. else
  2634. begin
  2635. FSegName:=Name;
  2636. FSegClass:='';
  2637. end;
  2638. { wlink recognizes the stack segment by the class name 'STACK' }
  2639. { let's be compatible with wlink }
  2640. IsStack:=FSegClass='STACK';
  2641. end;
  2642. destructor TMZExeUnifiedLogicalSegment.destroy;
  2643. begin
  2644. FObjSectionList.Free;
  2645. inherited destroy;
  2646. end;
  2647. procedure TMZExeUnifiedLogicalSegment.AddObjSection(ObjSec: TOmfObjSection);
  2648. begin
  2649. ObjSectionList.Add(ObjSec);
  2650. ObjSec.MZExeUnifiedLogicalSegment:=self;
  2651. { tlink (and ms link?) use the scStack segment combination to recognize
  2652. the stack segment.
  2653. let's be compatible with tlink as well }
  2654. if ObjSec.Combination=scStack then
  2655. IsStack:=True;
  2656. end;
  2657. procedure TMZExeUnifiedLogicalSegment.CalcMemPos;
  2658. var
  2659. MinMemPos: qword=high(qword);
  2660. MaxMemPos: qword=0;
  2661. objsec: TOmfObjSection;
  2662. i: Integer;
  2663. begin
  2664. if ObjSectionList.Count=0 then
  2665. internalerror(2015082201);
  2666. for i:=0 to ObjSectionList.Count-1 do
  2667. begin
  2668. objsec:=TOmfObjSection(ObjSectionList[i]);
  2669. if objsec.MemPos<MinMemPos then
  2670. MinMemPos:=objsec.MemPos;
  2671. if (objsec.MemPos+objsec.Size)>MaxMemPos then
  2672. MaxMemPos:=objsec.MemPos+objsec.Size;
  2673. end;
  2674. MemPos:=MinMemPos;
  2675. Size:=MaxMemPos-MemPos;
  2676. end;
  2677. function TMZExeUnifiedLogicalSegment.MemPosStr: string;
  2678. begin
  2679. Result:=HexStr(MemBasePos shr 4,4)+':'+HexStr((MemPos-MemBasePos),4);
  2680. end;
  2681. {****************************************************************************
  2682. TMZExeUnifiedLogicalGroup
  2683. ****************************************************************************}
  2684. constructor TMZExeUnifiedLogicalGroup.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2685. begin
  2686. inherited create(HashObjectList,s);
  2687. FSegmentList:=TFPHashObjectList.Create(false);
  2688. end;
  2689. destructor TMZExeUnifiedLogicalGroup.destroy;
  2690. begin
  2691. FSegmentList.Free;
  2692. inherited destroy;
  2693. end;
  2694. procedure TMZExeUnifiedLogicalGroup.CalcMemPos;
  2695. var
  2696. MinMemPos: qword=high(qword);
  2697. MaxMemPos: qword=0;
  2698. UniSeg: TMZExeUnifiedLogicalSegment;
  2699. i: Integer;
  2700. begin
  2701. if SegmentList.Count=0 then
  2702. internalerror(2015082202);
  2703. for i:=0 to SegmentList.Count-1 do
  2704. begin
  2705. UniSeg:=TMZExeUnifiedLogicalSegment(SegmentList[i]);
  2706. if UniSeg.MemPos<MinMemPos then
  2707. MinMemPos:=UniSeg.MemPos;
  2708. if (UniSeg.MemPos+UniSeg.Size)>MaxMemPos then
  2709. MaxMemPos:=UniSeg.MemPos+UniSeg.Size;
  2710. end;
  2711. { align *down* on a paragraph boundary }
  2712. MemPos:=(MinMemPos shr 4) shl 4;
  2713. Size:=MaxMemPos-MemPos;
  2714. end;
  2715. function TMZExeUnifiedLogicalGroup.MemPosStr: string;
  2716. begin
  2717. Result:=HexStr(MemPos shr 4,4)+':'+HexStr(MemPos and $f,4);
  2718. end;
  2719. procedure TMZExeUnifiedLogicalGroup.AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  2720. begin
  2721. SegmentList.Add(UniSeg.Name,UniSeg);
  2722. if UniSeg.PrimaryGroup='' then
  2723. UniSeg.PrimaryGroup:=Name;
  2724. end;
  2725. {****************************************************************************
  2726. TMZExeOutput
  2727. ****************************************************************************}
  2728. function TMZExeOutput.GetMZFlatContentSection: TMZExeSection;
  2729. begin
  2730. if not assigned(FMZFlatContentSection) then
  2731. FMZFlatContentSection:=TMZExeSection(FindExeSection('.MZ_flat_content'));
  2732. result:=FMZFlatContentSection;
  2733. end;
  2734. procedure TMZExeOutput.CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  2735. var
  2736. ExeSec: TMZExeSection;
  2737. ObjSec: TOmfObjSection;
  2738. UniSeg: TMZExeUnifiedLogicalSegment;
  2739. i: Integer;
  2740. begin
  2741. ExeSec:=TMZExeSection(FindExeSection(SecName));
  2742. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2743. begin
  2744. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2745. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments.Find(ObjSec.Name));
  2746. if not assigned(UniSeg) then
  2747. begin
  2748. UniSeg:=TMZExeUnifiedLogicalSegment.Create(DwarfUnifiedLogicalSegments,ObjSec.Name);
  2749. UniSeg.MemPos:=0;
  2750. end;
  2751. UniSeg.AddObjSection(ObjSec);
  2752. end;
  2753. for i:=0 to DwarfUnifiedLogicalSegments.Count-1 do
  2754. begin
  2755. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments[i]);
  2756. UniSeg.CalcMemPos;
  2757. end;
  2758. end;
  2759. procedure TMZExeOutput.CalcExeUnifiedLogicalSegments;
  2760. var
  2761. ExeSec: TMZExeSection;
  2762. ObjSec: TOmfObjSection;
  2763. UniSeg: TMZExeUnifiedLogicalSegment;
  2764. i: Integer;
  2765. begin
  2766. ExeSec:=MZFlatContentSection;
  2767. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2768. begin
  2769. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2770. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments.Find(ObjSec.Name));
  2771. if not assigned(UniSeg) then
  2772. UniSeg:=TMZExeUnifiedLogicalSegment.Create(ExeUnifiedLogicalSegments,ObjSec.Name);
  2773. UniSeg.AddObjSection(ObjSec);
  2774. end;
  2775. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2776. begin
  2777. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2778. UniSeg.CalcMemPos;
  2779. if UniSeg.Size>$10000 then
  2780. begin
  2781. if current_settings.x86memorymodel=mm_tiny then
  2782. Message1(link_e_program_segment_too_large,IntToStr(UniSeg.Size-$10000))
  2783. else if UniSeg.SegClass='CODE' then
  2784. Message2(link_e_code_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2785. else if UniSeg.SegClass='DATA' then
  2786. Message2(link_e_data_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2787. else
  2788. Message2(link_e_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000)+' '+UniSeg.SegName);
  2789. end;
  2790. end;
  2791. end;
  2792. procedure TMZExeOutput.CalcExeGroups;
  2793. procedure AddToGroup(UniSeg:TMZExeUnifiedLogicalSegment;GroupName:TSymStr);
  2794. var
  2795. Group: TMZExeUnifiedLogicalGroup;
  2796. begin
  2797. Group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(GroupName));
  2798. if not assigned(Group) then
  2799. Group:=TMZExeUnifiedLogicalGroup.Create(ExeUnifiedLogicalGroups,GroupName);
  2800. Group.AddSegment(UniSeg);
  2801. end;
  2802. var
  2803. objdataidx,groupidx,secidx: Integer;
  2804. ObjData: TObjData;
  2805. ObjGroup: TObjSectionGroup;
  2806. ObjSec: TOmfObjSection;
  2807. UniGrp: TMZExeUnifiedLogicalGroup;
  2808. begin
  2809. for objdataidx:=0 to ObjDataList.Count-1 do
  2810. begin
  2811. ObjData:=TObjData(ObjDataList[objdataidx]);
  2812. if assigned(ObjData.GroupsList) then
  2813. for groupidx:=0 to ObjData.GroupsList.Count-1 do
  2814. begin
  2815. ObjGroup:=TObjSectionGroup(ObjData.GroupsList[groupidx]);
  2816. for secidx:=low(ObjGroup.members) to high(ObjGroup.members) do
  2817. begin
  2818. ObjSec:=TOmfObjSection(ObjGroup.members[secidx]);
  2819. if assigned(ObjSec.MZExeUnifiedLogicalSegment) then
  2820. AddToGroup(ObjSec.MZExeUnifiedLogicalSegment,ObjGroup.Name);
  2821. end;
  2822. end;
  2823. end;
  2824. for groupidx:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2825. begin
  2826. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[groupidx]);
  2827. UniGrp.CalcMemPos;
  2828. if UniGrp.Size>$10000 then
  2829. begin
  2830. if current_settings.x86memorymodel=mm_tiny then
  2831. Message1(link_e_program_segment_too_large,IntToStr(UniGrp.Size-$10000))
  2832. else if UniGrp.Name='DGROUP' then
  2833. Message2(link_e_data_segment_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000))
  2834. else
  2835. Message2(link_e_group_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000));
  2836. end;
  2837. end;
  2838. end;
  2839. procedure TMZExeOutput.CalcSegments_MemBasePos;
  2840. var
  2841. lastbase:qword=0;
  2842. i: Integer;
  2843. UniSeg: TMZExeUnifiedLogicalSegment;
  2844. begin
  2845. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2846. begin
  2847. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2848. if (UniSeg.PrimaryGroup<>'') or (UniSeg.IsStack) or
  2849. (((UniSeg.MemPos+UniSeg.Size-1)-lastbase)>$ffff) then
  2850. lastbase:=(UniSeg.MemPos shr 4) shl 4;
  2851. UniSeg.MemBasePos:=lastbase;
  2852. end;
  2853. end;
  2854. procedure TMZExeOutput.WriteMap_SegmentsAndGroups;
  2855. var
  2856. i, LongestGroupName, LongestSegmentName, LongestClassName: Integer;
  2857. UniSeg: TMZExeUnifiedLogicalSegment;
  2858. UniGrp: TMZExeUnifiedLogicalGroup;
  2859. GroupColumnSize, SegmentColumnSize, ClassColumnSize: LongInt;
  2860. begin
  2861. LongestGroupName:=0;
  2862. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2863. begin
  2864. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2865. LongestGroupName:=max(LongestGroupName,Length(UniGrp.Name));
  2866. end;
  2867. LongestSegmentName:=0;
  2868. LongestClassName:=0;
  2869. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2870. begin
  2871. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2872. LongestSegmentName:=max(LongestSegmentName,Length(UniSeg.SegName));
  2873. LongestClassName:=max(LongestClassName,Length(UniSeg.SegClass));
  2874. end;
  2875. GroupColumnSize:=max(32,LongestGroupName+1);
  2876. SegmentColumnSize:=max(23,LongestSegmentName+1);
  2877. ClassColumnSize:=max(15,LongestClassName+1);
  2878. exemap.AddHeader('Groups list');
  2879. exemap.Add('');
  2880. exemap.Add(PadSpace('Group',GroupColumnSize)+PadSpace('Address',21)+'Size');
  2881. exemap.Add(PadSpace('=====',GroupColumnSize)+PadSpace('=======',21)+'====');
  2882. exemap.Add('');
  2883. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2884. begin
  2885. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2886. exemap.Add(PadSpace(UniGrp.Name,GroupColumnSize)+PadSpace(UniGrp.MemPosStr,21)+HexStr(UniGrp.Size,8));
  2887. end;
  2888. exemap.Add('');
  2889. GroupColumnSize:=max(15,LongestGroupName+1);
  2890. exemap.AddHeader('Segments list');
  2891. exemap.Add('');
  2892. exemap.Add(PadSpace('Segment',SegmentColumnSize)+PadSpace('Class',ClassColumnSize)+PadSpace('Group',GroupColumnSize)+PadSpace('Address',16)+'Size');
  2893. exemap.Add(PadSpace('=======',SegmentColumnSize)+PadSpace('=====',ClassColumnSize)+PadSpace('=====',GroupColumnSize)+PadSpace('=======',16)+'====');
  2894. exemap.Add('');
  2895. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2896. begin
  2897. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2898. exemap.Add(PadSpace(UniSeg.SegName,SegmentColumnSize)+PadSpace(UniSeg.SegClass,ClassColumnSize)+PadSpace(UniSeg.PrimaryGroup,GroupColumnSize)+PadSpace(UniSeg.MemPosStr,16)+HexStr(UniSeg.Size,8));
  2899. end;
  2900. exemap.Add('');
  2901. end;
  2902. procedure TMZExeOutput.WriteMap_HeaderData;
  2903. begin
  2904. exemap.AddHeader('Header data');
  2905. exemap.Add('Loadable image size: '+HexStr(Header.LoadableImageSize,8));
  2906. exemap.Add('Min extra paragraphs: '+HexStr(Header.MinExtraParagraphs,4));
  2907. exemap.Add('Max extra paragraphs: '+HexStr(Header.MaxExtraParagraphs,4));
  2908. exemap.Add('Initial stack pointer: '+HexStr(Header.InitialSS,4)+':'+HexStr(Header.InitialSP,4));
  2909. exemap.Add('Entry point address: '+HexStr(Header.InitialCS,4)+':'+HexStr(Header.InitialIP,4));
  2910. end;
  2911. function TMZExeOutput.FindStackSegment: TMZExeUnifiedLogicalSegment;
  2912. var
  2913. i: Integer;
  2914. stackseg_wannabe: TMZExeUnifiedLogicalSegment;
  2915. begin
  2916. Result:=nil;
  2917. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2918. begin
  2919. stackseg_wannabe:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2920. { if there are multiple stack segments, choose the largest one.
  2921. In theory, we're probably supposed to combine them all and put
  2922. them in a contiguous location in memory, but we don't care }
  2923. if stackseg_wannabe.IsStack and
  2924. (not assigned(result) or (Result.Size<stackseg_wannabe.Size)) then
  2925. Result:=stackseg_wannabe;
  2926. end;
  2927. end;
  2928. procedure TMZExeOutput.FillLoadableImageSize;
  2929. var
  2930. i: Integer;
  2931. ExeSec: TMZExeSection;
  2932. ObjSec: TOmfObjSection;
  2933. begin
  2934. Header.LoadableImageSize:=0;
  2935. ExeSec:=MZFlatContentSection;
  2936. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2937. begin
  2938. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2939. if (ObjSec.Size>0) and assigned(ObjSec.Data) then
  2940. if (ObjSec.MemPos+ObjSec.Size)>Header.LoadableImageSize then
  2941. Header.LoadableImageSize:=ObjSec.MemPos+ObjSec.Size;
  2942. end;
  2943. end;
  2944. procedure TMZExeOutput.FillMinExtraParagraphs;
  2945. var
  2946. ExeSec: TMZExeSection;
  2947. begin
  2948. ExeSec:=MZFlatContentSection;
  2949. Header.MinExtraParagraphs:=(align(ExeSec.Size,16)-align(Header.LoadableImageSize,16)) div 16;
  2950. end;
  2951. procedure TMZExeOutput.FillMaxExtraParagraphs;
  2952. var
  2953. heapmin_paragraphs: Integer;
  2954. heapmax_paragraphs: Integer;
  2955. begin
  2956. if current_settings.x86memorymodel in x86_far_data_models then
  2957. begin
  2958. { calculate the additional number of paragraphs needed }
  2959. heapmin_paragraphs:=(heapsize + 15) div 16;
  2960. heapmax_paragraphs:=(maxheapsize + 15) div 16;
  2961. Header.MaxExtraParagraphs:=min(Header.MinExtraParagraphs-heapmin_paragraphs+heapmax_paragraphs,$FFFF);
  2962. end
  2963. else
  2964. Header.MaxExtraParagraphs:=$FFFF;
  2965. end;
  2966. procedure TMZExeOutput.FillStartAddress;
  2967. var
  2968. EntryMemPos: qword;
  2969. EntryMemBasePos: qword;
  2970. begin
  2971. EntryMemPos:=EntrySym.address;
  2972. if assigned(EntrySym.group) then
  2973. EntryMemBasePos:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(EntrySym.group.Name)).MemPos
  2974. else
  2975. EntryMemBasePos:=TOmfObjSection(EntrySym.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2976. Header.InitialIP:=EntryMemPos-EntryMemBasePos;
  2977. Header.InitialCS:=EntryMemBasePos shr 4;
  2978. end;
  2979. procedure TMZExeOutput.FillStackAddress;
  2980. var
  2981. stackseg: TMZExeUnifiedLogicalSegment;
  2982. begin
  2983. stackseg:=FindStackSegment;
  2984. if assigned(stackseg) then
  2985. begin
  2986. Header.InitialSS:=stackseg.MemBasePos shr 4;
  2987. Header.InitialSP:=stackseg.MemPos+stackseg.Size-stackseg.MemBasePos;
  2988. end
  2989. else
  2990. begin
  2991. Header.InitialSS:=0;
  2992. Header.InitialSP:=0;
  2993. end;
  2994. end;
  2995. procedure TMZExeOutput.FillHeaderData;
  2996. begin
  2997. Header.MaxExtraParagraphs:=$FFFF;
  2998. FillLoadableImageSize;
  2999. FillMinExtraParagraphs;
  3000. FillMaxExtraParagraphs;
  3001. FillStartAddress;
  3002. FillStackAddress;
  3003. if assigned(exemap) then
  3004. WriteMap_HeaderData;
  3005. end;
  3006. function TMZExeOutput.writeExe: boolean;
  3007. var
  3008. ExeSec: TMZExeSection;
  3009. i: Integer;
  3010. ObjSec: TOmfObjSection;
  3011. begin
  3012. Result:=False;
  3013. FillHeaderData;
  3014. Header.WriteTo(FWriter);
  3015. ExeSec:=MZFlatContentSection;
  3016. ExeSec.DataPos:=FWriter.Size;
  3017. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  3018. begin
  3019. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  3020. if ObjSec.MemPos<Header.LoadableImageSize then
  3021. begin
  3022. FWriter.WriteZeros(max(0,ObjSec.MemPos-FWriter.Size+ExeSec.DataPos));
  3023. if assigned(ObjSec.Data) then
  3024. FWriter.writearray(ObjSec.Data);
  3025. end;
  3026. end;
  3027. Result:=True;
  3028. end;
  3029. function TMZExeOutput.writeCom: boolean;
  3030. const
  3031. ComFileOffset=$100;
  3032. var
  3033. i: Integer;
  3034. ExeSec: TMZExeSection;
  3035. ObjSec: TOmfObjSection;
  3036. buf: array [0..1023] of byte;
  3037. bytesread: LongWord;
  3038. begin
  3039. FillHeaderData;
  3040. if Length(Header.Relocations)>0 then
  3041. begin
  3042. Message(link_e_com_program_uses_segment_relocations);
  3043. exit(False);
  3044. end;
  3045. ExeSec:=MZFlatContentSection;
  3046. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  3047. begin
  3048. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  3049. if ObjSec.MemPos<Header.LoadableImageSize then
  3050. begin
  3051. FWriter.WriteZeros(max(0,int64(ObjSec.MemPos)-ComFileOffset-int64(FWriter.Size)));
  3052. if assigned(ObjSec.Data) then
  3053. begin
  3054. if ObjSec.MemPos<ComFileOffset then
  3055. begin
  3056. ObjSec.Data.seek(ComFileOffset-ObjSec.MemPos);
  3057. repeat
  3058. bytesread:=ObjSec.Data.read(buf,sizeof(buf));
  3059. if bytesread<>0 then
  3060. FWriter.write(buf,bytesread);
  3061. until bytesread=0;
  3062. end
  3063. else
  3064. FWriter.writearray(ObjSec.Data);
  3065. end;
  3066. end;
  3067. end;
  3068. Result:=True;
  3069. end;
  3070. function TMZExeOutput.writeDebugElf: boolean;
  3071. label
  3072. cleanup;
  3073. var
  3074. debugsections: array of TMZExeSection;
  3075. debugsections_count: Word;
  3076. elfsections_count: Word;
  3077. elfsechdrs: array of TElf32sechdr;
  3078. shstrndx: Word;
  3079. next_section_ofs, elf_start_pos, elf_end_pos: LongWord;
  3080. ElfHeader: TElf32header;
  3081. shstrtabsect_data: TDynamicArray=Nil;
  3082. I, elfsecidx, J: Integer;
  3083. ObjSec: TOmfObjSection;
  3084. tis_trailer: TTISTrailer;
  3085. begin
  3086. debugsections:=nil;
  3087. elfsechdrs:=nil;
  3088. { mark the offset of the start of the ELF image }
  3089. elf_start_pos:=Writer.Size;
  3090. { count the debug sections }
  3091. debugsections_count:=0;
  3092. for I:=0 to ExeSectionList.Count-1 do
  3093. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  3094. Inc(debugsections_count);
  3095. { extract them into the debugsections array }
  3096. SetLength(debugsections,debugsections_count);
  3097. debugsections_count:=0;
  3098. for I:=0 to ExeSectionList.Count-1 do
  3099. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  3100. begin
  3101. debugsections[debugsections_count]:=TMZExeSection(ExeSectionList[I]);
  3102. Inc(debugsections_count);
  3103. end;
  3104. { prepare/allocate elf section headers }
  3105. elfsections_count:=debugsections_count+2;
  3106. SetLength(elfsechdrs,elfsections_count);
  3107. for I:=0 to elfsections_count-1 do
  3108. FillChar(elfsechdrs[I],SizeOf(elfsechdrs[I]),0);
  3109. shstrndx:=elfsections_count-1;
  3110. shstrtabsect_data:=tdynamicarray.Create(SectionDataMaxGrow);
  3111. shstrtabsect_data.writestr(#0);
  3112. next_section_ofs:=SizeOf(ElfHeader)+elfsections_count*SizeOf(TElf32sechdr);
  3113. for I:=0 to debugsections_count-1 do
  3114. begin
  3115. elfsecidx:=I+1;
  3116. with elfsechdrs[elfsecidx] do
  3117. begin
  3118. sh_name:=shstrtabsect_data.Pos;
  3119. sh_type:=SHT_PROGBITS;
  3120. sh_flags:=0;
  3121. sh_addr:=0;
  3122. sh_offset:=next_section_ofs;
  3123. sh_size:=debugsections[I].Size;
  3124. sh_link:=0;
  3125. sh_info:=0;
  3126. sh_addralign:=0;
  3127. sh_entsize:=0;
  3128. end;
  3129. Inc(next_section_ofs,debugsections[I].Size);
  3130. shstrtabsect_data.writestr(debugsections[I].Name+#0);
  3131. end;
  3132. with elfsechdrs[shstrndx] do
  3133. begin
  3134. sh_name:=shstrtabsect_data.Pos;
  3135. shstrtabsect_data.writestr('.shstrtab'#0);
  3136. sh_type:=SHT_STRTAB;
  3137. sh_flags:=0;
  3138. sh_addr:=0;
  3139. sh_offset:=next_section_ofs;
  3140. sh_size:=shstrtabsect_data.Size;
  3141. sh_link:=0;
  3142. sh_info:=0;
  3143. sh_addralign:=0;
  3144. sh_entsize:=0;
  3145. end;
  3146. { write header }
  3147. FillChar(ElfHeader,SizeOf(ElfHeader),0);
  3148. ElfHeader.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  3149. ElfHeader.e_ident[EI_MAG1]:=ELFMAG1;
  3150. ElfHeader.e_ident[EI_MAG2]:=ELFMAG2;
  3151. ElfHeader.e_ident[EI_MAG3]:=ELFMAG3;
  3152. ElfHeader.e_ident[EI_CLASS]:=ELFCLASS32;
  3153. ElfHeader.e_ident[EI_DATA]:=ELFDATA2LSB;
  3154. ElfHeader.e_ident[EI_VERSION]:=1;
  3155. ElfHeader.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  3156. ElfHeader.e_ident[EI_ABIVERSION]:=0;
  3157. ElfHeader.e_type:=ET_EXEC;
  3158. ElfHeader.e_machine:=EM_386;
  3159. ElfHeader.e_version:=1;
  3160. ElfHeader.e_entry:=0;
  3161. ElfHeader.e_phoff:=0;
  3162. ElfHeader.e_shoff:=SizeOf(ElfHeader);
  3163. ElfHeader.e_flags:=0;
  3164. ElfHeader.e_ehsize:=SizeOf(ElfHeader);
  3165. ElfHeader.e_phentsize:=SizeOf(TElf32proghdr);
  3166. ElfHeader.e_phnum:=0;
  3167. ElfHeader.e_shentsize:=SizeOf(TElf32sechdr);
  3168. ElfHeader.e_shnum:=elfsections_count;
  3169. ElfHeader.e_shstrndx:=shstrndx;
  3170. MaybeSwapHeader(ElfHeader);
  3171. Writer.write(ElfHeader,sizeof(ElfHeader));
  3172. { write section headers }
  3173. for I:=0 to elfsections_count-1 do
  3174. begin
  3175. MaybeSwapSecHeader(elfsechdrs[I]);
  3176. Writer.write(elfsechdrs[I],SizeOf(elfsechdrs[I]));
  3177. end;
  3178. { write section data }
  3179. for J:=0 to debugsections_count-1 do
  3180. begin
  3181. debugsections[J].DataPos:=Writer.Size;
  3182. for i:=0 to debugsections[J].ObjSectionList.Count-1 do
  3183. begin
  3184. ObjSec:=TOmfObjSection(debugsections[J].ObjSectionList[i]);
  3185. if assigned(ObjSec.Data) then
  3186. FWriter.writearray(ObjSec.Data);
  3187. end;
  3188. end;
  3189. { write .shstrtab section data }
  3190. Writer.writearray(shstrtabsect_data);
  3191. { mark the offset past the end of the ELF image }
  3192. elf_end_pos:=Writer.Size;
  3193. { write TIS trailer (not part of the ELF image) }
  3194. FillChar(tis_trailer,sizeof(tis_trailer),0);
  3195. with tis_trailer do
  3196. begin
  3197. tis_signature:=TIS_TRAILER_SIGNATURE;
  3198. tis_vendor:=TIS_TRAILER_VENDOR_TIS;
  3199. tis_type:=TIS_TRAILER_TYPE_TIS_DWARF;
  3200. tis_size:=(elf_end_pos-elf_start_pos)+sizeof(tis_trailer);
  3201. end;
  3202. MayBeSwapTISTrailer(tis_trailer);
  3203. Writer.write(tis_trailer,sizeof(tis_trailer));
  3204. Result:=True;
  3205. cleanup:
  3206. shstrtabsect_data.Free;
  3207. end;
  3208. procedure TMZExeOutput.Load_Symbol(const aname: string);
  3209. var
  3210. dgroup: TObjSectionGroup;
  3211. sym: TObjSymbol;
  3212. begin
  3213. { special handling for the '_edata' and '_end' symbols, which are
  3214. internally added by the linker }
  3215. if (aname='_edata') or (aname='_end') then
  3216. begin
  3217. { create an internal segment with the 'BSS' class }
  3218. internalObjData.createsection('*'+aname+'||BSS',0,[]);
  3219. { add to group 'DGROUP' }
  3220. dgroup:=nil;
  3221. if assigned(internalObjData.GroupsList) then
  3222. dgroup:=TObjSectionGroup(internalObjData.GroupsList.Find('DGROUP'));
  3223. if dgroup=nil then
  3224. dgroup:=internalObjData.createsectiongroup('DGROUP');
  3225. SetLength(dgroup.members,Length(dgroup.members)+1);
  3226. dgroup.members[Length(dgroup.members)-1]:=internalObjData.CurrObjSec;
  3227. { define the symbol itself }
  3228. sym:=internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  3229. sym.group:=dgroup;
  3230. end
  3231. else
  3232. inherited;
  3233. end;
  3234. procedure TMZExeOutput.DoRelocationFixup(objsec: TObjSection);
  3235. var
  3236. i: Integer;
  3237. omfsec: TOmfObjSection absolute objsec;
  3238. objreloc: TOmfRelocation;
  3239. target: DWord;
  3240. framebase: DWord;
  3241. fixupamount: Integer;
  3242. target_group: TMZExeUnifiedLogicalGroup;
  3243. procedure FixupOffset;
  3244. var
  3245. w: Word;
  3246. begin
  3247. omfsec.Data.seek(objreloc.DataOffset);
  3248. omfsec.Data.read(w,2);
  3249. w:=LEtoN(w);
  3250. Inc(w,fixupamount);
  3251. w:=LEtoN(w);
  3252. omfsec.Data.seek(objreloc.DataOffset);
  3253. omfsec.Data.write(w,2);
  3254. end;
  3255. procedure FixupOffset32;
  3256. var
  3257. lw: LongWord;
  3258. begin
  3259. omfsec.Data.seek(objreloc.DataOffset);
  3260. omfsec.Data.read(lw,4);
  3261. lw:=LEtoN(lw);
  3262. Inc(lw,fixupamount);
  3263. lw:=LEtoN(lw);
  3264. omfsec.Data.seek(objreloc.DataOffset);
  3265. omfsec.Data.write(lw,4);
  3266. end;
  3267. procedure FixupBase(DataOffset: LongWord);
  3268. var
  3269. w: Word;
  3270. begin
  3271. omfsec.Data.seek(DataOffset);
  3272. omfsec.Data.read(w,2);
  3273. w:=LEtoN(w);
  3274. Inc(w,framebase shr 4);
  3275. w:=LEtoN(w);
  3276. omfsec.Data.seek(DataOffset);
  3277. omfsec.Data.write(w,2);
  3278. Header.AddRelocation(omfsec.MZExeUnifiedLogicalSegment.MemBasePos shr 4,
  3279. omfsec.MemPos+DataOffset-omfsec.MZExeUnifiedLogicalSegment.MemBasePos);
  3280. end;
  3281. begin
  3282. for i:=0 to objsec.ObjRelocations.Count-1 do
  3283. begin
  3284. objreloc:=TOmfRelocation(objsec.ObjRelocations[i]);
  3285. if assigned(objreloc.symbol) then
  3286. begin
  3287. target:=objreloc.symbol.address;
  3288. if objreloc.FrameGroup<>'' then
  3289. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3290. else if assigned(objreloc.symbol.group) then
  3291. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.symbol.group.Name)).MemPos
  3292. else
  3293. if assigned(TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment) then
  3294. framebase:=TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment.MemBasePos
  3295. else
  3296. begin
  3297. framebase:=0;
  3298. Comment(V_Warning,'Encountered an OMF reference to a symbol, that is not present in the final executable: '+objreloc.symbol.Name);
  3299. end;
  3300. case objreloc.typ of
  3301. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3302. fixupamount:=target-framebase;
  3303. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3304. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3305. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3306. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3307. else
  3308. internalerror(2015082402);
  3309. end;
  3310. case objreloc.typ of
  3311. RELOC_ABSOLUTE16,
  3312. RELOC_RELATIVE16:
  3313. FixupOffset;
  3314. RELOC_ABSOLUTE32,
  3315. RELOC_RELATIVE32:
  3316. FixupOffset32;
  3317. RELOC_SEG,
  3318. RELOC_SEGREL:
  3319. FixupBase(objreloc.DataOffset);
  3320. RELOC_FARPTR,
  3321. RELOC_FARPTR_RELATIVEOFFSET:
  3322. begin
  3323. FixupOffset;
  3324. FixupBase(objreloc.DataOffset+2);
  3325. end;
  3326. RELOC_FARPTR48,
  3327. RELOC_FARPTR48_RELATIVEOFFSET:
  3328. begin
  3329. FixupOffset32;
  3330. FixupBase(objreloc.DataOffset+4);
  3331. end;
  3332. else
  3333. internalerror(2015082403);
  3334. end;
  3335. end
  3336. else if assigned(objreloc.objsection) then
  3337. begin
  3338. target:=objreloc.objsection.MemPos;
  3339. if objreloc.FrameGroup<>'' then
  3340. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3341. else
  3342. begin
  3343. if assigned(TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment) then
  3344. framebase:=TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment.MemBasePos
  3345. else
  3346. begin
  3347. framebase:=0;
  3348. Comment(V_Warning,'Encountered an OMF reference to a section, that is not present in the final executable: '+TOmfObjSection(objreloc.objsection).Name);
  3349. end;
  3350. end;
  3351. case objreloc.typ of
  3352. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3353. fixupamount:=target-framebase;
  3354. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3355. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3356. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3357. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3358. else
  3359. internalerror(2015082405);
  3360. end;
  3361. case objreloc.typ of
  3362. RELOC_ABSOLUTE16,
  3363. RELOC_RELATIVE16:
  3364. FixupOffset;
  3365. RELOC_ABSOLUTE32,
  3366. RELOC_RELATIVE32:
  3367. FixupOffset32;
  3368. RELOC_SEG,
  3369. RELOC_SEGREL:
  3370. FixupBase(objreloc.DataOffset);
  3371. RELOC_FARPTR,
  3372. RELOC_FARPTR_RELATIVEOFFSET:
  3373. begin
  3374. FixupOffset;
  3375. FixupBase(objreloc.DataOffset+2);
  3376. end;
  3377. RELOC_FARPTR48,
  3378. RELOC_FARPTR48_RELATIVEOFFSET:
  3379. begin
  3380. FixupOffset32;
  3381. FixupBase(objreloc.DataOffset+4);
  3382. end;
  3383. else
  3384. internalerror(2015082406);
  3385. end;
  3386. end
  3387. else if assigned(objreloc.group) then
  3388. begin
  3389. target_group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.group.Name));
  3390. target:=target_group.MemPos;
  3391. if objreloc.FrameGroup<>'' then
  3392. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3393. else
  3394. framebase:=target_group.MemPos;
  3395. case objreloc.typ of
  3396. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3397. fixupamount:=target-framebase;
  3398. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3399. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3400. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3401. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3402. else
  3403. internalerror(2015111202);
  3404. end;
  3405. case objreloc.typ of
  3406. RELOC_ABSOLUTE16,
  3407. RELOC_RELATIVE16:
  3408. FixupOffset;
  3409. RELOC_ABSOLUTE32,
  3410. RELOC_RELATIVE32:
  3411. FixupOffset32;
  3412. RELOC_SEG,
  3413. RELOC_SEGREL:
  3414. FixupBase(objreloc.DataOffset);
  3415. RELOC_FARPTR,
  3416. RELOC_FARPTR_RELATIVEOFFSET:
  3417. begin
  3418. FixupOffset;
  3419. FixupBase(objreloc.DataOffset+2);
  3420. end;
  3421. RELOC_FARPTR48,
  3422. RELOC_FARPTR48_RELATIVEOFFSET:
  3423. begin
  3424. FixupOffset32;
  3425. FixupBase(objreloc.DataOffset+4);
  3426. end;
  3427. else
  3428. internalerror(2015111203);
  3429. end;
  3430. end
  3431. else
  3432. internalerror(2015082407);
  3433. end;
  3434. end;
  3435. function IOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  3436. var
  3437. I1 : TOmfObjSection absolute Item1;
  3438. I2 : TOmfObjSection absolute Item2;
  3439. begin
  3440. Result:=CompareStr(I1.ClassName,I2.ClassName);
  3441. if Result=0 then
  3442. Result:=CompareStr(I1.Name,I2.Name);
  3443. if Result=0 then
  3444. Result:=I1.SortOrder-I2.SortOrder;
  3445. end;
  3446. procedure TMZExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList; const aPattern: string);
  3447. var
  3448. i: Integer;
  3449. begin
  3450. for i:=0 to ObjSectionList.Count-1 do
  3451. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  3452. ObjSectionList.Sort(@IOmfObjSectionClassNameCompare);
  3453. end;
  3454. procedure TMZExeOutput.MemPos_ExeSection(const aname: string);
  3455. begin
  3456. { overlay all .exe sections on top of each other. In practice, the MZ
  3457. formats doesn't have sections, so really, everything goes to a single
  3458. section, called .MZ_flat_content. All the remaining sections, that we
  3459. use are the debug sections, which go to a separate ELF file, appended
  3460. after the end of the .exe. They live in a separate address space, with
  3461. each section starting at virtual offset 0. So, that's why we always
  3462. set CurrMemPos to 0 before each section here. }
  3463. CurrMemPos:=0;
  3464. inherited MemPos_ExeSection(aname);
  3465. end;
  3466. procedure TMZExeOutput.MemPos_EndExeSection;
  3467. var
  3468. SecName: TSymStr='';
  3469. begin
  3470. if assigned(CurrExeSec) then
  3471. SecName:=CurrExeSec.Name;
  3472. inherited MemPos_EndExeSection;
  3473. case SecName of
  3474. '.MZ_flat_content':
  3475. begin
  3476. CalcExeUnifiedLogicalSegments;
  3477. CalcExeGroups;
  3478. CalcSegments_MemBasePos;
  3479. if assigned(exemap) then
  3480. WriteMap_SegmentsAndGroups;
  3481. end;
  3482. '.debug_info',
  3483. '.debug_abbrev',
  3484. '.debug_line',
  3485. '.debug_aranges':
  3486. begin
  3487. CalcDwarfUnifiedLogicalSegmentsForSection(SecName);
  3488. with TMZExeSection(FindExeSection(SecName)) do
  3489. SecOptions:=SecOptions+[oso_debug];
  3490. end;
  3491. '':
  3492. {nothing to do};
  3493. else
  3494. internalerror(2018061401);
  3495. end;
  3496. end;
  3497. function TMZExeOutput.writeData: boolean;
  3498. begin
  3499. Result:=False;
  3500. if ExeWriteMode in [ewm_exefull,ewm_exeonly] then
  3501. begin
  3502. if apptype=app_com then
  3503. Result:=WriteCom
  3504. else
  3505. Result:=WriteExe;
  3506. if not Result then
  3507. exit;
  3508. end;
  3509. if ((cs_debuginfo in current_settings.moduleswitches) and
  3510. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) and
  3511. ((ExeWriteMode=ewm_dbgonly) or
  3512. ((ExeWriteMode=ewm_exefull) and
  3513. not(cs_link_strip in current_settings.globalswitches))) then
  3514. Result:=writeDebugElf;
  3515. end;
  3516. constructor TMZExeOutput.create;
  3517. begin
  3518. inherited create;
  3519. CExeSection:=TMZExeSection;
  3520. CObjData:=TOmfObjData;
  3521. CObjSymbol:=TOmfObjSymbol;
  3522. { "640K ought to be enough for anybody" :) }
  3523. MaxMemPos:=$9FFFF;
  3524. FExeUnifiedLogicalSegments:=TFPHashObjectList.Create;
  3525. FExeUnifiedLogicalGroups:=TFPHashObjectList.Create;
  3526. FDwarfUnifiedLogicalSegments:=TFPHashObjectList.Create;
  3527. FHeader:=TMZExeHeader.Create;
  3528. end;
  3529. destructor TMZExeOutput.destroy;
  3530. begin
  3531. FHeader.Free;
  3532. FDwarfUnifiedLogicalSegments.Free;
  3533. FExeUnifiedLogicalGroups.Free;
  3534. FExeUnifiedLogicalSegments.Free;
  3535. inherited destroy;
  3536. end;
  3537. {****************************************************************************
  3538. TNewExeHeader
  3539. ****************************************************************************}
  3540. constructor TNewExeHeader.Create;
  3541. begin
  3542. SetLength(FMsDosStub,High(win16stub)-Low(win16stub)+1);
  3543. Move(win16stub[Low(win16stub)],FMsDosStub[0],High(win16stub)-Low(win16stub)+1);
  3544. { BP7 identifies itself as linker version 6.1 in the Win16 .exe files it produces }
  3545. LinkerVersion:=6;
  3546. LinkerRevision:=1;
  3547. LogicalSectorAlignmentShiftCount:=8; { 256-byte logical sectors }
  3548. TargetOS:=netoWindows;
  3549. ExpectedWindowsVersion:=$0300;
  3550. Flags:=[nehfNotWindowAPICompatible,nehfWindowAPICompatible,nehfMultipleData,nehfProtectedModeOnly];
  3551. AdditionalFlags:=[];
  3552. GangLoadAreaStart:=0;
  3553. GangLoadAreaLength:=0;
  3554. Reserved:=0;
  3555. Reserved2:=0;
  3556. end;
  3557. procedure TNewExeHeader.WriteTo(aWriter: TObjectWriter);
  3558. var
  3559. HeaderBytes: array [0..$3F] of Byte;
  3560. begin
  3561. aWriter.write(MsDosStub[0],Length(MsDosStub));
  3562. HeaderBytes[$00]:=$4E; { 'N' }
  3563. HeaderBytes[$01]:=$45; { 'E' }
  3564. HeaderBytes[$02]:=Byte(LinkerVersion);
  3565. HeaderBytes[$03]:=Byte(LinkerRevision);
  3566. HeaderBytes[$04]:=Byte(EntryTableOffset);
  3567. HeaderBytes[$05]:=Byte(EntryTableOffset shr 8);
  3568. HeaderBytes[$06]:=Byte(EntryTableLength);
  3569. HeaderBytes[$07]:=Byte(EntryTableLength shr 8);
  3570. HeaderBytes[$08]:=Byte(Reserved);
  3571. HeaderBytes[$09]:=Byte(Reserved shr 8);
  3572. HeaderBytes[$0A]:=Byte(Reserved shr 16);
  3573. HeaderBytes[$0B]:=Byte(Reserved shr 24);
  3574. HeaderBytes[$0C]:=Byte(Word(Flags));
  3575. HeaderBytes[$0D]:=Byte(Word(Flags) shr 8);
  3576. HeaderBytes[$0E]:=Byte(AutoDataSegmentNumber);
  3577. HeaderBytes[$0F]:=Byte(AutoDataSegmentNumber shr 8);
  3578. HeaderBytes[$10]:=Byte(InitialLocalHeapSize);
  3579. HeaderBytes[$11]:=Byte(InitialLocalHeapSize shr 8);
  3580. HeaderBytes[$12]:=Byte(InitialStackSize);
  3581. HeaderBytes[$13]:=Byte(InitialStackSize shr 8);
  3582. HeaderBytes[$14]:=Byte(InitialIP);
  3583. HeaderBytes[$15]:=Byte(InitialIP shr 8);
  3584. HeaderBytes[$16]:=Byte(InitialCS);
  3585. HeaderBytes[$17]:=Byte(InitialCS shr 8);
  3586. HeaderBytes[$18]:=Byte(InitialSP);
  3587. HeaderBytes[$19]:=Byte(InitialSP shr 8);
  3588. HeaderBytes[$1A]:=Byte(InitialSS);
  3589. HeaderBytes[$1B]:=Byte(InitialSS shr 8);
  3590. HeaderBytes[$1C]:=Byte(SegmentTableEntriesCount);
  3591. HeaderBytes[$1D]:=Byte(SegmentTableEntriesCount shr 8);
  3592. HeaderBytes[$1E]:=Byte(ModuleReferenceTableEntriesCount);
  3593. HeaderBytes[$1F]:=Byte(ModuleReferenceTableEntriesCount shr 8);
  3594. HeaderBytes[$20]:=Byte(NonresidentNameTableLength);
  3595. HeaderBytes[$21]:=Byte(NonresidentNameTableLength shr 8);
  3596. HeaderBytes[$22]:=Byte(SegmentTableStart);
  3597. HeaderBytes[$23]:=Byte(SegmentTableStart shr 8);
  3598. HeaderBytes[$24]:=Byte(ResourceTableStart);
  3599. HeaderBytes[$25]:=Byte(ResourceTableStart shr 8);
  3600. HeaderBytes[$26]:=Byte(ResidentNameTableStart);
  3601. HeaderBytes[$27]:=Byte(ResidentNameTableStart shr 8);
  3602. HeaderBytes[$28]:=Byte(ModuleReferenceTableStart);
  3603. HeaderBytes[$29]:=Byte(ModuleReferenceTableStart shr 8);
  3604. HeaderBytes[$2A]:=Byte(ImportedNameTableStart);
  3605. HeaderBytes[$2B]:=Byte(ImportedNameTableStart shr 8);
  3606. HeaderBytes[$2C]:=Byte(NonresidentNameTableStart);
  3607. HeaderBytes[$2D]:=Byte(NonresidentNameTableStart shr 8);
  3608. HeaderBytes[$2E]:=Byte(NonresidentNameTableStart shr 16);
  3609. HeaderBytes[$2F]:=Byte(NonresidentNameTableStart shr 24);
  3610. HeaderBytes[$30]:=Byte(MovableEntryPointsCount);
  3611. HeaderBytes[$31]:=Byte(MovableEntryPointsCount shr 8);
  3612. HeaderBytes[$32]:=Byte(LogicalSectorAlignmentShiftCount);
  3613. HeaderBytes[$33]:=Byte(LogicalSectorAlignmentShiftCount shr 8);
  3614. HeaderBytes[$34]:=Byte(ResourceSegmentsCount);
  3615. HeaderBytes[$35]:=Byte(ResourceSegmentsCount shr 8);
  3616. HeaderBytes[$36]:=Byte(Ord(TargetOS));
  3617. HeaderBytes[$37]:=Byte(AdditionalFlags);
  3618. HeaderBytes[$38]:=Byte(GangLoadAreaStart);
  3619. HeaderBytes[$39]:=Byte(GangLoadAreaStart shr 8);
  3620. HeaderBytes[$3A]:=Byte(GangLoadAreaLength);
  3621. HeaderBytes[$3B]:=Byte(GangLoadAreaLength shr 8);
  3622. HeaderBytes[$3C]:=Byte(Reserved2);
  3623. HeaderBytes[$3D]:=Byte(Reserved2 shr 8);
  3624. HeaderBytes[$3E]:=Byte(ExpectedWindowsVersion);
  3625. HeaderBytes[$3F]:=Byte(ExpectedWindowsVersion shr 8);
  3626. aWriter.write(HeaderBytes[0],$40);
  3627. end;
  3628. {****************************************************************************
  3629. TNewExeResourceTable
  3630. ****************************************************************************}
  3631. function TNewExeResourceTable.GetSize: QWord;
  3632. begin
  3633. Result:=5;
  3634. end;
  3635. constructor TNewExeResourceTable.Create;
  3636. begin
  3637. ResourceDataAlignmentShiftCount:=8;
  3638. end;
  3639. procedure TNewExeResourceTable.WriteTo(aWriter: TObjectWriter);
  3640. procedure WriteAlignShift;
  3641. var
  3642. AlignShiftBytes: array [0..1] of Byte;
  3643. begin
  3644. AlignShiftBytes[0]:=Byte(ResourceDataAlignmentShiftCount);
  3645. AlignShiftBytes[1]:=Byte(ResourceDataAlignmentShiftCount shr 8);
  3646. aWriter.write(AlignShiftBytes[0],2);
  3647. end;
  3648. procedure WriteEndTypes;
  3649. const
  3650. EndTypesBytes: array [0..1] of Byte = (0, 0);
  3651. begin
  3652. aWriter.write(EndTypesBytes[0],2);
  3653. end;
  3654. procedure WriteEndNames;
  3655. const
  3656. EndNames: Byte = 0;
  3657. begin
  3658. aWriter.write(EndNames,1);
  3659. end;
  3660. begin
  3661. WriteAlignShift;
  3662. WriteEndTypes;
  3663. WriteEndNames;
  3664. end;
  3665. {****************************************************************************
  3666. TNewExeExportNameTableEntry
  3667. ****************************************************************************}
  3668. constructor TNewExeExportNameTableEntry.Create(HashObjectList:TFPHashObjectList;const s:TSymStr;OrdNr:Word);
  3669. begin
  3670. inherited Create(HashObjectList,s);
  3671. OrdinalNr:=OrdNr;
  3672. end;
  3673. {****************************************************************************
  3674. TNewExeExportNameTable
  3675. ****************************************************************************}
  3676. function TNewExeExportNameTable.GetSize: QWord;
  3677. var
  3678. i: Integer;
  3679. begin
  3680. { the end of table mark is 1 byte }
  3681. Result:=1;
  3682. { each entry is 3 bytes, plus the length of the name }
  3683. for i:=0 to Count-1 do
  3684. Inc(Result,3+Length(TNewExeExportNameTableEntry(Items[i]).Name));
  3685. end;
  3686. procedure TNewExeExportNameTable.WriteTo(aWriter: TObjectWriter);
  3687. var
  3688. i: Integer;
  3689. rn: TNewExeExportNameTableEntry;
  3690. slen: Byte;
  3691. OrdNrBuf: array [0..1] of Byte;
  3692. begin
  3693. for i:=0 to Count-1 do
  3694. begin
  3695. rn:=TNewExeExportNameTableEntry(Items[i]);
  3696. slen:=Length(rn.Name);
  3697. if slen=0 then
  3698. internalerror(2019080801);
  3699. aWriter.write(slen,1);
  3700. aWriter.write(rn.Name[1],slen);
  3701. OrdNrBuf[0]:=Byte(rn.OrdinalNr);
  3702. OrdNrBuf[1]:=Byte(rn.OrdinalNr shr 8);
  3703. aWriter.write(OrdNrBuf[0],2);
  3704. end;
  3705. { end of table mark }
  3706. slen:=0;
  3707. aWriter.write(slen,1);
  3708. end;
  3709. {****************************************************************************
  3710. TNewExeModuleReferenceTable
  3711. ****************************************************************************}
  3712. function TNewExeModuleReferenceTable.GetSize: QWord;
  3713. begin
  3714. Result:=Count*2;
  3715. end;
  3716. procedure TNewExeModuleReferenceTable.AddModuleReference(const dllname:TSymStr);
  3717. begin
  3718. if not Assigned(Find(dllname)) then
  3719. TNewExeModuleReferenceTableEntry.Create(Self,dllname);
  3720. end;
  3721. procedure TNewExeModuleReferenceTable.WriteTo(aWriter: TObjectWriter;imptbl: TNewExeImportedNameTable);
  3722. var
  3723. buf: array of Byte;
  3724. i: Integer;
  3725. ImpTblEntry: TNewExeImportedNameTableEntry;
  3726. begin
  3727. SetLength(buf,Size);
  3728. for i:=0 to Count-1 do
  3729. begin
  3730. ImpTblEntry:=TNewExeImportedNameTableEntry(imptbl.Find(TNewExeModuleReferenceTableEntry(Items[i]).Name));
  3731. if not Assigned(ImpTblEntry) then
  3732. internalerror(2019080903);
  3733. buf[2*i]:=Byte(ImpTblEntry.TableOffset);
  3734. buf[2*i+1]:=Byte(ImpTblEntry.TableOffset shr 8);
  3735. end;
  3736. aWriter.write(buf[0],Length(buf));
  3737. end;
  3738. {****************************************************************************
  3739. TNewExeImportedNameTable
  3740. ****************************************************************************}
  3741. function TNewExeImportedNameTable.GetSize: QWord;
  3742. var
  3743. i: Integer;
  3744. begin
  3745. { the table starts with an empty entry, which takes 1 byte }
  3746. Result:=1;
  3747. { each entry is 1 byte, plus the length of the name }
  3748. for i:=0 to Count-1 do
  3749. Inc(Result,1+Length(TNewExeImportedNameTableEntry(Items[i]).Name));
  3750. end;
  3751. procedure TNewExeImportedNameTable.AddImportedName(const name: TSymStr);
  3752. begin
  3753. if not Assigned(Find(name)) then
  3754. TNewExeImportedNameTableEntry.Create(Self,name);
  3755. end;
  3756. procedure TNewExeImportedNameTable.CalcTableOffsets;
  3757. var
  3758. cofs: LongInt;
  3759. i: Integer;
  3760. entry: TNewExeImportedNameTableEntry;
  3761. begin
  3762. { the table starts with an empty entry, which takes 1 byte }
  3763. cofs:=1;
  3764. for i:=0 to Count-1 do
  3765. begin
  3766. entry:=TNewExeImportedNameTableEntry(Items[i]);
  3767. entry.TableOffset:=cofs;
  3768. Inc(cofs,1+Length(entry.Name));
  3769. if cofs>High(Word) then
  3770. internalerror(2019080902);
  3771. end;
  3772. end;
  3773. procedure TNewExeImportedNameTable.WriteTo(aWriter: TObjectWriter);
  3774. var
  3775. i: Integer;
  3776. entry: TNewExeImportedNameTableEntry;
  3777. slen: Byte;
  3778. begin
  3779. { the table starts with an empty entry }
  3780. slen:=0;
  3781. aWriter.write(slen,1);
  3782. for i:=0 to Count-1 do
  3783. begin
  3784. entry:=TNewExeImportedNameTableEntry(Items[i]);
  3785. slen:=Length(entry.Name);
  3786. if slen=0 then
  3787. internalerror(2019080901);
  3788. aWriter.write(slen,1);
  3789. aWriter.write(entry.Name[1],slen);
  3790. end;
  3791. end;
  3792. {****************************************************************************
  3793. TNewExeEntryPoint
  3794. ****************************************************************************}
  3795. function TNewExeEntryPoint.GetFlagsByte: Byte;
  3796. begin
  3797. Result:=Byte(ParmCount shl 3);
  3798. if neepfExported in Flags then
  3799. Result:=Result or 1;
  3800. if neepfSingleData in Flags then
  3801. Result:=Result or 2;
  3802. end;
  3803. {****************************************************************************
  3804. TNewExeEntryTable
  3805. ****************************************************************************}
  3806. function TNewExeEntryTable.GetSize: QWord;
  3807. var
  3808. CurBundleStart: Integer;
  3809. CurBundleSize: Byte;
  3810. begin
  3811. Result:=0;
  3812. CurBundleStart:=1;
  3813. repeat
  3814. CurBundleSize:=BundleSize(CurBundleStart);
  3815. Inc(Result,2);
  3816. if CurBundleSize>0 then
  3817. begin
  3818. if Items[CurBundleStart]=nil then
  3819. { a bundle of null entries }
  3820. else if neepfMovableSegment in Items[CurBundleStart].Flags then
  3821. { a bundle of movable segment records }
  3822. Inc(Result,6*CurBundleSize)
  3823. else
  3824. { a bundle of fixed segment records }
  3825. Inc(Result,3*CurBundleSize);
  3826. end;
  3827. Inc(CurBundleStart,CurBundleSize);
  3828. until CurBundleSize=0;
  3829. end;
  3830. procedure TNewExeEntryTable.SetItems(i: Integer; AValue: TNewExeEntryPoint);
  3831. begin
  3832. if (i<1) or (i>Length(FItems)) then
  3833. internalerror(2019081002);
  3834. FItems[i-1]:=AValue;
  3835. end;
  3836. function TNewExeEntryTable.CanBeInSameBundle(i, j: Integer): Boolean;
  3837. begin
  3838. if (Items[i]=nil) or (Items[j]=nil) then
  3839. Result:=(Items[i]=nil) and (Items[j]=nil)
  3840. else if not (neepfMovableSegment in Items[i].Flags) and
  3841. not (neepfMovableSegment in Items[j].Flags) then
  3842. Result:=Items[i].Segment=Items[j].Segment
  3843. else
  3844. Result:=(neepfMovableSegment in Items[i].Flags)=
  3845. (neepfMovableSegment in Items[j].Flags);
  3846. end;
  3847. function TNewExeEntryTable.BundleSize(StartingElement:Integer): Byte;
  3848. begin
  3849. if StartingElement>Count then
  3850. Result:=0
  3851. else
  3852. begin
  3853. Result:=1;
  3854. while (Result<255) and ((StartingElement+Result)<=Count) and CanBeInSameBundle(StartingElement,StartingElement+Result) do
  3855. Inc(Result);
  3856. end;
  3857. end;
  3858. function TNewExeEntryTable.GetCount: Word;
  3859. begin
  3860. Result:=Length(FItems);
  3861. end;
  3862. function TNewExeEntryTable.GetItems(i: Integer): TNewExeEntryPoint;
  3863. begin
  3864. if (i<1) or (i>Length(FItems)) then
  3865. internalerror(2019081011);
  3866. Result:=FItems[i-1];
  3867. end;
  3868. destructor TNewExeEntryTable.Destroy;
  3869. var
  3870. i: Integer;
  3871. begin
  3872. for i:=low(FItems) to high(FItems) do
  3873. FreeAndNil(FItems[i]);
  3874. inherited Destroy;
  3875. end;
  3876. procedure TNewExeEntryTable.WriteTo(aWriter: TObjectWriter);
  3877. var
  3878. CurBundleStart, i: Integer;
  3879. CurBundleSize: Byte;
  3880. buf: array [0..5] of Byte;
  3881. cp: TNewExeEntryPoint;
  3882. begin
  3883. CurBundleStart:=1;
  3884. repeat
  3885. CurBundleSize:=BundleSize(CurBundleStart);
  3886. aWriter.write(CurBundleSize,1);
  3887. if CurBundleSize>0 then
  3888. begin
  3889. if Items[CurBundleStart]=nil then
  3890. begin
  3891. { a bundle of null entries }
  3892. buf[0]:=0;
  3893. aWriter.write(buf[0],1);
  3894. end
  3895. else if neepfMovableSegment in Items[CurBundleStart].Flags then
  3896. begin
  3897. { a bundle of movable segment records }
  3898. buf[0]:=$ff;
  3899. aWriter.write(buf[0],1);
  3900. for i:=CurBundleStart to CurBundleStart+CurBundleSize-1 do
  3901. begin
  3902. cp:=Items[i];
  3903. buf[0]:=cp.FlagsByte;
  3904. buf[1]:=$CD; { INT 3Fh instruction }
  3905. buf[2]:=$3F;
  3906. buf[3]:=Byte(cp.Segment);
  3907. buf[4]:=Byte(cp.Offset);
  3908. buf[5]:=Byte(cp.Offset shr 8);
  3909. aWriter.write(buf[0],6);
  3910. end;
  3911. end
  3912. else
  3913. begin
  3914. { a bundle of fixed segment records }
  3915. buf[0]:=Items[CurBundleStart].Segment;
  3916. aWriter.write(buf[0],1);
  3917. for i:=CurBundleStart to CurBundleStart+CurBundleSize-1 do
  3918. begin
  3919. cp:=Items[i];
  3920. buf[0]:=cp.FlagsByte;
  3921. buf[1]:=Byte(cp.Offset);
  3922. buf[2]:=Byte(cp.Offset shr 8);
  3923. aWriter.write(buf[0],3);
  3924. end;
  3925. end;
  3926. end;
  3927. Inc(CurBundleStart,CurBundleSize);
  3928. until CurBundleSize=0;
  3929. { finish the end marker - a null bundle of 0 entries - must be 2 zero
  3930. bytes. The first one was already written by the loop, time to add the
  3931. second one. }
  3932. buf[0]:=0;
  3933. aWriter.write(buf[0],1);
  3934. end;
  3935. procedure TNewExeEntryTable.GrowTo(aNewCount: Word);
  3936. begin
  3937. if aNewCount<Count then
  3938. internalerror(2019081003);
  3939. SetLength(FItems,aNewCount);
  3940. end;
  3941. {****************************************************************************
  3942. TNewExeRelocation
  3943. ****************************************************************************}
  3944. procedure TNewExeRelocation.EncodeTo(dest: PByte);
  3945. begin
  3946. dest[0]:=Ord(AddressType);
  3947. dest[1]:=Ord(RelocationType) or (Ord(IsAdditive) shl 2);
  3948. dest[2]:=Byte(Offset);
  3949. dest[3]:=Byte(Offset shr 8);
  3950. case RelocationType of
  3951. nertInternalRef:
  3952. begin
  3953. case InternalRefSegmentType of
  3954. neirstFixed:
  3955. begin
  3956. dest[4]:=Byte(InternalRefFixedSegmentNumber);
  3957. dest[5]:=0;
  3958. dest[6]:=Byte(InternalRefFixedSegmentOffset);
  3959. dest[7]:=Byte(InternalRefFixedSegmentOffset shr 8);
  3960. end;
  3961. neirstMovable:
  3962. begin
  3963. dest[4]:=$FF;
  3964. dest[5]:=0;
  3965. dest[6]:=Byte(InternalRefMovableSegmentEntryTableIndex);
  3966. dest[7]:=Byte(InternalRefMovableSegmentEntryTableIndex shr 8);
  3967. end;
  3968. end;
  3969. end;
  3970. nertImportName:
  3971. begin
  3972. dest[4]:=Byte(ImportModuleIndex);
  3973. dest[5]:=Byte(ImportModuleIndex shr 8);
  3974. dest[6]:=Byte(ImportNameIndex);
  3975. dest[7]:=Byte(ImportNameIndex shr 8);
  3976. end;
  3977. nertImportOrdinal:
  3978. begin
  3979. dest[4]:=Byte(ImportModuleIndex);
  3980. dest[5]:=Byte(ImportModuleIndex shr 8);
  3981. dest[6]:=Byte(ImportOrdinal);
  3982. dest[7]:=Byte(ImportOrdinal shr 8);
  3983. end;
  3984. nertOsFixup:
  3985. begin
  3986. dest[4]:=Byte(Ord(OsFixupType));
  3987. dest[5]:=Byte(Ord(OsFixupType) shr 8);
  3988. dest[6]:=0;
  3989. dest[7]:=0;
  3990. end;
  3991. end;
  3992. end;
  3993. {****************************************************************************
  3994. TNewExeRelocationList
  3995. ****************************************************************************}
  3996. function TNewExeRelocationList.GetCount: Integer;
  3997. begin
  3998. Result:=FInternalList.Count;
  3999. end;
  4000. function TNewExeRelocationList.GetItem(Index: Integer): TNewExeRelocation;
  4001. begin
  4002. Result:=TNewExeRelocation(FInternalList[Index]);
  4003. end;
  4004. function TNewExeRelocationList.GetSize: QWord;
  4005. begin
  4006. Result:=2+Count*NewExeRelocationRecordSize;
  4007. end;
  4008. procedure TNewExeRelocationList.SetCount(AValue: Integer);
  4009. begin
  4010. FInternalList.Count:=AValue;
  4011. end;
  4012. procedure TNewExeRelocationList.SetItem(Index:Integer;AValue:TNewExeRelocation);
  4013. begin
  4014. FInternalList[Index]:=AValue;
  4015. end;
  4016. constructor TNewExeRelocationList.Create;
  4017. begin
  4018. FInternalList:=TFPObjectList.Create;
  4019. end;
  4020. destructor TNewExeRelocationList.Destroy;
  4021. begin
  4022. FInternalList.Free;
  4023. inherited Destroy;
  4024. end;
  4025. procedure TNewExeRelocationList.WriteTo(aWriter: TObjectWriter);
  4026. var
  4027. buf: array of Byte;
  4028. p: PByte;
  4029. i: Integer;
  4030. begin
  4031. SetLength(buf,Size);
  4032. buf[0]:=Byte(Count);
  4033. buf[1]:=Byte(Count shr 8);
  4034. p:=@(buf[2]);
  4035. for i:=0 to Count-1 do
  4036. begin
  4037. Items[i].EncodeTo(p);
  4038. Inc(p,NewExeRelocationRecordSize);
  4039. end;
  4040. aWriter.write(buf[0],Size);
  4041. end;
  4042. function TNewExeRelocationList.Add(AObject: TNewExeRelocation): Integer;
  4043. begin
  4044. Result:=FInternalList.Add(AObject);
  4045. end;
  4046. {****************************************************************************
  4047. TNewExeSection
  4048. ****************************************************************************}
  4049. function TNewExeSection.GetMinAllocSize: QWord;
  4050. begin
  4051. Result:=Size-StackSize;
  4052. end;
  4053. function TNewExeSection.GetNewExeSegmentFlags: TNewExeSegmentFlags;
  4054. begin
  4055. Result:=FNewExeSegmentFlags;
  4056. if Relocations.Count>0 then
  4057. Include(Result,nesfHasRelocationData)
  4058. else
  4059. Exclude(Result,nesfHasRelocationData);
  4060. end;
  4061. constructor TNewExeSection.create(AList:TFPHashObjectList;const AName:string);
  4062. begin
  4063. inherited create(AList, AName);
  4064. FRelocations:=TNewExeRelocationList.Create;
  4065. end;
  4066. destructor TNewExeSection.destroy;
  4067. begin
  4068. FRelocations.Free;
  4069. inherited destroy;
  4070. end;
  4071. procedure TNewExeSection.WriteHeaderTo(aWriter: TObjectWriter);
  4072. var
  4073. SegmentHeaderBytes: array [0..7] of Byte;
  4074. begin
  4075. SegmentHeaderBytes[0]:=Byte(DataPosSectors);
  4076. SegmentHeaderBytes[1]:=Byte(DataPosSectors shr 8);
  4077. SegmentHeaderBytes[2]:=Byte(SizeInFile);
  4078. SegmentHeaderBytes[3]:=Byte(SizeInFile shr 8);
  4079. SegmentHeaderBytes[4]:=Byte(Word(NewExeSegmentFlags));
  4080. SegmentHeaderBytes[5]:=Byte(Word(NewExeSegmentFlags) shr 8);
  4081. SegmentHeaderBytes[6]:=Byte(MinAllocSize);
  4082. SegmentHeaderBytes[7]:=Byte(MinAllocSize shr 8);
  4083. aWriter.write(SegmentHeaderBytes[0],8);
  4084. end;
  4085. function TNewExeSection.MemPosStr(AImageBase: qword): string;
  4086. begin
  4087. Result:=HexStr(MemBasePos,4)+':'+HexStr(MemPos,4);
  4088. end;
  4089. procedure TNewExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  4090. var
  4091. s: TSymStr;
  4092. Separator: SizeInt;
  4093. {SegName,} SegClass: string;
  4094. IsStack, IsBss: Boolean;
  4095. begin
  4096. { allow mixing initialized and uninitialized data in the same section
  4097. => set ignoreprops=true }
  4098. inherited AddObjSection(objsec,true);
  4099. IsBss:=not(oso_Data in objsec.SecOptions);
  4100. s:=objsec.Name;
  4101. { name format is 'SegName||ClassName' }
  4102. Separator:=Pos('||',s);
  4103. if Separator>0 then
  4104. begin
  4105. //SegName:=Copy(s,1,Separator-1);
  4106. SegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  4107. end
  4108. else
  4109. begin
  4110. //SegName:=s;
  4111. SegClass:='';
  4112. end;
  4113. { wlink recognizes the stack segment by the class name 'STACK' }
  4114. { let's be compatible with wlink }
  4115. IsStack:=SegClass='STACK';
  4116. { tlink (and ms link?) use the scStack segment combination to recognize
  4117. the stack segment.
  4118. let's be compatible with tlink as well }
  4119. if TOmfObjSection(ObjSec).Combination=scStack then
  4120. IsStack:=True;
  4121. if IsStack then
  4122. StackSize:=StackSize+objsec.Size;
  4123. EarlySize:=align_qword(EarlySize,SecAlign)+objsec.Size;
  4124. if (not IsBss) and (not IsStack) then
  4125. SizeInFile:=EarlySize;
  4126. end;
  4127. function TNewExeSection.CanAddObjSection(objsec: TObjSection; ExeSectionLimit: QWord): boolean;
  4128. var
  4129. NewSecAlign: LongInt;
  4130. NewSize: QWord;
  4131. begin
  4132. NewSecAlign:=max(objsec.SecAlign,SecAlign);
  4133. NewSize:=align_qword(EarlySize,NewSecAlign)+objsec.Size;
  4134. Result:=NewSize<=ExeSectionLimit;
  4135. end;
  4136. {****************************************************************************
  4137. TNewExeOutput
  4138. ****************************************************************************}
  4139. procedure TNewExeOutput.AddImportSymbol(const libname, symname,
  4140. symmangledname: TCmdStr; OrdNr: longint; isvar: boolean);
  4141. var
  4142. ImportLibrary: TImportLibrary;
  4143. ImportSymbol: TFPHashObject;
  4144. begin
  4145. ImportLibrary:=TImportLibrary(FImports.Find(libname));
  4146. if not assigned(ImportLibrary) then
  4147. ImportLibrary:=TImportLibrary.Create(FImports,libname);
  4148. ImportSymbol:=TFPHashObject(ImportLibrary.ImportSymbolList.Find(symname));
  4149. if not assigned(ImportSymbol) then
  4150. ImportSymbol:=TImportSymbol.Create(ImportLibrary.ImportSymbolList,symname,symmangledname,OrdNr,isvar);
  4151. end;
  4152. procedure TNewExeOutput.AddImportLibrariesExtractedFromObjectModules;
  4153. var
  4154. i, j, k: Integer;
  4155. ObjData: TOmfObjData;
  4156. ImportLibrary: TImportLibrary;
  4157. ImportSymbol: TImportSymbol;
  4158. begin
  4159. for i:=0 to ObjDataList.Count-1 do
  4160. begin
  4161. ObjData:=TOmfObjData(ObjDataList[i]);
  4162. for j:=0 to ObjData.ImportLibraryList.Count-1 do
  4163. begin
  4164. ImportLibrary:=TImportLibrary(ObjData.ImportLibraryList[j]);
  4165. for k:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4166. begin
  4167. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[k]);
  4168. AddImportSymbol(ImportLibrary.Name,ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.OrdNr,ImportSymbol.IsVar);
  4169. end;
  4170. end;
  4171. end;
  4172. end;
  4173. procedure TNewExeOutput.AddNewExeSection;
  4174. var
  4175. SegNr: Integer;
  4176. SecName: string;
  4177. begin
  4178. SegNr:=ExeSectionList.Count+1;
  4179. WriteStr(SecName,'Segment',SegNr,'_',NewExeMetaSection2String[CurrExeMetaSec]);
  4180. inherited Order_ExeSection(SecName);
  4181. TNewExeSection(CurrExeSec).ExeMetaSec:=CurrExeMetaSec;
  4182. TNewExeSection(CurrExeSec).MemBasePos:=SegNr;
  4183. if (CurrExeMetaSec=nemsData) and (Header.AutoDataSegmentNumber=0) then
  4184. Header.AutoDataSegmentNumber:=SegNr;
  4185. case CurrExeMetaSec of
  4186. nemsCode:
  4187. TNewExeSection(CurrExeSec).NewExeSegmentFlags:=[nesfMovable,nesfPreload];
  4188. nemsData:
  4189. TNewExeSection(CurrExeSec).NewExeSegmentFlags:=[nesfData,nesfPreload];
  4190. else
  4191. internalerror(2019070601);
  4192. end;
  4193. end;
  4194. function TNewExeOutput.WriteNewExe: boolean;
  4195. function ExtractModuleName(filename: string): string;
  4196. begin
  4197. Result:=UpCase(ChangeFileExt(filename,''));
  4198. end;
  4199. var
  4200. i: Integer;
  4201. begin
  4202. if IsSharedLibrary then
  4203. Header.Flags:=Header.Flags+[nehfIsDLL,nehfSingleData]-[nehfMultipleData];
  4204. { all exported symbols must have an ordinal }
  4205. AssignOrdinalsToAllExportSymbols;
  4206. AddEntryPointsForAllExportSymbols;
  4207. { the first entry in the resident-name table is the module name }
  4208. TNewExeExportNameTableEntry.Create(ResidentNameTable,ExtractModuleName(current_module.exefilename),0);
  4209. { the first entry in the nonresident-name table is the module description }
  4210. TNewExeExportNameTableEntry.Create(NonresidentNameTable,description,0);
  4211. { add all symbols, exported by name to the resident and nonresident-name tables }
  4212. AddExportedNames;
  4213. FillImportedNameAndModuleReferenceTable;
  4214. ImportedNameTable.CalcTableOffsets;
  4215. Header.InitialIP:=EntrySym.address;
  4216. Header.InitialCS:=TNewExeSection(EntrySym.objsection.ExeSection).MemBasePos;
  4217. Header.InitialSP:=0;
  4218. Header.InitialSS:=Header.AutoDataSegmentNumber;
  4219. Header.InitialStackSize:=TNewExeSection(ExeSectionList[Header.AutoDataSegmentNumber-1]).StackSize;
  4220. Header.InitialLocalHeapSize:=heapsize;
  4221. Header.SegmentTableStart:=NewExeHeaderSize;
  4222. Header.SegmentTableEntriesCount:=ExeSectionList.Count;
  4223. Header.ResourceTableStart:=Header.SegmentTableStart+NewExeSegmentHeaderSize*Header.SegmentTableEntriesCount;
  4224. Header.ResidentNameTableStart:=Header.ResourceTableStart+ResourceTable.Size;
  4225. Header.ModuleReferenceTableStart:=Header.ResidentNameTableStart+ResidentNameTable.Size;
  4226. Header.ModuleReferenceTableEntriesCount:=ModuleReferenceTable.Count;
  4227. Header.ImportedNameTableStart:=Header.ModuleReferenceTableStart+ModuleReferenceTable.Size;
  4228. Header.EntryTableOffset:=Header.ImportedNameTableStart+ImportedNameTable.Size;
  4229. Header.EntryTableLength:=EntryTable.Size;
  4230. Header.NonresidentNameTableStart:=Header.EntryTableOffset+Header.EntryTableLength+Length(Header.MsDosStub);
  4231. Header.NonresidentNameTableLength:=NonresidentNameTable.Size;
  4232. Header.WriteTo(FWriter);
  4233. for i:=0 to ExeSectionList.Count-1 do
  4234. TNewExeSection(ExeSectionList[i]).WriteHeaderTo(FWriter);
  4235. ResourceTable.WriteTo(FWriter);
  4236. ResidentNameTable.WriteTo(FWriter);
  4237. ModuleReferenceTable.WriteTo(FWriter,ImportedNameTable);
  4238. ImportedNameTable.WriteTo(FWriter);
  4239. EntryTable.WriteTo(FWriter);
  4240. NonresidentNameTable.WriteTo(FWriter);
  4241. { todo: write the rest of the file as well }
  4242. Result:=True;
  4243. end;
  4244. procedure TNewExeOutput.FillImportedNameAndModuleReferenceTable;
  4245. var
  4246. i, j: Integer;
  4247. ImportLibrary: TImportLibrary;
  4248. ImportSymbol: TImportSymbol;
  4249. exesym: TExeSymbol;
  4250. LibNameAdded: Boolean;
  4251. dllname: TSymStr;
  4252. begin
  4253. for i:=0 to FImports.Count-1 do
  4254. begin
  4255. ImportLibrary:=TImportLibrary(FImports[i]);
  4256. LibNameAdded:=False;
  4257. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4258. begin
  4259. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4260. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4261. if assigned(exesym) then
  4262. begin
  4263. if not LibNameAdded then
  4264. begin
  4265. dllname:=StripDllExt(ImportLibrary.Name);
  4266. ImportedNameTable.AddImportedName(dllname);
  4267. ModuleReferenceTable.AddModuleReference(dllname);
  4268. LibNameAdded:=True;
  4269. end;
  4270. if (ImportSymbol.OrdNr=0) and (ImportSymbol.Name<>'') then
  4271. ImportedNameTable.AddImportedName(ImportSymbol.Name);
  4272. end;
  4273. end;
  4274. end;
  4275. end;
  4276. function TNewExeOutput.GetHighestExportSymbolOrdinal: Word;
  4277. var
  4278. i, j: Integer;
  4279. ObjData: TOmfObjData;
  4280. sym: TOmfObjExportedSymbol;
  4281. begin
  4282. Result:=0;
  4283. for i:=0 to ObjDataList.Count-1 do
  4284. begin
  4285. ObjData:=TOmfObjData(ObjDataList[i]);
  4286. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4287. begin
  4288. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4289. if sym.ExportByOrdinal then
  4290. Result:=Max(Result,sym.ExportOrdinal);
  4291. end;
  4292. end;
  4293. end;
  4294. procedure TNewExeOutput.AssignOrdinalsToAllExportSymbols;
  4295. var
  4296. NextOrdinal: LongInt;
  4297. i, j: Integer;
  4298. ObjData: TOmfObjData;
  4299. sym: TOmfObjExportedSymbol;
  4300. begin
  4301. NextOrdinal:=GetHighestExportSymbolOrdinal+1;
  4302. for i:=0 to ObjDataList.Count-1 do
  4303. begin
  4304. ObjData:=TOmfObjData(ObjDataList[i]);
  4305. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4306. begin
  4307. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4308. if not sym.ExportByOrdinal then
  4309. begin
  4310. if NextOrdinal>High(Word) then
  4311. internalerror(2019081001);
  4312. sym.ExportByOrdinal:=True;
  4313. sym.ExportOrdinal:=NextOrdinal;
  4314. Inc(NextOrdinal);
  4315. end;
  4316. end;
  4317. end;
  4318. end;
  4319. procedure TNewExeOutput.AddEntryPointsForAllExportSymbols;
  4320. var
  4321. LastOrdinal: Word;
  4322. i, j: Integer;
  4323. ObjData: TOmfObjData;
  4324. sym: TOmfObjExportedSymbol;
  4325. ent: TNewExeEntryPoint;
  4326. exesym: TExeSymbol;
  4327. sec: TNewExeSection;
  4328. begin
  4329. LastOrdinal:=GetHighestExportSymbolOrdinal;
  4330. EntryTable.GrowTo(LastOrdinal);
  4331. for i:=0 to ObjDataList.Count-1 do
  4332. begin
  4333. ObjData:=TOmfObjData(ObjDataList[i]);
  4334. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4335. begin
  4336. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4337. { all exports must have an ordinal at this point }
  4338. if not sym.ExportByOrdinal then
  4339. internalerror(2019081004);
  4340. { check for duplicated ordinals }
  4341. if Assigned(EntryTable[sym.ExportOrdinal]) then
  4342. internalerror(2019081005);
  4343. ent:=TNewExeEntryPoint.Create;
  4344. EntryTable[sym.ExportOrdinal]:=ent;
  4345. exesym:=TExeSymbol(ExeSymbolList.Find(sym.InternalName));
  4346. if not Assigned(exesym) then
  4347. internalerror(2019081006);
  4348. ent.Flags:=[neepfExported];
  4349. if IsSharedLibrary then
  4350. ent.Flags:=ent.Flags+[neepfSingleData];
  4351. ent.Offset:=exesym.ObjSymbol.address;
  4352. sec:=TNewExeSection(exesym.ObjSymbol.objsection.ExeSection);
  4353. ent.Segment:=sec.MemBasePos;
  4354. if nesfMovable in sec.NewExeSegmentFlags then
  4355. ent.Flags:=ent.Flags+[neepfMovableSegment];
  4356. ent.ParmCount:=sym.ParmCount;
  4357. end;
  4358. end;
  4359. end;
  4360. procedure TNewExeOutput.AddExportedNames;
  4361. var
  4362. i, j: Integer;
  4363. ObjData: TOmfObjData;
  4364. sym: TOmfObjExportedSymbol;
  4365. begin
  4366. for i:=0 to ObjDataList.Count-1 do
  4367. begin
  4368. ObjData:=TOmfObjData(ObjDataList[i]);
  4369. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4370. begin
  4371. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4372. { all exports must have an ordinal at this point }
  4373. if not sym.ExportByOrdinal then
  4374. internalerror(2019081007);
  4375. if sym.ResidentName then
  4376. TNewExeExportNameTableEntry.Create(ResidentNameTable,sym.ExportedName,sym.ExportOrdinal)
  4377. else
  4378. TNewExeExportNameTableEntry.Create(NonresidentNameTable,sym.ExportedName,sym.ExportOrdinal);
  4379. end;
  4380. end;
  4381. end;
  4382. procedure TNewExeOutput.DoRelocationFixup(objsec: TObjSection);
  4383. begin
  4384. {todo}
  4385. end;
  4386. function INewExeOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  4387. var
  4388. I1 : TOmfObjSection absolute Item1;
  4389. I2 : TOmfObjSection absolute Item2;
  4390. begin
  4391. Result:=CompareStr(I1.ClassName,I2.ClassName);
  4392. if Result=0 then
  4393. Result:=CompareStr(I1.Name,I2.Name);
  4394. if Result=0 then
  4395. Result:=I1.SortOrder-I2.SortOrder;
  4396. end;
  4397. procedure TNewExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList;const aPattern: string);
  4398. var
  4399. i: Integer;
  4400. begin
  4401. for i:=0 to ObjSectionList.Count-1 do
  4402. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  4403. ObjSectionList.Sort(@INewExeOmfObjSectionClassNameCompare);
  4404. end;
  4405. constructor TNewExeOutput.create;
  4406. begin
  4407. inherited create;
  4408. CObjData:=TOmfObjData;
  4409. CObjSymbol:=TOmfObjSymbol;
  4410. CExeSection:=TNewExeSection;
  4411. FHeader:=TNewExeHeader.Create;
  4412. MaxMemPos:=$FFFFFFFF;
  4413. CurrExeMetaSec:=nemsNone;
  4414. FResourceTable:=TNewExeResourceTable.Create;
  4415. FResidentNameTable:=TNewExeExportNameTable.Create;
  4416. FNonresidentNameTable:=TNewExeExportNameTable.Create;
  4417. FModuleReferenceTable:=TNewExeModuleReferenceTable.Create;
  4418. FImportedNameTable:=TNewExeImportedNameTable.Create;
  4419. FEntryTable:=TNewExeEntryTable.Create;
  4420. end;
  4421. destructor TNewExeOutput.destroy;
  4422. begin
  4423. FEntryTable.Free;
  4424. FImportedNameTable.Free;
  4425. FModuleReferenceTable.Free;
  4426. FNonresidentNameTable.Free;
  4427. FResidentNameTable.Free;
  4428. FResourceTable.Free;
  4429. FHeader.Free;
  4430. inherited destroy;
  4431. end;
  4432. procedure TNewExeOutput.Order_ExeSection(const aname: string);
  4433. begin
  4434. case aname of
  4435. '.NE_code':
  4436. CurrExeMetaSec:=nemsCode;
  4437. '.NE_data':
  4438. CurrExeMetaSec:=nemsData;
  4439. else
  4440. internalerror(2019080201);
  4441. end;
  4442. end;
  4443. procedure TNewExeOutput.Order_EndExeSection;
  4444. begin
  4445. CurrExeMetaSec:=nemsNone;
  4446. inherited;
  4447. end;
  4448. procedure TNewExeOutput.Order_ObjSection(const aname: string);
  4449. const
  4450. SegmentLimit=$10000;
  4451. var
  4452. i,j : longint;
  4453. ObjData : TObjData;
  4454. objsec : TObjSection;
  4455. TmpObjSectionList : TFPObjectList;
  4456. begin
  4457. if CurrExeMetaSec=nemsNone then
  4458. internalerror(2019080202);
  4459. if not assigned (CurrExeSec) then
  4460. AddNewExeSection;
  4461. TmpObjSectionList:=TFPObjectList.Create(false);
  4462. for i:=0 to ObjDataList.Count-1 do
  4463. begin
  4464. ObjData:=TObjData(ObjDataList[i]);
  4465. for j:=0 to ObjData.ObjSectionList.Count-1 do
  4466. begin
  4467. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  4468. if (not objsec.Used) and
  4469. MatchPattern(aname,objsec.name) then
  4470. TmpObjSectionList.Add(objsec);
  4471. end;
  4472. end;
  4473. { Order list if needed }
  4474. Order_ObjSectionList(TmpObjSectionList,aname);
  4475. { Add the (ordered) list to the current ExeSection }
  4476. for i:=0 to TmpObjSectionList.Count-1 do
  4477. begin
  4478. objsec:=TObjSection(TmpObjSectionList[i]);
  4479. { If there's no room left in the current section, create a new one }
  4480. if not TNewExeSection(CurrExeSec).CanAddObjSection(objsec,SegmentLimit) then
  4481. AddNewExeSection;
  4482. CurrExeSec.AddObjSection(objsec);
  4483. end;
  4484. TmpObjSectionList.Free;
  4485. end;
  4486. procedure TNewExeOutput.MemPos_Start;
  4487. var
  4488. i: Integer;
  4489. begin
  4490. inherited MemPos_Start;
  4491. for i:=0 to ExeSectionList.Count-1 do
  4492. begin
  4493. MemPos_ExeSection(TExeSection(ExeSectionList[i]));
  4494. CurrMemPos:=0;
  4495. end;
  4496. end;
  4497. procedure TNewExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4498. var
  4499. i,j: longint;
  4500. ImportLibrary: TImportLibrary;
  4501. ImportSymbol: TImportSymbol;
  4502. exesym: TExeSymbol;
  4503. begin
  4504. FImports:=ImportLibraryList;
  4505. AddImportLibrariesExtractedFromObjectModules;
  4506. for i:=0 to FImports.Count-1 do
  4507. begin
  4508. ImportLibrary:=TImportLibrary(FImports[i]);
  4509. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4510. begin
  4511. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4512. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4513. if assigned(exesym) and
  4514. (exesym.State<>symstate_defined) then
  4515. begin
  4516. ImportSymbol.CachedExeSymbol:=exesym;
  4517. exesym.State:=symstate_defined;
  4518. end;
  4519. end;
  4520. end;
  4521. PackUnresolvedExeSymbols('after DLL imports');
  4522. end;
  4523. function TNewExeOutput.writeData: boolean;
  4524. begin
  4525. Result:=False;
  4526. if ExeWriteMode in [ewm_exefull,ewm_exeonly] then
  4527. begin
  4528. Result:=WriteNewExe;
  4529. if not Result then
  4530. exit;
  4531. end;
  4532. end;
  4533. {****************************************************************************
  4534. TOmfAssembler
  4535. ****************************************************************************}
  4536. constructor TOmfAssembler.Create(info: pasminfo; smart:boolean);
  4537. begin
  4538. inherited;
  4539. CObjOutput:=TOmfObjOutput;
  4540. CInternalAr:=TOmfLibObjectWriter;
  4541. end;
  4542. {*****************************************************************************
  4543. Procedures and functions
  4544. *****************************************************************************}
  4545. function StripDllExt(const DllName:TSymStr):TSymStr;
  4546. begin
  4547. if UpCase(ExtractFileExt(DllName))='.DLL' then
  4548. Result:=Copy(DllName,1,Length(DllName)-4)
  4549. else
  4550. Result:=DllName;
  4551. end;
  4552. function MaybeAddDllExt(const DllName: TSymStr): TSymStr;
  4553. begin
  4554. if ExtractFileExt(DllName)='' then
  4555. Result:=ChangeFileExt(DllName,'.dll')
  4556. else
  4557. Result:=DllName;
  4558. end;
  4559. {*****************************************************************************
  4560. Initialize
  4561. *****************************************************************************}
  4562. {$ifdef i8086}
  4563. const
  4564. as_i8086_omf_info : tasminfo =
  4565. (
  4566. id : as_i8086_omf;
  4567. idtxt : 'OMF';
  4568. asmbin : '';
  4569. asmcmd : '';
  4570. supported_targets : [system_i8086_msdos,system_i8086_embedded,system_i8086_win16];
  4571. flags : [af_outputbinary,af_smartlink_sections];
  4572. labelprefix : '..@';
  4573. labelmaxlen : -1;
  4574. comment : '; ';
  4575. dollarsign: '$';
  4576. );
  4577. {$endif i8086}
  4578. initialization
  4579. {$ifdef i8086}
  4580. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  4581. {$endif i8086}
  4582. end.