ogomf.pas 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226
  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. interface
  21. uses
  22. { common }
  23. cclasses,globtype,
  24. { target }
  25. systems,
  26. { assembler }
  27. cpuinfo,cpubase,aasmbase,assemble,link,
  28. { OMF definitions }
  29. omfbase,
  30. { output }
  31. ogbase,
  32. owbase;
  33. type
  34. { TOmfObjSymbol }
  35. TOmfObjSymbol = class(TObjSymbol)
  36. public
  37. { string representation for the linker map file }
  38. function AddressStr(AImageBase: qword): string;override;
  39. end;
  40. { TOmfRelocation }
  41. TOmfRelocation = class(TObjRelocation)
  42. private
  43. FFrameGroup: string;
  44. FOmfFixup: TOmfSubRecord_FIXUP;
  45. public
  46. destructor Destroy; override;
  47. procedure BuildOmfFixup;
  48. property FrameGroup: string read FFrameGroup write FFrameGroup;
  49. property OmfFixup: TOmfSubRecord_FIXUP read FOmfFixup;
  50. end;
  51. TMZExeUnifiedLogicalSegment=class;
  52. { TOmfObjSection }
  53. TOmfObjSection = class(TObjSection)
  54. private
  55. FClassName: string;
  56. FOverlayName: string;
  57. FCombination: TOmfSegmentCombination;
  58. FUse: TOmfSegmentUse;
  59. FPrimaryGroup: TObjSectionGroup;
  60. FSortOrder: Integer;
  61. FMZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment;
  62. FLinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList;
  63. function GetOmfAlignment: TOmfSegmentAlignment;
  64. public
  65. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  66. destructor destroy;override;
  67. function MemPosStr(AImageBase: qword): string;override;
  68. property ClassName: string read FClassName;
  69. property OverlayName: string read FOverlayName;
  70. property OmfAlignment: TOmfSegmentAlignment read GetOmfAlignment;
  71. property Combination: TOmfSegmentCombination read FCombination;
  72. property Use: TOmfSegmentUse read FUse;
  73. property PrimaryGroup: TObjSectionGroup read FPrimaryGroup;
  74. property SortOrder: Integer read FSortOrder write FSortOrder;
  75. property MZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment read FMZExeUnifiedLogicalSegment write FMZExeUnifiedLogicalSegment;
  76. property LinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList read FLinNumEntries;
  77. end;
  78. { TOmfObjData }
  79. TOmfObjData = class(TObjData)
  80. private
  81. FMainSource: TPathStr;
  82. class function CodeSectionName(const aname:string): string;
  83. public
  84. constructor create(const n:string);override;
  85. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;override;
  86. function sectiontype2align(atype:TAsmSectiontype):longint;override;
  87. function sectiontype2class(atype:TAsmSectiontype):string;
  88. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  89. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;override;
  90. function reffardatasection:TObjSection;
  91. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  92. property MainSource: TPathStr read FMainSource;
  93. end;
  94. { TOmfObjOutput }
  95. TOmfObjOutput = class(tObjOutput)
  96. private
  97. FLNames: TOmfOrderedNameCollection;
  98. FSegments: TFPHashObjectList;
  99. FGroups: TFPHashObjectList;
  100. procedure AddSegment(const name,segclass,ovlname: string;
  101. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  102. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  103. procedure AddGroup(group: TObjSectionGroup);
  104. procedure WriteSections(Data:TObjData);
  105. procedure WriteSectionContentAndFixups(sec: TObjSection);
  106. procedure WriteLinNumRecords(sec: TOmfObjSection);
  107. procedure section_count_sections(p:TObject;arg:pointer);
  108. procedure group_count_groups(p:TObject;arg:pointer);
  109. procedure WritePUBDEFs(Data: TObjData);
  110. procedure WriteEXTDEFs(Data: TObjData);
  111. property LNames: TOmfOrderedNameCollection read FLNames;
  112. property Segments: TFPHashObjectList read FSegments;
  113. property Groups: TFPHashObjectList read FGroups;
  114. protected
  115. function writeData(Data:TObjData):boolean;override;
  116. public
  117. constructor create(AWriter:TObjectWriter);override;
  118. destructor Destroy;override;
  119. procedure WriteDllImport(const dllname,afuncname,mangledname:string;ordnr:longint;isvar:boolean);
  120. end;
  121. { TOmfObjInput }
  122. TOmfObjInput = class(TObjInput)
  123. private
  124. FLNames: TOmfOrderedNameCollection;
  125. FExtDefs: TFPHashObjectList;
  126. FPubDefs: TFPHashObjectList;
  127. FFixupThreads: TOmfThreads;
  128. FRawRecord: TOmfRawRecord;
  129. FCOMENTRecord: TOmfRecord_COMENT;
  130. FCaseSensitiveSegments: Boolean;
  131. FCaseSensitiveSymbols: Boolean;
  132. function PeekNextRecordType: Byte;
  133. function ReadLNames(RawRec: TOmfRawRecord): Boolean;
  134. function ReadSegDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  135. function ReadGrpDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  136. function ReadExtDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  137. function ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  138. function ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  139. function ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  140. function ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  141. property LNames: TOmfOrderedNameCollection read FLNames;
  142. property ExtDefs: TFPHashObjectList read FExtDefs;
  143. property PubDefs: TFPHashObjectList read FPubDefs;
  144. { Specifies whether we're case sensitive in regards to segment, class, overlay and group names. }
  145. property CaseSensitiveSegments: Boolean read FCaseSensitiveSegments write FCaseSensitiveSegments;
  146. { Specifies whether symbol names (in EXTDEF and PUBDEF records) are case sensitive. }
  147. property CaseSensitiveSymbols: Boolean read FCaseSensitiveSymbols write FCaseSensitiveSymbols;
  148. public
  149. constructor create;override;
  150. destructor destroy;override;
  151. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  152. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  153. end;
  154. { TMZExeRelocation }
  155. TMZExeRelocation = record
  156. offset: Word;
  157. segment: Word;
  158. end;
  159. TMZExeRelocations = array of TMZExeRelocation;
  160. TMZExeExtraHeaderData = array of Byte;
  161. { TMZExeHeader }
  162. TMZExeHeader = class
  163. private
  164. FChecksum: Word;
  165. FExtraHeaderData: TMZExeExtraHeaderData;
  166. FHeaderSizeAlignment: Integer;
  167. FInitialCS: Word;
  168. FInitialIP: Word;
  169. FInitialSP: Word;
  170. FInitialSS: Word;
  171. FLoadableImageSize: DWord;
  172. FMaxExtraParagraphs: Word;
  173. FMinExtraParagraphs: Word;
  174. FOverlayNumber: Word;
  175. FRelocations: TMZExeRelocations;
  176. procedure SetHeaderSizeAlignment(AValue: Integer);
  177. public
  178. constructor Create;
  179. procedure WriteTo(aWriter: TObjectWriter);
  180. procedure AddRelocation(aSegment,aOffset: Word);
  181. property HeaderSizeAlignment: Integer read FHeaderSizeAlignment write SetHeaderSizeAlignment; {default=16, must be multiple of 16}
  182. property Relocations: TMZExeRelocations read FRelocations write FRelocations;
  183. property ExtraHeaderData: TMZExeExtraHeaderData read FExtraHeaderData write FExtraHeaderData;
  184. property LoadableImageSize: DWord read FLoadableImageSize write FLoadableImageSize;
  185. property MinExtraParagraphs: Word read FMinExtraParagraphs write FMinExtraParagraphs;
  186. property MaxExtraParagraphs: Word read FMaxExtraParagraphs write FMaxExtraParagraphs;
  187. property InitialSS: Word read FInitialSS write FInitialSS;
  188. property InitialSP: Word read FInitialSP write FInitialSP;
  189. property Checksum: Word read FChecksum write FChecksum;
  190. property InitialIP: Word read FInitialIP write FInitialIP;
  191. property InitialCS: Word read FInitialCS write FInitialCS;
  192. property OverlayNumber: Word read FOverlayNumber write FOverlayNumber;
  193. end;
  194. { TMZExeSection }
  195. TMZExeSection=class(TExeSection)
  196. public
  197. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  198. end;
  199. { TMZExeUnifiedLogicalSegment }
  200. TMZExeUnifiedLogicalSegment=class(TFPHashObject)
  201. private
  202. FObjSectionList: TFPObjectList;
  203. FSegName: TSymStr;
  204. FSegClass: TSymStr;
  205. FPrimaryGroup: string;
  206. public
  207. Size,
  208. MemPos,
  209. MemBasePos: qword;
  210. IsStack: Boolean;
  211. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  212. destructor destroy;override;
  213. procedure AddObjSection(ObjSec: TOmfObjSection);
  214. procedure CalcMemPos;
  215. function MemPosStr:string;
  216. property ObjSectionList: TFPObjectList read FObjSectionList;
  217. property SegName: TSymStr read FSegName;
  218. property SegClass: TSymStr read FSegClass;
  219. property PrimaryGroup: string read FPrimaryGroup write FPrimaryGroup;
  220. end;
  221. { TMZExeUnifiedLogicalGroup }
  222. TMZExeUnifiedLogicalGroup=class(TFPHashObject)
  223. private
  224. FSegmentList: TFPHashObjectList;
  225. public
  226. Size,
  227. MemPos: qword;
  228. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  229. destructor destroy;override;
  230. procedure CalcMemPos;
  231. function MemPosStr:string;
  232. procedure AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  233. property SegmentList: TFPHashObjectList read FSegmentList;
  234. end;
  235. { TMZExeOutput }
  236. TMZExeOutput = class(TExeOutput)
  237. private
  238. FMZFlatContentSection: TMZExeSection;
  239. FExeUnifiedLogicalSegments: TFPHashObjectList;
  240. FExeUnifiedLogicalGroups: TFPHashObjectList;
  241. FDwarfUnifiedLogicalSegments: TFPHashObjectList;
  242. FHeader: TMZExeHeader;
  243. function GetMZFlatContentSection: TMZExeSection;
  244. procedure CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  245. procedure CalcExeUnifiedLogicalSegments;
  246. procedure CalcExeGroups;
  247. procedure CalcSegments_MemBasePos;
  248. procedure WriteMap_SegmentsAndGroups;
  249. procedure WriteMap_HeaderData;
  250. function FindStackSegment: TMZExeUnifiedLogicalSegment;
  251. procedure FillLoadableImageSize;
  252. procedure FillMinExtraParagraphs;
  253. procedure FillMaxExtraParagraphs;
  254. procedure FillStartAddress;
  255. procedure FillStackAddress;
  256. procedure FillHeaderData;
  257. function writeExe:boolean;
  258. function writeCom:boolean;
  259. function writeDebugElf:boolean;
  260. property ExeUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  261. property ExeUnifiedLogicalGroups: TFPHashObjectList read FExeUnifiedLogicalGroups;
  262. property DwarfUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  263. property Header: TMZExeHeader read FHeader;
  264. protected
  265. procedure Load_Symbol(const aname:string);override;
  266. procedure DoRelocationFixup(objsec:TObjSection);override;
  267. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  268. procedure MemPos_ExeSection(const aname:string);override;
  269. procedure MemPos_EndExeSection;override;
  270. function writeData:boolean;override;
  271. public
  272. constructor create;override;
  273. destructor destroy;override;
  274. property MZFlatContentSection: TMZExeSection read GetMZFlatContentSection;
  275. end;
  276. TOmfAssembler = class(tinternalassembler)
  277. constructor create(info: pasminfo; smart:boolean);override;
  278. end;
  279. implementation
  280. uses
  281. SysUtils,
  282. cutils,verbose,globals,
  283. fmodule,aasmtai,aasmdata,
  284. ogmap,owomflib,elfbase,
  285. version
  286. ;
  287. const win16stub : array[0..255] of byte=(
  288. $4d,$5a,$00,$01,$01,$00,$00,$00,$08,$00,$10,$00,$ff,$ff,$08,$00,
  289. $00,$01,$00,$00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,
  290. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  291. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,
  292. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  293. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  294. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  295. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  296. $ba,$10,$00,$0e,$1f,$b4,$09,$cd,$21,$b8,$01,$4c,$cd,$21,$90,$90,
  297. $54,$68,$69,$73,$20,$70,$72,$6f,$67,$72,$61,$6d,$20,$72,$65,$71,
  298. $75,$69,$72,$65,$73,$20,$4d,$69,$63,$72,$6f,$73,$6f,$66,$74,$20,
  299. $57,$69,$6e,$64,$6f,$77,$73,$2e,$0d,$0a,$24,$20,$20,$20,$20,$20,
  300. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  301. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  302. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  303. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20);
  304. {****************************************************************************
  305. TTISTrailer
  306. ****************************************************************************}
  307. const
  308. TIS_TRAILER_SIGNATURE: array[1..4] of char='TIS'#0;
  309. TIS_TRAILER_VENDOR_TIS=0;
  310. TIS_TRAILER_TYPE_TIS_DWARF=0;
  311. type
  312. TTISTrailer=record
  313. tis_signature: array[1..4] of char;
  314. tis_vendor,
  315. tis_type,
  316. tis_size: LongWord;
  317. end;
  318. procedure MayBeSwapTISTrailer(var h: TTISTrailer);
  319. begin
  320. if source_info.endian<>target_info.endian then
  321. with h do
  322. begin
  323. tis_vendor:=swapendian(tis_vendor);
  324. tis_type:=swapendian(tis_type);
  325. tis_size:=swapendian(tis_size);
  326. end;
  327. end;
  328. {****************************************************************************
  329. TOmfObjSymbol
  330. ****************************************************************************}
  331. function TOmfObjSymbol.AddressStr(AImageBase: qword): string;
  332. var
  333. base: qword;
  334. begin
  335. if assigned(TOmfObjSection(objsection).MZExeUnifiedLogicalSegment) then
  336. base:=TOmfObjSection(objsection).MZExeUnifiedLogicalSegment.MemBasePos
  337. else
  338. base:=(address shr 4) shl 4;
  339. Result:=HexStr(base shr 4,4)+':'+HexStr(address-base,4);
  340. end;
  341. {****************************************************************************
  342. TOmfRelocation
  343. ****************************************************************************}
  344. destructor TOmfRelocation.Destroy;
  345. begin
  346. FOmfFixup.Free;
  347. inherited Destroy;
  348. end;
  349. procedure TOmfRelocation.BuildOmfFixup;
  350. begin
  351. FreeAndNil(FOmfFixup);
  352. FOmfFixup:=TOmfSubRecord_FIXUP.Create;
  353. if ObjSection<>nil then
  354. begin
  355. FOmfFixup.LocationOffset:=DataOffset;
  356. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  357. FOmfFixup.LocationType:=fltOffset
  358. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  359. FOmfFixup.LocationType:=fltOffset32
  360. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  361. FOmfFixup.LocationType:=fltBase
  362. else
  363. internalerror(2015041501);
  364. FOmfFixup.FrameDeterminedByThread:=False;
  365. FOmfFixup.TargetDeterminedByThread:=False;
  366. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  367. FOmfFixup.Mode:=fmSegmentRelative
  368. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  369. FOmfFixup.Mode:=fmSelfRelative
  370. else
  371. internalerror(2015041401);
  372. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_RELATIVE16,RELOC_RELATIVE32] then
  373. begin
  374. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  375. FOmfFixup.TargetDatum:=ObjSection.Index;
  376. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  377. begin
  378. FOmfFixup.FrameMethod:=ffmGroupIndex;
  379. FOmfFixup.FrameDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  380. end
  381. else
  382. FOmfFixup.FrameMethod:=ffmTarget;
  383. end
  384. else
  385. begin
  386. FOmfFixup.FrameMethod:=ffmTarget;
  387. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  388. begin
  389. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  390. FOmfFixup.TargetDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  391. end
  392. else
  393. begin
  394. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  395. FOmfFixup.TargetDatum:=ObjSection.Index;
  396. end;
  397. end;
  398. end
  399. else if symbol<>nil then
  400. begin
  401. FOmfFixup.LocationOffset:=DataOffset;
  402. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  403. FOmfFixup.LocationType:=fltOffset
  404. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  405. FOmfFixup.LocationType:=fltOffset32
  406. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  407. FOmfFixup.LocationType:=fltBase
  408. else
  409. internalerror(2015041501);
  410. FOmfFixup.FrameDeterminedByThread:=False;
  411. FOmfFixup.TargetDeterminedByThread:=False;
  412. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  413. FOmfFixup.Mode:=fmSegmentRelative
  414. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  415. FOmfFixup.Mode:=fmSelfRelative
  416. else
  417. internalerror(2015041401);
  418. FOmfFixup.TargetMethod:=ftmExternalIndexNoDisp;
  419. FOmfFixup.TargetDatum:=symbol.symidx;
  420. FOmfFixup.FrameMethod:=ffmTarget;
  421. end
  422. else if group<>nil then
  423. begin
  424. FOmfFixup.LocationOffset:=DataOffset;
  425. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  426. FOmfFixup.LocationType:=fltOffset
  427. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  428. FOmfFixup.LocationType:=fltOffset32
  429. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  430. FOmfFixup.LocationType:=fltBase
  431. else
  432. internalerror(2015041501);
  433. FOmfFixup.FrameDeterminedByThread:=False;
  434. FOmfFixup.TargetDeterminedByThread:=False;
  435. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  436. FOmfFixup.Mode:=fmSegmentRelative
  437. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  438. FOmfFixup.Mode:=fmSelfRelative
  439. else
  440. internalerror(2015041401);
  441. FOmfFixup.FrameMethod:=ffmTarget;
  442. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  443. FOmfFixup.TargetDatum:=group.index;
  444. end
  445. else
  446. internalerror(2015040702);
  447. end;
  448. {****************************************************************************
  449. TOmfObjSection
  450. ****************************************************************************}
  451. function TOmfObjSection.GetOmfAlignment: TOmfSegmentAlignment;
  452. begin
  453. case SecAlign of
  454. 1:
  455. result:=saRelocatableByteAligned;
  456. 2:
  457. result:=saRelocatableWordAligned;
  458. 4:
  459. result:=saRelocatableDWordAligned;
  460. 16:
  461. result:=saRelocatableParaAligned;
  462. 256:
  463. result:=saRelocatablePageAligned;
  464. 4096:
  465. result:=saNotSupported;
  466. else
  467. internalerror(2015041504);
  468. end;
  469. end;
  470. constructor TOmfObjSection.create(AList: TFPHashObjectList;
  471. const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  472. begin
  473. inherited create(AList, Aname, Aalign, Aoptions);
  474. FCombination:=scPublic;
  475. FUse:=suUse16;
  476. FLinNumEntries:=TOmfSubRecord_LINNUM_MsLink_LineNumberList.Create;
  477. end;
  478. destructor TOmfObjSection.destroy;
  479. begin
  480. FLinNumEntries.Free;
  481. inherited destroy;
  482. end;
  483. function TOmfObjSection.MemPosStr(AImageBase: qword): string;
  484. begin
  485. Result:=HexStr(MZExeUnifiedLogicalSegment.MemBasePos shr 4,4)+':'+
  486. HexStr(MemPos-MZExeUnifiedLogicalSegment.MemBasePos,4);
  487. end;
  488. {****************************************************************************
  489. TOmfObjData
  490. ****************************************************************************}
  491. class function TOmfObjData.CodeSectionName(const aname: string): string;
  492. begin
  493. {$ifdef i8086}
  494. if current_settings.x86memorymodel in x86_far_code_models then
  495. begin
  496. if cs_huge_code in current_settings.moduleswitches then
  497. result:=aname + '_TEXT'
  498. else
  499. result:=current_module.modulename^ + '_TEXT';
  500. end
  501. else
  502. {$endif}
  503. result:='_TEXT';
  504. end;
  505. constructor TOmfObjData.create(const n: string);
  506. begin
  507. inherited create(n);
  508. CObjSymbol:=TOmfObjSymbol;
  509. CObjSection:=TOmfObjSection;
  510. createsectiongroup('DGROUP');
  511. FMainSource:=current_module.mainsource;
  512. end;
  513. function TOmfObjData.sectiontype2options(atype: TAsmSectiontype): TObjSectionOptions;
  514. begin
  515. Result:=inherited sectiontype2options(atype);
  516. { in the huge memory model, BSS data is actually written in the regular
  517. FAR_DATA segment of the module }
  518. if sectiontype2class(atype)='FAR_DATA' then
  519. Result:=Result+[oso_data,oso_sparse_data];
  520. end;
  521. function TOmfObjData.sectiontype2align(atype: TAsmSectiontype): longint;
  522. begin
  523. Result:=omf_sectiontype2align(atype);
  524. end;
  525. function TOmfObjData.sectiontype2class(atype: TAsmSectiontype): string;
  526. begin
  527. Result:=omf_segclass(atype);
  528. end;
  529. function TOmfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  530. var
  531. sep : string[3];
  532. secname : string;
  533. begin
  534. if (atype=sec_user) then
  535. Result:=aname
  536. else
  537. begin
  538. if omf_secnames[atype]=omf_secnames[sec_code] then
  539. secname:=CodeSectionName(aname)
  540. else if omf_segclass(atype)='FAR_DATA' then
  541. secname:=current_module.modulename^ + '_DATA'
  542. else
  543. secname:=omf_secnames[atype];
  544. if create_smartlink_sections and (aname<>'') then
  545. begin
  546. case aorder of
  547. secorder_begin :
  548. sep:='.b_';
  549. secorder_end :
  550. sep:='.z_';
  551. else
  552. sep:='.n_';
  553. end;
  554. result:=UpCase(secname+sep+aname);
  555. end
  556. else
  557. result:=secname;
  558. end;
  559. end;
  560. function TOmfObjData.createsection(atype: TAsmSectionType; const aname: string; aorder: TAsmSectionOrder): TObjSection;
  561. var
  562. is_new: Boolean;
  563. primary_group: String;
  564. grp: TObjSectionGroup;
  565. begin
  566. is_new:=TObjSection(ObjSectionList.Find(sectionname(atype,aname,aorder)))=nil;
  567. Result:=inherited createsection(atype, aname, aorder);
  568. if is_new then
  569. begin
  570. TOmfObjSection(Result).FClassName:=sectiontype2class(atype);
  571. if atype=sec_stack then
  572. TOmfObjSection(Result).FCombination:=scStack
  573. else if atype in [sec_debug_frame,sec_debug_info,sec_debug_line,sec_debug_abbrev,sec_debug_aranges,sec_debug_ranges] then
  574. begin
  575. TOmfObjSection(Result).FUse:=suUse32;
  576. TOmfObjSection(Result).SizeLimit:=high(longword);
  577. end;
  578. primary_group:=omf_section_primary_group(atype,aname);
  579. if primary_group<>'' then
  580. begin
  581. { find the primary group, if it already exists, else create it }
  582. grp:=nil;
  583. if GroupsList<>nil then
  584. grp:=TObjSectionGroup(GroupsList.Find(primary_group));
  585. if grp=nil then
  586. grp:=createsectiongroup(primary_group);
  587. { add the current section to the group }
  588. SetLength(grp.members,Length(grp.members)+1);
  589. grp.members[High(grp.members)]:=Result;
  590. TOmfObjSection(Result).FPrimaryGroup:=grp;
  591. end;
  592. end;
  593. end;
  594. function TOmfObjData.reffardatasection: TObjSection;
  595. var
  596. secname: string;
  597. begin
  598. secname:=current_module.modulename^ + '_DATA';
  599. result:=TObjSection(ObjSectionList.Find(secname));
  600. if not assigned(result) then
  601. begin
  602. result:=CObjSection.create(ObjSectionList,secname,2,[oso_Data,oso_load,oso_write]);
  603. result.ObjData:=self;
  604. TOmfObjSection(Result).FClassName:='FAR_DATA';
  605. end;
  606. end;
  607. procedure TOmfObjData.writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  608. var
  609. objreloc: TOmfRelocation;
  610. symaddr: AWord;
  611. begin
  612. { RELOC_FARPTR = RELOC_ABSOLUTE16+RELOC_SEG }
  613. if Reloctype=RELOC_FARPTR then
  614. begin
  615. if len<>4 then
  616. internalerror(2015041502);
  617. writeReloc(Data,2,p,RELOC_ABSOLUTE16);
  618. writeReloc(0,2,p,RELOC_SEG);
  619. exit;
  620. end
  621. { RELOC_FARPTR48 = RELOC_ABSOLUTE16+RELOC_SEG }
  622. else if Reloctype=RELOC_FARPTR48 then
  623. begin
  624. if len<>6 then
  625. internalerror(2015041502);
  626. writeReloc(Data,4,p,RELOC_ABSOLUTE32);
  627. writeReloc(0,2,p,RELOC_SEG);
  628. exit;
  629. end;
  630. if CurrObjSec=nil then
  631. internalerror(200403072);
  632. objreloc:=nil;
  633. if Reloctype in [RELOC_FARDATASEG,RELOC_FARDATASEGREL] then
  634. begin
  635. if Reloctype=RELOC_FARDATASEG then
  636. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEG)
  637. else
  638. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEGREL);
  639. CurrObjSec.ObjRelocations.Add(objreloc);
  640. end
  641. else if assigned(p) then
  642. begin
  643. { real address of the symbol }
  644. symaddr:=p.address;
  645. if p.bind=AB_EXTERNAL then
  646. begin
  647. objreloc:=TOmfRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  648. CurrObjSec.ObjRelocations.Add(objreloc);
  649. end
  650. { relative relocations within the same section can be calculated directly,
  651. without the need to emit a relocation entry }
  652. else if (p.objsection=CurrObjSec) and
  653. (p.bind<>AB_COMMON) and
  654. (Reloctype=RELOC_RELATIVE) then
  655. begin
  656. data:=data+symaddr-len-CurrObjSec.Size;
  657. end
  658. else
  659. begin
  660. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,p.objsection,Reloctype);
  661. CurrObjSec.ObjRelocations.Add(objreloc);
  662. if not (Reloctype in [RELOC_SEG,RELOC_SEGREL]) then
  663. inc(data,symaddr);
  664. end;
  665. end
  666. else if Reloctype in [RELOC_DGROUP,RELOC_DGROUPREL] then
  667. begin
  668. if Reloctype=RELOC_DGROUP then
  669. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEG)
  670. else
  671. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEGREL);
  672. CurrObjSec.ObjRelocations.Add(objreloc);
  673. end;
  674. CurrObjSec.write(data,len);
  675. end;
  676. {****************************************************************************
  677. TOmfObjOutput
  678. ****************************************************************************}
  679. procedure TOmfObjOutput.AddSegment(const name, segclass, ovlname: string;
  680. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  681. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  682. var
  683. s: TOmfRecord_SEGDEF;
  684. begin
  685. s:=TOmfRecord_SEGDEF.Create;
  686. Segments.Add(name,s);
  687. s.SegmentNameIndex:=LNames.Add(name);
  688. s.ClassNameIndex:=LNames.Add(segclass);
  689. s.OverlayNameIndex:=LNames.Add(ovlname);
  690. s.Alignment:=Alignment;
  691. s.Combination:=Combination;
  692. s.Use:=Use;
  693. s.SegmentLength:=Size;
  694. end;
  695. procedure TOmfObjOutput.AddGroup(group: TObjSectionGroup);
  696. var
  697. g: TOmfRecord_GRPDEF;
  698. seglist: TSegmentList;
  699. I: Integer;
  700. begin
  701. seglist:=nil;
  702. g:=TOmfRecord_GRPDEF.Create;
  703. Groups.Add(group.Name,g);
  704. g.GroupNameIndex:=LNames.Add(group.Name);
  705. SetLength(seglist,Length(group.members));
  706. for I:=Low(group.members) to High(group.members) do
  707. seglist[I]:=group.members[I].index;
  708. g.SegmentList:=seglist;
  709. end;
  710. procedure TOmfObjOutput.WriteSections(Data: TObjData);
  711. var
  712. i:longint;
  713. sec:TObjSection;
  714. begin
  715. for i:=0 to Data.ObjSectionList.Count-1 do
  716. begin
  717. sec:=TObjSection(Data.ObjSectionList[i]);
  718. WriteSectionContentAndFixups(sec);
  719. WriteLinNumRecords(TOmfObjSection(sec));
  720. end;
  721. end;
  722. procedure TOmfObjOutput.WriteSectionContentAndFixups(sec: TObjSection);
  723. const
  724. MaxChunkSize=$3fa;
  725. var
  726. RawRecord: TOmfRawRecord;
  727. ChunkStart,ChunkLen: DWord;
  728. ChunkFixupStart,ChunkFixupEnd: Integer;
  729. SegIndex: Integer;
  730. NextOfs: Integer;
  731. Is32BitLEDATA: Boolean;
  732. I: Integer;
  733. begin
  734. if (oso_data in sec.SecOptions) then
  735. begin
  736. if sec.Data=nil then
  737. internalerror(200403073);
  738. for I:=0 to sec.ObjRelocations.Count-1 do
  739. TOmfRelocation(sec.ObjRelocations[I]).BuildOmfFixup;
  740. SegIndex:=Segments.FindIndexOf(sec.Name);
  741. RawRecord:=TOmfRawRecord.Create;
  742. sec.data.seek(0);
  743. ChunkFixupStart:=0;
  744. ChunkFixupEnd:=-1;
  745. ChunkStart:=0;
  746. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  747. while ChunkLen>0 do
  748. begin
  749. { find last fixup in the chunk }
  750. while (ChunkFixupEnd<(sec.ObjRelocations.Count-1)) and
  751. (TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd+1]).DataOffset<(ChunkStart+ChunkLen)) do
  752. inc(ChunkFixupEnd);
  753. { check if last chunk is crossing the chunk boundary, and trim ChunkLen if necessary }
  754. if (ChunkFixupEnd>=ChunkFixupStart) and
  755. ((TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset+
  756. TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).OmfFixup.LocationSize)>(ChunkStart+ChunkLen)) then
  757. begin
  758. ChunkLen:=TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset-ChunkStart;
  759. Dec(ChunkFixupEnd);
  760. end;
  761. { write LEDATA record }
  762. Is32BitLEDATA:=TOmfObjSection(sec).Use=suUse32;
  763. if Is32BitLEDATA then
  764. RawRecord.RecordType:=RT_LEDATA32
  765. else
  766. RawRecord.RecordType:=RT_LEDATA;
  767. NextOfs:=RawRecord.WriteIndexedRef(0,SegIndex);
  768. if Is32BitLEDATA then
  769. begin
  770. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  771. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  772. RawRecord.RawData[NextOfs+2]:=Byte(ChunkStart shr 16);
  773. RawRecord.RawData[NextOfs+3]:=Byte(ChunkStart shr 24);
  774. Inc(NextOfs,4);
  775. end
  776. else
  777. begin
  778. if ChunkStart>$ffff then
  779. internalerror(2018052201);
  780. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  781. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  782. Inc(NextOfs,2);
  783. end;
  784. sec.data.read(RawRecord.RawData[NextOfs], ChunkLen);
  785. Inc(NextOfs, ChunkLen);
  786. RawRecord.RecordLength:=NextOfs+1;
  787. RawRecord.CalculateChecksumByte;
  788. RawRecord.WriteTo(FWriter);
  789. { write FIXUPP record }
  790. if ChunkFixupEnd>=ChunkFixupStart then
  791. begin
  792. RawRecord.RecordType:=RT_FIXUPP;
  793. NextOfs:=0;
  794. for I:=ChunkFixupStart to ChunkFixupEnd do
  795. begin
  796. TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.DataRecordStartOffset:=ChunkStart;
  797. NextOfs:=TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.WriteAt(RawRecord,NextOfs);
  798. end;
  799. RawRecord.RecordLength:=NextOfs+1;
  800. RawRecord.CalculateChecksumByte;
  801. RawRecord.WriteTo(FWriter);
  802. end;
  803. { prepare next chunk }
  804. Inc(ChunkStart, ChunkLen);
  805. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  806. ChunkFixupStart:=ChunkFixupEnd+1;
  807. end;
  808. RawRecord.Free;
  809. end;
  810. end;
  811. procedure TOmfObjOutput.WriteLinNumRecords(sec: TOmfObjSection);
  812. var
  813. SegIndex: Integer;
  814. RawRecord: TOmfRawRecord;
  815. LinNumRec: TOmfRecord_LINNUM_MsLink;
  816. begin
  817. if (oso_data in sec.SecOptions) then
  818. begin
  819. if sec.Data=nil then
  820. internalerror(200403073);
  821. if sec.LinNumEntries.Count=0 then
  822. exit;
  823. SegIndex:=Segments.FindIndexOf(sec.Name);
  824. RawRecord:=TOmfRawRecord.Create;
  825. LinNumRec:=TOmfRecord_LINNUM_MsLink.Create;
  826. LinNumRec.BaseGroup:=0;
  827. LinNumRec.BaseSegment:=SegIndex;
  828. LinNumRec.LineNumberList:=sec.LinNumEntries;
  829. while LinNumRec.NextIndex<sec.LinNumEntries.Count do
  830. begin
  831. LinNumRec.EncodeTo(RawRecord);
  832. RawRecord.WriteTo(FWriter);
  833. end;
  834. LinNumRec.Free;
  835. RawRecord.Free;
  836. end;
  837. end;
  838. procedure TOmfObjOutput.section_count_sections(p: TObject; arg: pointer);
  839. begin
  840. TOmfObjSection(p).index:=pinteger(arg)^;
  841. inc(pinteger(arg)^);
  842. end;
  843. procedure TOmfObjOutput.group_count_groups(p: TObject; arg: pointer);
  844. begin
  845. TObjSectionGroup(p).index:=pinteger(arg)^;
  846. inc(pinteger(arg)^);
  847. end;
  848. procedure TOmfObjOutput.WritePUBDEFs(Data: TObjData);
  849. var
  850. PubNamesForSection: array of TFPHashObjectList;
  851. i: Integer;
  852. objsym: TObjSymbol;
  853. PublicNameElem: TOmfPublicNameElement;
  854. RawRecord: TOmfRawRecord;
  855. PubDefRec: TOmfRecord_PUBDEF;
  856. begin
  857. PubNamesForSection:=nil;
  858. RawRecord:=TOmfRawRecord.Create;
  859. SetLength(PubNamesForSection,Data.ObjSectionList.Count);
  860. for i:=0 to Data.ObjSectionList.Count-1 do
  861. PubNamesForSection[i]:=TFPHashObjectList.Create;
  862. for i:=0 to Data.ObjSymbolList.Count-1 do
  863. begin
  864. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  865. if objsym.bind=AB_GLOBAL then
  866. begin
  867. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  868. PublicNameElem.PublicOffset:=objsym.offset;
  869. PublicNameElem.IsLocal:=False;
  870. end
  871. else if objsym.bind=AB_LOCAL then
  872. begin
  873. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  874. PublicNameElem.PublicOffset:=objsym.offset;
  875. PublicNameElem.IsLocal:=True;
  876. end
  877. end;
  878. for i:=0 to Data.ObjSectionList.Count-1 do
  879. if PubNamesForSection[i].Count>0 then
  880. begin
  881. PubDefRec:=TOmfRecord_PUBDEF.Create;
  882. PubDefRec.BaseSegmentIndex:=i+1;
  883. if TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup<>nil then
  884. PubDefRec.BaseGroupIndex:=Groups.FindIndexOf(TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup.Name)
  885. else
  886. PubDefRec.BaseGroupIndex:=0;
  887. PubDefRec.PublicNames:=PubNamesForSection[i];
  888. while PubDefRec.NextIndex<PubDefRec.PublicNames.Count do
  889. begin
  890. PubDefRec.EncodeTo(RawRecord);
  891. RawRecord.WriteTo(FWriter);
  892. end;
  893. PubDefRec.Free;
  894. end;
  895. for i:=0 to Data.ObjSectionList.Count-1 do
  896. FreeAndNil(PubNamesForSection[i]);
  897. RawRecord.Free;
  898. end;
  899. procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
  900. var
  901. ExtNames: TFPHashObjectList;
  902. RawRecord: TOmfRawRecord;
  903. i,idx: Integer;
  904. objsym: TObjSymbol;
  905. ExternalNameElem: TOmfExternalNameElement;
  906. ExtDefRec: TOmfRecord_EXTDEF;
  907. begin
  908. ExtNames:=TFPHashObjectList.Create;
  909. RawRecord:=TOmfRawRecord.Create;
  910. idx:=1;
  911. for i:=0 to Data.ObjSymbolList.Count-1 do
  912. begin
  913. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  914. if objsym.bind=AB_EXTERNAL then
  915. begin
  916. ExternalNameElem:=TOmfExternalNameElement.Create(ExtNames,objsym.Name);
  917. objsym.symidx:=idx;
  918. Inc(idx);
  919. end;
  920. end;
  921. if ExtNames.Count>0 then
  922. begin
  923. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  924. ExtDefRec.ExternalNames:=ExtNames;
  925. while ExtDefRec.NextIndex<ExtDefRec.ExternalNames.Count do
  926. begin
  927. ExtDefRec.EncodeTo(RawRecord);
  928. RawRecord.WriteTo(FWriter);
  929. end;
  930. ExtDefRec.Free;
  931. end;
  932. ExtNames.Free;
  933. RawRecord.Free;
  934. end;
  935. function TOmfObjOutput.writeData(Data:TObjData):boolean;
  936. var
  937. RawRecord: TOmfRawRecord;
  938. Header: TOmfRecord_THEADR;
  939. Translator_COMENT: TOmfRecord_COMENT;
  940. DebugFormat_COMENT: TOmfRecord_COMENT;
  941. LinkPassSeparator_COMENT: TOmfRecord_COMENT;
  942. LNamesRec: TOmfRecord_LNAMES;
  943. ModEnd: TOmfRecord_MODEND;
  944. I: Integer;
  945. SegDef: TOmfRecord_SEGDEF;
  946. GrpDef: TOmfRecord_GRPDEF;
  947. nsections,ngroups: Integer;
  948. objsym: TObjSymbol;
  949. begin
  950. { calc amount of sections we have and set their index, starting with 1 }
  951. nsections:=1;
  952. data.ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  953. { calc amount of groups we have and set their index, starting with 1 }
  954. ngroups:=1;
  955. data.GroupsList.ForEachCall(@group_count_groups,@ngroups);
  956. { maximum amount of sections supported in the omf format is $7fff }
  957. if (nsections-1)>$7fff then
  958. internalerror(2015040701);
  959. { maximum amount of groups supported in the omf format is $7fff }
  960. if (ngroups-1)>$7fff then
  961. internalerror(2018062101);
  962. { write header record }
  963. RawRecord:=TOmfRawRecord.Create;
  964. Header:=TOmfRecord_THEADR.Create;
  965. if cs_debuginfo in current_settings.moduleswitches then
  966. Header.ModuleName:=TOmfObjData(Data).MainSource
  967. else
  968. Header.ModuleName:=Data.Name;
  969. Header.EncodeTo(RawRecord);
  970. RawRecord.WriteTo(FWriter);
  971. Header.Free;
  972. { write translator COMENT header }
  973. Translator_COMENT:=TOmfRecord_COMENT.Create;
  974. Translator_COMENT.CommentClass:=CC_Translator;
  975. Translator_COMENT.CommentString:='FPC '+full_version_string+
  976. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  977. Translator_COMENT.EncodeTo(RawRecord);
  978. RawRecord.WriteTo(FWriter);
  979. Translator_COMENT.Free;
  980. if (target_dbg.id=dbg_codeview) or
  981. ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
  982. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) then
  983. begin
  984. DebugFormat_COMENT:=TOmfRecord_COMENT.Create;
  985. DebugFormat_COMENT.CommentClass:=CC_NewOmfExtension;
  986. DebugFormat_COMENT.CommentString:='';
  987. DebugFormat_COMENT.EncodeTo(RawRecord);
  988. RawRecord.WriteTo(FWriter);
  989. DebugFormat_COMENT.Free;
  990. end;
  991. LNames.Clear;
  992. LNames.Add(''); { insert an empty string, which has index 1 }
  993. FSegments.Clear;
  994. FSegments.Add('',nil);
  995. FGroups.Clear;
  996. FGroups.Add('',nil);
  997. for i:=0 to Data.GroupsList.Count-1 do
  998. AddGroup(TObjSectionGroup(Data.GroupsList[I]));
  999. for i:=0 to Data.ObjSectionList.Count-1 do
  1000. with TOmfObjSection(Data.ObjSectionList[I]) do
  1001. AddSegment(Name,ClassName,OverlayName,OmfAlignment,Combination,Use,Size);
  1002. { write LNAMES record(s) }
  1003. LNamesRec:=TOmfRecord_LNAMES.Create;
  1004. LNamesRec.Names:=LNames;
  1005. while LNamesRec.NextIndex<=LNames.Count do
  1006. begin
  1007. LNamesRec.EncodeTo(RawRecord);
  1008. RawRecord.WriteTo(FWriter);
  1009. end;
  1010. LNamesRec.Free;
  1011. { write SEGDEF record(s) }
  1012. for I:=1 to Segments.Count-1 do
  1013. begin
  1014. SegDef:=TOmfRecord_SEGDEF(Segments[I]);
  1015. SegDef.EncodeTo(RawRecord);
  1016. RawRecord.WriteTo(FWriter);
  1017. end;
  1018. { write GRPDEF record(s) }
  1019. for I:=1 to Groups.Count-1 do
  1020. begin
  1021. GrpDef:=TOmfRecord_GRPDEF(Groups[I]);
  1022. GrpDef.EncodeTo(RawRecord);
  1023. RawRecord.WriteTo(FWriter);
  1024. end;
  1025. { write PUBDEF record(s) }
  1026. WritePUBDEFs(Data);
  1027. { write EXTDEF record(s) }
  1028. WriteEXTDEFs(Data);
  1029. { write link pass separator }
  1030. LinkPassSeparator_COMENT:=TOmfRecord_COMENT.Create;
  1031. LinkPassSeparator_COMENT.CommentClass:=CC_LinkPassSeparator;
  1032. LinkPassSeparator_COMENT.CommentString:=#1;
  1033. LinkPassSeparator_COMENT.NoList:=True;
  1034. LinkPassSeparator_COMENT.EncodeTo(RawRecord);
  1035. RawRecord.WriteTo(FWriter);
  1036. LinkPassSeparator_COMENT.Free;
  1037. { write section content, interleaved with fixups }
  1038. WriteSections(Data);
  1039. { write MODEND record }
  1040. ModEnd:=TOmfRecord_MODEND.Create;
  1041. ModEnd.EncodeTo(RawRecord);
  1042. RawRecord.WriteTo(FWriter);
  1043. ModEnd.Free;
  1044. RawRecord.Free;
  1045. result:=true;
  1046. end;
  1047. constructor TOmfObjOutput.create(AWriter:TObjectWriter);
  1048. begin
  1049. inherited create(AWriter);
  1050. cobjdata:=TOmfObjData;
  1051. FLNames:=TOmfOrderedNameCollection.Create(False);
  1052. FSegments:=TFPHashObjectList.Create;
  1053. FSegments.Add('',nil);
  1054. FGroups:=TFPHashObjectList.Create;
  1055. FGroups.Add('',nil);
  1056. end;
  1057. destructor TOmfObjOutput.Destroy;
  1058. begin
  1059. FGroups.Free;
  1060. FSegments.Free;
  1061. FLNames.Free;
  1062. inherited Destroy;
  1063. end;
  1064. procedure TOmfObjOutput.WriteDllImport(const dllname,afuncname,mangledname: string; ordnr: longint; isvar: boolean);
  1065. var
  1066. RawRecord: TOmfRawRecord;
  1067. Header: TOmfRecord_THEADR;
  1068. DllImport_COMENT: TOmfRecord_COMENT;
  1069. ModEnd: TOmfRecord_MODEND;
  1070. begin
  1071. { write header record }
  1072. RawRecord:=TOmfRawRecord.Create;
  1073. Header:=TOmfRecord_THEADR.Create;
  1074. Header.ModuleName:=mangledname;
  1075. Header.EncodeTo(RawRecord);
  1076. RawRecord.WriteTo(FWriter);
  1077. Header.Free;
  1078. { write IMPDEF record }
  1079. DllImport_COMENT:=TOmfRecord_COMENT.Create;
  1080. DllImport_COMENT.CommentClass:=CC_OmfExtension;
  1081. if ordnr <= 0 then
  1082. begin
  1083. if afuncname=mangledname then
  1084. DllImport_COMENT.CommentString:=#1#0+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+#0
  1085. else
  1086. DllImport_COMENT.CommentString:=#1#0+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+Chr(Length(afuncname))+afuncname;
  1087. end
  1088. else
  1089. DllImport_COMENT.CommentString:=#1#1+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+Chr(ordnr and $ff)+Chr((ordnr shr 8) and $ff);
  1090. DllImport_COMENT.EncodeTo(RawRecord);
  1091. RawRecord.WriteTo(FWriter);
  1092. DllImport_COMENT.Free;
  1093. { write MODEND record }
  1094. ModEnd:=TOmfRecord_MODEND.Create;
  1095. ModEnd.EncodeTo(RawRecord);
  1096. RawRecord.WriteTo(FWriter);
  1097. ModEnd.Free;
  1098. RawRecord.Free;
  1099. end;
  1100. {****************************************************************************
  1101. TOmfObjInput
  1102. ****************************************************************************}
  1103. function TOmfObjInput.PeekNextRecordType: Byte;
  1104. var
  1105. OldPos: LongInt;
  1106. begin
  1107. OldPos:=FReader.Pos;
  1108. if not FReader.read(Result, 1) then
  1109. begin
  1110. InputError('Unexpected end of file');
  1111. Result:=0;
  1112. exit;
  1113. end;
  1114. FReader.seek(OldPos);
  1115. end;
  1116. function TOmfObjInput.ReadLNames(RawRec: TOmfRawRecord): Boolean;
  1117. var
  1118. LNamesRec: TOmfRecord_LNAMES;
  1119. begin
  1120. Result:=False;
  1121. LNamesRec:=TOmfRecord_LNAMES.Create;
  1122. LNamesRec.Names:=LNames;
  1123. LNamesRec.DecodeFrom(RawRec);
  1124. LNamesRec.Free;
  1125. Result:=True;
  1126. end;
  1127. function TOmfObjInput.ReadSegDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1128. var
  1129. SegDefRec: TOmfRecord_SEGDEF;
  1130. SegmentName,SegClassName,OverlayName: string;
  1131. SecAlign: LongInt;
  1132. secoptions: TObjSectionOptions;
  1133. objsec: TOmfObjSection;
  1134. begin
  1135. Result:=False;
  1136. SegDefRec:=TOmfRecord_SEGDEF.Create;
  1137. SegDefRec.DecodeFrom(RawRec);
  1138. if (SegDefRec.SegmentNameIndex<1) or (SegDefRec.SegmentNameIndex>LNames.Count) then
  1139. begin
  1140. InputError('Segment name index out of range');
  1141. SegDefRec.Free;
  1142. exit;
  1143. end;
  1144. SegmentName:=LNames[SegDefRec.SegmentNameIndex];
  1145. if (SegDefRec.ClassNameIndex<1) or (SegDefRec.ClassNameIndex>LNames.Count) then
  1146. begin
  1147. InputError('Segment class name index out of range');
  1148. SegDefRec.Free;
  1149. exit;
  1150. end;
  1151. SegClassName:=LNames[SegDefRec.ClassNameIndex];
  1152. if (SegDefRec.OverlayNameIndex<1) or (SegDefRec.OverlayNameIndex>LNames.Count) then
  1153. begin
  1154. InputError('Segment overlay name index out of range');
  1155. SegDefRec.Free;
  1156. exit;
  1157. end;
  1158. OverlayName:=LNames[SegDefRec.OverlayNameIndex];
  1159. SecAlign:=1; // otherwise warning prohibits compilation
  1160. case SegDefRec.Alignment of
  1161. saRelocatableByteAligned:
  1162. SecAlign:=1;
  1163. saRelocatableWordAligned:
  1164. SecAlign:=2;
  1165. saRelocatableParaAligned:
  1166. SecAlign:=16;
  1167. saRelocatableDWordAligned:
  1168. SecAlign:=4;
  1169. saRelocatablePageAligned:
  1170. SecAlign:=256;
  1171. saNotSupported:
  1172. SecAlign:=4096;
  1173. saAbsolute:
  1174. begin
  1175. InputError('Absolute segment alignment not supported');
  1176. SegDefRec.Free;
  1177. exit;
  1178. end;
  1179. saNotDefined:
  1180. begin
  1181. InputError('Invalid (unsupported/undefined) OMF segment alignment');
  1182. SegDefRec.Free;
  1183. exit;
  1184. end;
  1185. end;
  1186. if not CaseSensitiveSegments then
  1187. begin
  1188. SegmentName:=UpCase(SegmentName);
  1189. SegClassName:=UpCase(SegClassName);
  1190. OverlayName:=UpCase(OverlayName);
  1191. end;
  1192. { hack for supporting object modules, generated by Borland's BINOBJ tool }
  1193. if (SegClassName='') and (SegmentName='CODE') then
  1194. begin
  1195. SegmentName:=InputFileName;
  1196. SegClassName:='CODE';
  1197. end;
  1198. secoptions:=[];
  1199. objsec:=TOmfObjSection(objdata.createsection(SegmentName+'||'+SegClassName,SecAlign,secoptions,false));
  1200. objsec.FClassName:=SegClassName;
  1201. objsec.FOverlayName:=OverlayName;
  1202. objsec.FCombination:=SegDefRec.Combination;
  1203. objsec.FUse:=SegDefRec.Use;
  1204. if SegDefRec.SegmentLength>High(objsec.Size) then
  1205. begin
  1206. InputError('Segment too large');
  1207. SegDefRec.Free;
  1208. exit;
  1209. end;
  1210. objsec.Size:=SegDefRec.SegmentLength;
  1211. if SegClassName='DWARF' then
  1212. objsec.SecOptions:=objsec.SecOptions+[oso_debug];
  1213. if (SegClassName='HEAP') or
  1214. (SegClassName='STACK') or (SegDefRec.Combination=scStack) or
  1215. (SegClassName='BEGDATA') or
  1216. (SegmentName='FPC') then
  1217. objsec.SecOptions:=objsec.SecOptions+[oso_keep];
  1218. SegDefRec.Free;
  1219. Result:=True;
  1220. end;
  1221. function TOmfObjInput.ReadGrpDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1222. var
  1223. GrpDefRec: TOmfRecord_GRPDEF;
  1224. GroupName: string;
  1225. SecGroup: TObjSectionGroup;
  1226. i,SegIndex: Integer;
  1227. begin
  1228. Result:=False;
  1229. GrpDefRec:=TOmfRecord_GRPDEF.Create;
  1230. GrpDefRec.DecodeFrom(RawRec);
  1231. if (GrpDefRec.GroupNameIndex<1) or (GrpDefRec.GroupNameIndex>LNames.Count) then
  1232. begin
  1233. InputError('Group name index out of range');
  1234. GrpDefRec.Free;
  1235. exit;
  1236. end;
  1237. GroupName:=LNames[GrpDefRec.GroupNameIndex];
  1238. if not CaseSensitiveSegments then
  1239. GroupName:=UpCase(GroupName);
  1240. SecGroup:=objdata.createsectiongroup(GroupName);
  1241. SetLength(SecGroup.members,Length(GrpDefRec.SegmentList));
  1242. for i:=0 to Length(GrpDefRec.SegmentList)-1 do
  1243. begin
  1244. SegIndex:=GrpDefRec.SegmentList[i];
  1245. if (SegIndex<1) or (SegIndex>objdata.ObjSectionList.Count) then
  1246. begin
  1247. InputError('Segment name index out of range in group definition');
  1248. GrpDefRec.Free;
  1249. exit;
  1250. end;
  1251. SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
  1252. end;
  1253. GrpDefRec.Free;
  1254. Result:=True;
  1255. end;
  1256. function TOmfObjInput.ReadExtDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1257. var
  1258. ExtDefRec: TOmfRecord_EXTDEF;
  1259. ExtDefElem: TOmfExternalNameElement;
  1260. OldCount,NewCount,i: Integer;
  1261. objsym: TObjSymbol;
  1262. symname: TSymStr;
  1263. begin
  1264. Result:=False;
  1265. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1266. ExtDefRec.ExternalNames:=ExtDefs;
  1267. OldCount:=ExtDefs.Count;
  1268. ExtDefRec.DecodeFrom(RawRec);
  1269. NewCount:=ExtDefs.Count;
  1270. for i:=OldCount to NewCount-1 do
  1271. begin
  1272. ExtDefElem:=TOmfExternalNameElement(ExtDefs[i]);
  1273. symname:=ExtDefElem.Name;
  1274. if not CaseSensitiveSymbols then
  1275. symname:=UpCase(symname);
  1276. objsym:=objdata.CreateSymbol(symname);
  1277. objsym.bind:=AB_EXTERNAL;
  1278. objsym.typ:=AT_FUNCTION;
  1279. objsym.objsection:=nil;
  1280. objsym.offset:=0;
  1281. objsym.size:=0;
  1282. end;
  1283. ExtDefRec.Free;
  1284. Result:=True;
  1285. end;
  1286. function TOmfObjInput.ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1287. var
  1288. PubDefRec: TOmfRecord_PUBDEF;
  1289. PubDefElem: TOmfPublicNameElement;
  1290. OldCount,NewCount,i: Integer;
  1291. basegroup: TObjSectionGroup;
  1292. objsym: TObjSymbol;
  1293. objsec: TOmfObjSection;
  1294. symname: TSymStr;
  1295. begin
  1296. Result:=False;
  1297. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1298. PubDefRec.PublicNames:=PubDefs;
  1299. OldCount:=PubDefs.Count;
  1300. PubDefRec.DecodeFrom(RawRec);
  1301. NewCount:=PubDefs.Count;
  1302. if (PubDefRec.BaseGroupIndex<0) or (PubDefRec.BaseGroupIndex>objdata.GroupsList.Count) then
  1303. begin
  1304. InputError('Public symbol''s group name index out of range');
  1305. PubDefRec.Free;
  1306. exit;
  1307. end;
  1308. if PubDefRec.BaseGroupIndex<>0 then
  1309. basegroup:=TObjSectionGroup(objdata.GroupsList[PubDefRec.BaseGroupIndex-1])
  1310. else
  1311. basegroup:=nil;
  1312. if (PubDefRec.BaseSegmentIndex<0) or (PubDefRec.BaseSegmentIndex>objdata.ObjSectionList.Count) then
  1313. begin
  1314. InputError('Public symbol''s segment name index out of range');
  1315. PubDefRec.Free;
  1316. exit;
  1317. end;
  1318. if PubDefRec.BaseSegmentIndex=0 then
  1319. begin
  1320. InputError('Public symbol uses absolute addressing, which is not supported by this linker');
  1321. PubDefRec.Free;
  1322. exit;
  1323. end;
  1324. objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
  1325. for i:=OldCount to NewCount-1 do
  1326. begin
  1327. PubDefElem:=TOmfPublicNameElement(PubDefs[i]);
  1328. symname:=PubDefElem.Name;
  1329. if not CaseSensitiveSymbols then
  1330. symname:=UpCase(symname);
  1331. objsym:=objdata.CreateSymbol(symname);
  1332. if PubDefElem.IsLocal then
  1333. objsym.bind:=AB_LOCAL
  1334. else
  1335. objsym.bind:=AB_GLOBAL;
  1336. objsym.typ:=AT_FUNCTION;
  1337. objsym.group:=basegroup;
  1338. objsym.objsection:=objsec;
  1339. objsym.offset:=PubDefElem.PublicOffset;
  1340. objsym.size:=0;
  1341. end;
  1342. PubDefRec.Free;
  1343. Result:=True;
  1344. end;
  1345. function TOmfObjInput.ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1346. var
  1347. ModEndRec: TOmfRecord_MODEND;
  1348. objsym: TObjSymbol;
  1349. objsec: TOmfObjSection;
  1350. basegroup: TObjSectionGroup;
  1351. begin
  1352. Result:=False;
  1353. ModEndRec:=TOmfRecord_MODEND.Create;
  1354. ModEndRec.DecodeFrom(RawRec);
  1355. if ModEndRec.HasStartAddress then
  1356. begin
  1357. if not ModEndRec.LogicalStartAddress then
  1358. begin
  1359. InputError('Physical start address not supported');
  1360. ModEndRec.Free;
  1361. exit;
  1362. end;
  1363. if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
  1364. begin
  1365. InputError('Target method for start address other than "Segment Index" is not supported');
  1366. ModEndRec.Free;
  1367. exit;
  1368. end;
  1369. if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
  1370. begin
  1371. InputError('Segment name index for start address out of range');
  1372. ModEndRec.Free;
  1373. exit;
  1374. end;
  1375. case ModEndRec.FrameMethod of
  1376. ffmSegmentIndex:
  1377. begin
  1378. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.ObjSectionList.Count) then
  1379. begin
  1380. InputError('Frame segment name index for start address out of range');
  1381. ModEndRec.Free;
  1382. exit;
  1383. end;
  1384. if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
  1385. begin
  1386. InputError('Frame segment different than target segment is not supported supported for start address');
  1387. ModEndRec.Free;
  1388. exit;
  1389. end;
  1390. basegroup:=nil;
  1391. end;
  1392. ffmGroupIndex:
  1393. begin
  1394. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.GroupsList.Count) then
  1395. begin
  1396. InputError('Frame group name index for start address out of range');
  1397. ModEndRec.Free;
  1398. exit;
  1399. end;
  1400. basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
  1401. end;
  1402. else
  1403. begin
  1404. InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
  1405. ModEndRec.Free;
  1406. exit;
  1407. end;
  1408. end;
  1409. objsec:=TOmfObjSection(objdata.ObjSectionList[ModEndRec.TargetDatum-1]);
  1410. objsym:=objdata.CreateSymbol('..start');
  1411. objsym.bind:=AB_GLOBAL;
  1412. objsym.typ:=AT_FUNCTION;
  1413. objsym.group:=basegroup;
  1414. objsym.objsection:=objsec;
  1415. objsym.offset:=ModEndRec.TargetDisplacement;
  1416. objsym.size:=0;
  1417. end;
  1418. ModEndRec.Free;
  1419. Result:=True;
  1420. end;
  1421. function TOmfObjInput.ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1422. var
  1423. Is32Bit: Boolean;
  1424. NextOfs: Integer;
  1425. SegmentIndex: Integer;
  1426. EnumeratedDataOffset: DWord;
  1427. BlockLength: Integer;
  1428. objsec: TOmfObjSection;
  1429. FixupRawRec: TOmfRawRecord=nil;
  1430. Fixup: TOmfSubRecord_FIXUP;
  1431. Thread: TOmfSubRecord_THREAD;
  1432. FixuppWithoutLeOrLiData: Boolean=False;
  1433. begin
  1434. Result:=False;
  1435. case RawRec.RecordType of
  1436. RT_LEDATA,RT_LEDATA32:
  1437. begin
  1438. Is32Bit:=RawRec.RecordType=RT_LEDATA32;
  1439. NextOfs:=RawRec.ReadIndexedRef(0,SegmentIndex);
  1440. if Is32Bit then
  1441. begin
  1442. if (NextOfs+3)>=RawRec.RecordLength then
  1443. internalerror(2015040504);
  1444. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1445. (RawRec.RawData[NextOfs+1] shl 8)+
  1446. (RawRec.RawData[NextOfs+2] shl 16)+
  1447. (RawRec.RawData[NextOfs+3] shl 24);
  1448. Inc(NextOfs,4);
  1449. end
  1450. else
  1451. begin
  1452. if (NextOfs+1)>=RawRec.RecordLength then
  1453. internalerror(2015040504);
  1454. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1455. (RawRec.RawData[NextOfs+1] shl 8);
  1456. Inc(NextOfs,2);
  1457. end;
  1458. BlockLength:=RawRec.RecordLength-NextOfs-1;
  1459. if BlockLength<0 then
  1460. internalerror(2015060501);
  1461. if BlockLength>1024 then
  1462. begin
  1463. InputError('LEDATA contains more than 1024 bytes of data');
  1464. exit;
  1465. end;
  1466. if (SegmentIndex<1) or (SegmentIndex>objdata.ObjSectionList.Count) then
  1467. begin
  1468. InputError('Segment index in LEDATA field is out of range');
  1469. exit;
  1470. end;
  1471. objsec:=TOmfObjSection(objdata.ObjSectionList[SegmentIndex-1]);
  1472. objsec.SecOptions:=objsec.SecOptions+[oso_Data];
  1473. if (objsec.Data.Size>EnumeratedDataOffset) then
  1474. begin
  1475. InputError('LEDATA enumerated data offset field out of sequence');
  1476. exit;
  1477. end;
  1478. if (EnumeratedDataOffset+BlockLength)>objsec.Size then
  1479. begin
  1480. InputError('LEDATA goes beyond the segment size declared in the SEGDEF record');
  1481. exit;
  1482. end;
  1483. objsec.Data.seek(EnumeratedDataOffset);
  1484. objsec.Data.write(RawRec.RawData[NextOfs],BlockLength);
  1485. end;
  1486. RT_LIDATA,RT_LIDATA32:
  1487. begin
  1488. InputError('LIDATA records are not supported');
  1489. exit;
  1490. end;
  1491. RT_FIXUPP,RT_FIXUPP32:
  1492. begin
  1493. FixuppWithoutLeOrLiData:=True;
  1494. { a hack, used to indicate, that we must process this record }
  1495. { (RawRec) first in the FIXUPP record processing loop that follows }
  1496. FixupRawRec:=RawRec;
  1497. end;
  1498. else
  1499. internalerror(2015040301);
  1500. end;
  1501. { also read all the FIXUPP records that may follow; }
  1502. { (FixupRawRec=RawRec) indicates that we must process RawRec first, but }
  1503. { without freeing it }
  1504. while (FixupRawRec=RawRec) or (PeekNextRecordType in [RT_FIXUPP,RT_FIXUPP32]) do
  1505. begin
  1506. if FixupRawRec<>RawRec then
  1507. begin
  1508. FixupRawRec:=TOmfRawRecord.Create;
  1509. FixupRawRec.ReadFrom(FReader);
  1510. if not FRawRecord.VerifyChecksumByte then
  1511. begin
  1512. InputError('Invalid checksum in OMF record');
  1513. FixupRawRec.Free;
  1514. exit;
  1515. end;
  1516. end;
  1517. NextOfs:=0;
  1518. Thread:=TOmfSubRecord_THREAD.Create;
  1519. Fixup:=TOmfSubRecord_FIXUP.Create;
  1520. Fixup.Is32Bit:=FixupRawRec.RecordType=RT_FIXUPP32;
  1521. Fixup.DataRecordStartOffset:=EnumeratedDataOffset;
  1522. while NextOfs<(FixupRawRec.RecordLength-1) do
  1523. begin
  1524. if (FixupRawRec.RawData[NextOfs] and $80)<>0 then
  1525. begin
  1526. { FIXUP subrecord }
  1527. if FixuppWithoutLeOrLiData then
  1528. begin
  1529. InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
  1530. Fixup.Free;
  1531. Thread.Free;
  1532. if FixupRawRec<>RawRec then
  1533. FixupRawRec.Free;
  1534. exit;
  1535. end;
  1536. NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
  1537. Fixup.ResolveByThread(FFixupThreads);
  1538. ImportOmfFixup(objdata,objsec,Fixup);
  1539. end
  1540. else
  1541. begin
  1542. { THREAD subrecord }
  1543. NextOfs:=Thread.ReadAt(FixupRawRec,NextOfs);
  1544. Thread.ApplyTo(FFixupThreads);
  1545. end;
  1546. end;
  1547. Fixup.Free;
  1548. Thread.Free;
  1549. if FixupRawRec<>RawRec then
  1550. FixupRawRec.Free;
  1551. { always set it to null, so that we read the next record on the next }
  1552. { loop iteration (this ensures that FixupRawRec<>RawRec, without }
  1553. { freeing RawRec) }
  1554. FixupRawRec:=nil;
  1555. end;
  1556. Result:=True;
  1557. end;
  1558. function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  1559. var
  1560. reloc: TOmfRelocation;
  1561. sym: TObjSymbol;
  1562. RelocType: TObjRelocationType;
  1563. target_section: TOmfObjSection;
  1564. target_group: TObjSectionGroup;
  1565. begin
  1566. Result:=False;
  1567. { range check location }
  1568. if (Fixup.LocationOffset+Fixup.LocationSize)>objsec.Size then
  1569. begin
  1570. InputError('Fixup location exceeds the current segment boundary');
  1571. exit;
  1572. end;
  1573. { range check target datum }
  1574. case Fixup.TargetMethod of
  1575. ftmSegmentIndex:
  1576. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  1577. begin
  1578. InputError('Segment name index in SI(<segment name>),<displacement> fixup target is out of range');
  1579. exit;
  1580. end;
  1581. ftmSegmentIndexNoDisp:
  1582. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  1583. begin
  1584. InputError('Segment name index in SI(<segment name>) fixup target is out of range');
  1585. exit;
  1586. end;
  1587. ftmGroupIndex:
  1588. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  1589. begin
  1590. InputError('Group name index in GI(<group name>),<displacement> fixup target is out of range');
  1591. exit;
  1592. end;
  1593. ftmGroupIndexNoDisp:
  1594. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  1595. begin
  1596. InputError('Group name index in GI(<group name>) fixup target is out of range');
  1597. exit;
  1598. end;
  1599. ftmExternalIndex:
  1600. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1601. begin
  1602. InputError('External symbol name index in EI(<symbol name>),<displacement> fixup target is out of range');
  1603. exit;
  1604. end;
  1605. ftmExternalIndexNoDisp:
  1606. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1607. begin
  1608. InputError('External symbol name index in EI(<symbol name>) fixup target is out of range');
  1609. exit;
  1610. end;
  1611. end;
  1612. { range check frame datum }
  1613. case Fixup.FrameMethod of
  1614. ffmSegmentIndex:
  1615. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.ObjSectionList.Count) then
  1616. begin
  1617. InputError('Segment name index in SI(<segment name>) fixup frame is out of range');
  1618. exit;
  1619. end;
  1620. ffmGroupIndex:
  1621. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.GroupsList.Count) then
  1622. begin
  1623. InputError('Group name index in GI(<group name>) fixup frame is out of range');
  1624. exit;
  1625. end;
  1626. ffmExternalIndex:
  1627. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1628. begin
  1629. InputError('External symbol name index in EI(<symbol name>) fixup frame is out of range');
  1630. exit;
  1631. end;
  1632. end;
  1633. if Fixup.TargetMethod in [ftmExternalIndex,ftmExternalIndexNoDisp] then
  1634. begin
  1635. sym:=objdata.symbolref(TOmfExternalNameElement(ExtDefs[Fixup.TargetDatum-1]).Name);
  1636. RelocType:=RELOC_NONE;
  1637. case Fixup.LocationType of
  1638. fltOffset:
  1639. case Fixup.Mode of
  1640. fmSegmentRelative:
  1641. RelocType:=RELOC_ABSOLUTE16;
  1642. fmSelfRelative:
  1643. RelocType:=RELOC_RELATIVE16;
  1644. end;
  1645. fltOffset32:
  1646. case Fixup.Mode of
  1647. fmSegmentRelative:
  1648. RelocType:=RELOC_ABSOLUTE32;
  1649. fmSelfRelative:
  1650. RelocType:=RELOC_RELATIVE32;
  1651. end;
  1652. fltBase:
  1653. case Fixup.Mode of
  1654. fmSegmentRelative:
  1655. RelocType:=RELOC_SEG;
  1656. fmSelfRelative:
  1657. RelocType:=RELOC_SEGREL;
  1658. end;
  1659. fltFarPointer:
  1660. case Fixup.Mode of
  1661. fmSegmentRelative:
  1662. RelocType:=RELOC_FARPTR;
  1663. fmSelfRelative:
  1664. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  1665. end;
  1666. fltFarPointer48:
  1667. case Fixup.Mode of
  1668. fmSegmentRelative:
  1669. RelocType:=RELOC_FARPTR48;
  1670. fmSelfRelative:
  1671. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  1672. end;
  1673. end;
  1674. if RelocType=RELOC_NONE then
  1675. begin
  1676. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode))+' in external reference to '+sym.Name);
  1677. exit;
  1678. end;
  1679. reloc:=TOmfRelocation.CreateSymbol(Fixup.LocationOffset,sym,RelocType);
  1680. objsec.ObjRelocations.Add(reloc);
  1681. case Fixup.FrameMethod of
  1682. ffmTarget:
  1683. {nothing};
  1684. ffmGroupIndex:
  1685. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  1686. else
  1687. begin
  1688. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in external reference to '+sym.Name);
  1689. exit;
  1690. end;
  1691. end;
  1692. if Fixup.TargetDisplacement<>0 then
  1693. begin
  1694. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in external reference to '+sym.Name);
  1695. exit;
  1696. end;
  1697. end
  1698. else if Fixup.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp] then
  1699. begin
  1700. target_section:=TOmfObjSection(objdata.ObjSectionList[Fixup.TargetDatum-1]);
  1701. RelocType:=RELOC_NONE;
  1702. case Fixup.LocationType of
  1703. fltOffset:
  1704. case Fixup.Mode of
  1705. fmSegmentRelative:
  1706. RelocType:=RELOC_ABSOLUTE16;
  1707. fmSelfRelative:
  1708. RelocType:=RELOC_RELATIVE16;
  1709. end;
  1710. fltOffset32:
  1711. case Fixup.Mode of
  1712. fmSegmentRelative:
  1713. RelocType:=RELOC_ABSOLUTE32;
  1714. fmSelfRelative:
  1715. RelocType:=RELOC_RELATIVE32;
  1716. end;
  1717. fltBase:
  1718. case Fixup.Mode of
  1719. fmSegmentRelative:
  1720. RelocType:=RELOC_SEG;
  1721. fmSelfRelative:
  1722. RelocType:=RELOC_SEGREL;
  1723. end;
  1724. fltFarPointer:
  1725. case Fixup.Mode of
  1726. fmSegmentRelative:
  1727. RelocType:=RELOC_FARPTR;
  1728. fmSelfRelative:
  1729. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  1730. end;
  1731. fltFarPointer48:
  1732. case Fixup.Mode of
  1733. fmSegmentRelative:
  1734. RelocType:=RELOC_FARPTR48;
  1735. fmSelfRelative:
  1736. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  1737. end;
  1738. end;
  1739. if RelocType=RELOC_NONE then
  1740. begin
  1741. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  1742. exit;
  1743. end;
  1744. reloc:=TOmfRelocation.CreateSection(Fixup.LocationOffset,target_section,RelocType);
  1745. objsec.ObjRelocations.Add(reloc);
  1746. case Fixup.FrameMethod of
  1747. ffmTarget:
  1748. {nothing};
  1749. ffmGroupIndex:
  1750. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  1751. else
  1752. begin
  1753. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to segment '+target_section.Name);
  1754. exit;
  1755. end;
  1756. end;
  1757. if Fixup.TargetDisplacement<>0 then
  1758. begin
  1759. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to segment '+target_section.Name);
  1760. exit;
  1761. end;
  1762. end
  1763. else if Fixup.TargetMethod in [ftmGroupIndex,ftmGroupIndexNoDisp] then
  1764. begin
  1765. target_group:=TObjSectionGroup(objdata.GroupsList[Fixup.TargetDatum-1]);
  1766. RelocType:=RELOC_NONE;
  1767. case Fixup.LocationType of
  1768. fltOffset:
  1769. case Fixup.Mode of
  1770. fmSegmentRelative:
  1771. RelocType:=RELOC_ABSOLUTE16;
  1772. fmSelfRelative:
  1773. RelocType:=RELOC_RELATIVE16;
  1774. end;
  1775. fltOffset32:
  1776. case Fixup.Mode of
  1777. fmSegmentRelative:
  1778. RelocType:=RELOC_ABSOLUTE32;
  1779. fmSelfRelative:
  1780. RelocType:=RELOC_RELATIVE32;
  1781. end;
  1782. fltBase:
  1783. case Fixup.Mode of
  1784. fmSegmentRelative:
  1785. RelocType:=RELOC_SEG;
  1786. fmSelfRelative:
  1787. RelocType:=RELOC_SEGREL;
  1788. end;
  1789. fltFarPointer:
  1790. case Fixup.Mode of
  1791. fmSegmentRelative:
  1792. RelocType:=RELOC_FARPTR;
  1793. fmSelfRelative:
  1794. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  1795. end;
  1796. fltFarPointer48:
  1797. case Fixup.Mode of
  1798. fmSegmentRelative:
  1799. RelocType:=RELOC_FARPTR48;
  1800. fmSelfRelative:
  1801. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  1802. end;
  1803. end;
  1804. if RelocType=RELOC_NONE then
  1805. begin
  1806. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  1807. exit;
  1808. end;
  1809. reloc:=TOmfRelocation.CreateGroup(Fixup.LocationOffset,target_group,RelocType);
  1810. objsec.ObjRelocations.Add(reloc);
  1811. case Fixup.FrameMethod of
  1812. ffmTarget:
  1813. {nothing};
  1814. else
  1815. begin
  1816. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to group '+target_group.Name);
  1817. exit;
  1818. end;
  1819. end;
  1820. if Fixup.TargetDisplacement<>0 then
  1821. begin
  1822. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to group '+target_group.Name);
  1823. exit;
  1824. end;
  1825. end
  1826. else
  1827. begin
  1828. {todo: convert other fixup types as well }
  1829. InputError('Unsupported fixup target method '+IntToStr(Ord(Fixup.TargetMethod)));
  1830. exit;
  1831. end;
  1832. Result:=True;
  1833. end;
  1834. constructor TOmfObjInput.create;
  1835. begin
  1836. inherited create;
  1837. cobjdata:=TOmfObjData;
  1838. FLNames:=TOmfOrderedNameCollection.Create(True);
  1839. FExtDefs:=TFPHashObjectList.Create;
  1840. FPubDefs:=TFPHashObjectList.Create;
  1841. FFixupThreads:=TOmfThreads.Create;
  1842. FRawRecord:=TOmfRawRecord.Create;
  1843. CaseSensitiveSegments:=False;
  1844. CaseSensitiveSymbols:=True;
  1845. end;
  1846. destructor TOmfObjInput.destroy;
  1847. begin
  1848. FCOMENTRecord.Free;
  1849. FRawRecord.Free;
  1850. FFixupThreads.Free;
  1851. FPubDefs.Free;
  1852. FExtDefs.Free;
  1853. FLNames.Free;
  1854. inherited destroy;
  1855. end;
  1856. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  1857. var
  1858. b: Byte;
  1859. begin
  1860. result:=false;
  1861. if AReader.Read(b,sizeof(b)) then
  1862. begin
  1863. if b=RT_THEADR then
  1864. { TODO: check additional fields }
  1865. result:=true;
  1866. end;
  1867. AReader.Seek(0);
  1868. end;
  1869. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  1870. begin
  1871. FReader:=AReader;
  1872. InputFileName:=AReader.FileName;
  1873. objdata:=CObjData.Create(InputFileName);
  1874. result:=false;
  1875. { the TOmfObjData constructor creates a group 'DGROUP', which is to be
  1876. used by the code generator, when writing files. When reading object
  1877. files, however, we need to start with an empty list of groups, so
  1878. let's clear the group list now. }
  1879. objdata.GroupsList.Clear;
  1880. LNames.Clear;
  1881. ExtDefs.Clear;
  1882. FRawRecord.ReadFrom(FReader);
  1883. if not FRawRecord.VerifyChecksumByte then
  1884. begin
  1885. InputError('Invalid checksum in OMF record');
  1886. exit;
  1887. end;
  1888. if FRawRecord.RecordType<>RT_THEADR then
  1889. begin
  1890. InputError('Can''t read OMF header');
  1891. exit;
  1892. end;
  1893. repeat
  1894. FRawRecord.ReadFrom(FReader);
  1895. if not FRawRecord.VerifyChecksumByte then
  1896. begin
  1897. InputError('Invalid checksum in OMF record');
  1898. exit;
  1899. end;
  1900. FreeAndNil(FCOMENTRecord);
  1901. case FRawRecord.RecordType of
  1902. RT_LNAMES:
  1903. if not ReadLNames(FRawRecord) then
  1904. exit;
  1905. RT_SEGDEF,RT_SEGDEF32:
  1906. if not ReadSegDef(FRawRecord,objdata) then
  1907. exit;
  1908. RT_GRPDEF:
  1909. if not ReadGrpDef(FRawRecord,objdata) then
  1910. exit;
  1911. RT_COMENT:
  1912. begin
  1913. FCOMENTRecord:=TOmfRecord_COMENT.Create;
  1914. FCOMENTRecord.DecodeFrom(FRawRecord);
  1915. case FCOMENTRecord.CommentClass of
  1916. CC_OmfExtension:
  1917. begin
  1918. {todo: handle these as well...}
  1919. end;
  1920. CC_LIBMOD:
  1921. begin
  1922. {todo: do we need to read the module name here?}
  1923. end;
  1924. CC_EXESTR:
  1925. begin
  1926. InputError('EXESTR record (Executable String Record) is not supported');
  1927. exit;
  1928. end;
  1929. CC_INCERR:
  1930. begin
  1931. InputError('Invalid object file (contains indication of error encountered during incremental compilation)');
  1932. exit;
  1933. end;
  1934. CC_NOPAD:
  1935. begin
  1936. InputError('NOPAD (No Segment Padding) record is not supported');
  1937. exit;
  1938. end;
  1939. CC_WKEXT:
  1940. begin
  1941. InputError('Weak externals are not supported');
  1942. exit;
  1943. end;
  1944. CC_LZEXT:
  1945. begin
  1946. InputError('Lazy externals are not supported');
  1947. exit;
  1948. end;
  1949. else
  1950. begin
  1951. {the rest are ignored for now...}
  1952. end;
  1953. end;
  1954. end;
  1955. RT_EXTDEF:
  1956. if not ReadExtDef(FRawRecord,objdata) then
  1957. exit;
  1958. RT_LPUBDEF,RT_LPUBDEF32,
  1959. RT_PUBDEF,RT_PUBDEF32:
  1960. if not ReadPubDef(FRawRecord,objdata) then
  1961. exit;
  1962. RT_LEDATA,RT_LEDATA32,
  1963. RT_LIDATA,RT_LIDATA32,
  1964. RT_FIXUPP,RT_FIXUPP32:
  1965. if not ReadLeOrLiDataAndFixups(FRawRecord,objdata) then
  1966. exit;
  1967. RT_MODEND,RT_MODEND32:
  1968. if not ReadModEnd(FRawRecord,objdata) then
  1969. exit;
  1970. RT_LINNUM,RT_LINNUM32:
  1971. ;
  1972. else
  1973. begin
  1974. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  1975. exit;
  1976. end;
  1977. end;
  1978. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  1979. result:=true;
  1980. end;
  1981. {****************************************************************************
  1982. TMZExeHeader
  1983. ****************************************************************************}
  1984. procedure TMZExeHeader.SetHeaderSizeAlignment(AValue: Integer);
  1985. begin
  1986. if (AValue<16) or ((AValue mod 16) <> 0) then
  1987. Internalerror(2015060601);
  1988. FHeaderSizeAlignment:=AValue;
  1989. end;
  1990. constructor TMZExeHeader.Create;
  1991. begin
  1992. FHeaderSizeAlignment:=16;
  1993. end;
  1994. procedure TMZExeHeader.WriteTo(aWriter: TObjectWriter);
  1995. var
  1996. NumRelocs: Word;
  1997. HeaderSizeInBytes: DWord;
  1998. HeaderParagraphs: Word;
  1999. RelocTableOffset: Word;
  2000. BytesInLastBlock: Word;
  2001. BlocksInFile: Word;
  2002. HeaderBytes: array [0..$1B] of Byte;
  2003. RelocBytes: array [0..3] of Byte;
  2004. TotalExeSize: DWord;
  2005. i: Integer;
  2006. begin
  2007. NumRelocs:=Length(Relocations);
  2008. RelocTableOffset:=$1C+Length(ExtraHeaderData);
  2009. HeaderSizeInBytes:=Align(RelocTableOffset+4*NumRelocs,16);
  2010. HeaderParagraphs:=HeaderSizeInBytes div 16;
  2011. TotalExeSize:=HeaderSizeInBytes+LoadableImageSize;
  2012. BlocksInFile:=(TotalExeSize+511) div 512;
  2013. BytesInLastBlock:=TotalExeSize mod 512;
  2014. HeaderBytes[$00]:=$4D; { 'M' }
  2015. HeaderBytes[$01]:=$5A; { 'Z' }
  2016. HeaderBytes[$02]:=Byte(BytesInLastBlock);
  2017. HeaderBytes[$03]:=Byte(BytesInLastBlock shr 8);
  2018. HeaderBytes[$04]:=Byte(BlocksInFile);
  2019. HeaderBytes[$05]:=Byte(BlocksInFile shr 8);
  2020. HeaderBytes[$06]:=Byte(NumRelocs);
  2021. HeaderBytes[$07]:=Byte(NumRelocs shr 8);
  2022. HeaderBytes[$08]:=Byte(HeaderParagraphs);
  2023. HeaderBytes[$09]:=Byte(HeaderParagraphs shr 8);
  2024. HeaderBytes[$0A]:=Byte(MinExtraParagraphs);
  2025. HeaderBytes[$0B]:=Byte(MinExtraParagraphs shr 8);
  2026. HeaderBytes[$0C]:=Byte(MaxExtraParagraphs);
  2027. HeaderBytes[$0D]:=Byte(MaxExtraParagraphs shr 8);
  2028. HeaderBytes[$0E]:=Byte(InitialSS);
  2029. HeaderBytes[$0F]:=Byte(InitialSS shr 8);
  2030. HeaderBytes[$10]:=Byte(InitialSP);
  2031. HeaderBytes[$11]:=Byte(InitialSP shr 8);
  2032. HeaderBytes[$12]:=Byte(Checksum);
  2033. HeaderBytes[$13]:=Byte(Checksum shr 8);
  2034. HeaderBytes[$14]:=Byte(InitialIP);
  2035. HeaderBytes[$15]:=Byte(InitialIP shr 8);
  2036. HeaderBytes[$16]:=Byte(InitialCS);
  2037. HeaderBytes[$17]:=Byte(InitialCS shr 8);
  2038. HeaderBytes[$18]:=Byte(RelocTableOffset);
  2039. HeaderBytes[$19]:=Byte(RelocTableOffset shr 8);
  2040. HeaderBytes[$1A]:=Byte(OverlayNumber);
  2041. HeaderBytes[$1B]:=Byte(OverlayNumber shr 8);
  2042. aWriter.write(HeaderBytes[0],$1C);
  2043. aWriter.write(ExtraHeaderData[0],Length(ExtraHeaderData));
  2044. for i:=0 to NumRelocs-1 do
  2045. with Relocations[i] do
  2046. begin
  2047. RelocBytes[0]:=Byte(offset);
  2048. RelocBytes[1]:=Byte(offset shr 8);
  2049. RelocBytes[2]:=Byte(segment);
  2050. RelocBytes[3]:=Byte(segment shr 8);
  2051. aWriter.write(RelocBytes[0],4);
  2052. end;
  2053. { pad with zeros until the end of header (paragraph aligned) }
  2054. aWriter.WriteZeros(HeaderSizeInBytes-aWriter.Size);
  2055. end;
  2056. procedure TMZExeHeader.AddRelocation(aSegment, aOffset: Word);
  2057. begin
  2058. SetLength(FRelocations,Length(FRelocations)+1);
  2059. with FRelocations[High(FRelocations)] do
  2060. begin
  2061. segment:=aSegment;
  2062. offset:=aOffset;
  2063. end;
  2064. end;
  2065. {****************************************************************************
  2066. TMZExeSection
  2067. ****************************************************************************}
  2068. procedure TMZExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  2069. begin
  2070. { allow mixing initialized and uninitialized data in the same section
  2071. => set ignoreprops=true }
  2072. inherited AddObjSection(objsec,true);
  2073. end;
  2074. {****************************************************************************
  2075. TMZExeUnifiedLogicalSegment
  2076. ****************************************************************************}
  2077. constructor TMZExeUnifiedLogicalSegment.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2078. var
  2079. Separator: SizeInt;
  2080. begin
  2081. inherited create(HashObjectList,s);
  2082. FObjSectionList:=TFPObjectList.Create(false);
  2083. { name format is 'SegName||ClassName' }
  2084. Separator:=Pos('||',s);
  2085. if Separator>0 then
  2086. begin
  2087. FSegName:=Copy(s,1,Separator-1);
  2088. FSegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  2089. end
  2090. else
  2091. begin
  2092. FSegName:=Name;
  2093. FSegClass:='';
  2094. end;
  2095. { wlink recognizes the stack segment by the class name 'STACK' }
  2096. { let's be compatible with wlink }
  2097. IsStack:=FSegClass='STACK';
  2098. end;
  2099. destructor TMZExeUnifiedLogicalSegment.destroy;
  2100. begin
  2101. FObjSectionList.Free;
  2102. inherited destroy;
  2103. end;
  2104. procedure TMZExeUnifiedLogicalSegment.AddObjSection(ObjSec: TOmfObjSection);
  2105. begin
  2106. ObjSectionList.Add(ObjSec);
  2107. ObjSec.MZExeUnifiedLogicalSegment:=self;
  2108. { tlink (and ms link?) use the scStack segment combination to recognize
  2109. the stack segment.
  2110. let's be compatible with tlink as well }
  2111. if ObjSec.Combination=scStack then
  2112. IsStack:=True;
  2113. end;
  2114. procedure TMZExeUnifiedLogicalSegment.CalcMemPos;
  2115. var
  2116. MinMemPos: qword=high(qword);
  2117. MaxMemPos: qword=0;
  2118. objsec: TOmfObjSection;
  2119. i: Integer;
  2120. begin
  2121. if ObjSectionList.Count=0 then
  2122. internalerror(2015082201);
  2123. for i:=0 to ObjSectionList.Count-1 do
  2124. begin
  2125. objsec:=TOmfObjSection(ObjSectionList[i]);
  2126. if objsec.MemPos<MinMemPos then
  2127. MinMemPos:=objsec.MemPos;
  2128. if (objsec.MemPos+objsec.Size)>MaxMemPos then
  2129. MaxMemPos:=objsec.MemPos+objsec.Size;
  2130. end;
  2131. MemPos:=MinMemPos;
  2132. Size:=MaxMemPos-MemPos;
  2133. end;
  2134. function TMZExeUnifiedLogicalSegment.MemPosStr: string;
  2135. begin
  2136. Result:=HexStr(MemBasePos shr 4,4)+':'+HexStr((MemPos-MemBasePos),4);
  2137. end;
  2138. {****************************************************************************
  2139. TMZExeUnifiedLogicalGroup
  2140. ****************************************************************************}
  2141. constructor TMZExeUnifiedLogicalGroup.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2142. begin
  2143. inherited create(HashObjectList,s);
  2144. FSegmentList:=TFPHashObjectList.Create(false);
  2145. end;
  2146. destructor TMZExeUnifiedLogicalGroup.destroy;
  2147. begin
  2148. FSegmentList.Free;
  2149. inherited destroy;
  2150. end;
  2151. procedure TMZExeUnifiedLogicalGroup.CalcMemPos;
  2152. var
  2153. MinMemPos: qword=high(qword);
  2154. MaxMemPos: qword=0;
  2155. UniSeg: TMZExeUnifiedLogicalSegment;
  2156. i: Integer;
  2157. begin
  2158. if SegmentList.Count=0 then
  2159. internalerror(2015082201);
  2160. for i:=0 to SegmentList.Count-1 do
  2161. begin
  2162. UniSeg:=TMZExeUnifiedLogicalSegment(SegmentList[i]);
  2163. if UniSeg.MemPos<MinMemPos then
  2164. MinMemPos:=UniSeg.MemPos;
  2165. if (UniSeg.MemPos+UniSeg.Size)>MaxMemPos then
  2166. MaxMemPos:=UniSeg.MemPos+UniSeg.Size;
  2167. end;
  2168. { align *down* on a paragraph boundary }
  2169. MemPos:=(MinMemPos shr 4) shl 4;
  2170. Size:=MaxMemPos-MemPos;
  2171. end;
  2172. function TMZExeUnifiedLogicalGroup.MemPosStr: string;
  2173. begin
  2174. Result:=HexStr(MemPos shr 4,4)+':'+HexStr(MemPos and $f,4);
  2175. end;
  2176. procedure TMZExeUnifiedLogicalGroup.AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  2177. begin
  2178. SegmentList.Add(UniSeg.Name,UniSeg);
  2179. if UniSeg.PrimaryGroup='' then
  2180. UniSeg.PrimaryGroup:=Name;
  2181. end;
  2182. {****************************************************************************
  2183. TMZExeOutput
  2184. ****************************************************************************}
  2185. function TMZExeOutput.GetMZFlatContentSection: TMZExeSection;
  2186. begin
  2187. if not assigned(FMZFlatContentSection) then
  2188. FMZFlatContentSection:=TMZExeSection(FindExeSection('.MZ_flat_content'));
  2189. result:=FMZFlatContentSection;
  2190. end;
  2191. procedure TMZExeOutput.CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  2192. var
  2193. ExeSec: TMZExeSection;
  2194. ObjSec: TOmfObjSection;
  2195. UniSeg: TMZExeUnifiedLogicalSegment;
  2196. i: Integer;
  2197. begin
  2198. ExeSec:=TMZExeSection(FindExeSection(SecName));
  2199. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2200. begin
  2201. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2202. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments.Find(ObjSec.Name));
  2203. if not assigned(UniSeg) then
  2204. begin
  2205. UniSeg:=TMZExeUnifiedLogicalSegment.Create(DwarfUnifiedLogicalSegments,ObjSec.Name);
  2206. UniSeg.MemPos:=0;
  2207. end;
  2208. UniSeg.AddObjSection(ObjSec);
  2209. end;
  2210. for i:=0 to DwarfUnifiedLogicalSegments.Count-1 do
  2211. begin
  2212. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments[i]);
  2213. UniSeg.CalcMemPos;
  2214. end;
  2215. end;
  2216. procedure TMZExeOutput.CalcExeUnifiedLogicalSegments;
  2217. var
  2218. ExeSec: TMZExeSection;
  2219. ObjSec: TOmfObjSection;
  2220. UniSeg: TMZExeUnifiedLogicalSegment;
  2221. i: Integer;
  2222. begin
  2223. ExeSec:=MZFlatContentSection;
  2224. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2225. begin
  2226. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2227. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments.Find(ObjSec.Name));
  2228. if not assigned(UniSeg) then
  2229. UniSeg:=TMZExeUnifiedLogicalSegment.Create(ExeUnifiedLogicalSegments,ObjSec.Name);
  2230. UniSeg.AddObjSection(ObjSec);
  2231. end;
  2232. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2233. begin
  2234. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2235. UniSeg.CalcMemPos;
  2236. if UniSeg.Size>$10000 then
  2237. begin
  2238. if current_settings.x86memorymodel=mm_tiny then
  2239. Message1(link_e_program_segment_too_large,IntToStr(UniSeg.Size-$10000))
  2240. else if UniSeg.SegClass='CODE' then
  2241. Message2(link_e_code_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2242. else if UniSeg.SegClass='DATA' then
  2243. Message2(link_e_data_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2244. else
  2245. Message2(link_e_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000)+' '+UniSeg.SegName);
  2246. end;
  2247. end;
  2248. end;
  2249. procedure TMZExeOutput.CalcExeGroups;
  2250. procedure AddToGroup(UniSeg:TMZExeUnifiedLogicalSegment;GroupName:TSymStr);
  2251. var
  2252. Group: TMZExeUnifiedLogicalGroup;
  2253. begin
  2254. Group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(GroupName));
  2255. if not assigned(Group) then
  2256. Group:=TMZExeUnifiedLogicalGroup.Create(ExeUnifiedLogicalGroups,GroupName);
  2257. Group.AddSegment(UniSeg);
  2258. end;
  2259. var
  2260. objdataidx,groupidx,secidx: Integer;
  2261. ObjData: TObjData;
  2262. ObjGroup: TObjSectionGroup;
  2263. ObjSec: TOmfObjSection;
  2264. UniGrp: TMZExeUnifiedLogicalGroup;
  2265. begin
  2266. for objdataidx:=0 to ObjDataList.Count-1 do
  2267. begin
  2268. ObjData:=TObjData(ObjDataList[objdataidx]);
  2269. if assigned(ObjData.GroupsList) then
  2270. for groupidx:=0 to ObjData.GroupsList.Count-1 do
  2271. begin
  2272. ObjGroup:=TObjSectionGroup(ObjData.GroupsList[groupidx]);
  2273. for secidx:=low(ObjGroup.members) to high(ObjGroup.members) do
  2274. begin
  2275. ObjSec:=TOmfObjSection(ObjGroup.members[secidx]);
  2276. if assigned(ObjSec.MZExeUnifiedLogicalSegment) then
  2277. AddToGroup(ObjSec.MZExeUnifiedLogicalSegment,ObjGroup.Name);
  2278. end;
  2279. end;
  2280. end;
  2281. for groupidx:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2282. begin
  2283. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[groupidx]);
  2284. UniGrp.CalcMemPos;
  2285. if UniGrp.Size>$10000 then
  2286. begin
  2287. if current_settings.x86memorymodel=mm_tiny then
  2288. Message1(link_e_program_segment_too_large,IntToStr(UniGrp.Size-$10000))
  2289. else if UniGrp.Name='DGROUP' then
  2290. Message2(link_e_data_segment_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000))
  2291. else
  2292. Message2(link_e_group_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000));
  2293. end;
  2294. end;
  2295. end;
  2296. procedure TMZExeOutput.CalcSegments_MemBasePos;
  2297. var
  2298. lastbase:qword=0;
  2299. i: Integer;
  2300. UniSeg: TMZExeUnifiedLogicalSegment;
  2301. begin
  2302. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2303. begin
  2304. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2305. if (UniSeg.PrimaryGroup<>'') or (UniSeg.IsStack) or
  2306. (((UniSeg.MemPos+UniSeg.Size-1)-lastbase)>$ffff) then
  2307. lastbase:=(UniSeg.MemPos shr 4) shl 4;
  2308. UniSeg.MemBasePos:=lastbase;
  2309. end;
  2310. end;
  2311. procedure TMZExeOutput.WriteMap_SegmentsAndGroups;
  2312. var
  2313. i, LongestGroupName, LongestSegmentName, LongestClassName: Integer;
  2314. UniSeg: TMZExeUnifiedLogicalSegment;
  2315. UniGrp: TMZExeUnifiedLogicalGroup;
  2316. GroupColumnSize, SegmentColumnSize, ClassColumnSize: LongInt;
  2317. begin
  2318. LongestGroupName:=0;
  2319. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2320. begin
  2321. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2322. LongestGroupName:=max(LongestGroupName,Length(UniGrp.Name));
  2323. end;
  2324. LongestSegmentName:=0;
  2325. LongestClassName:=0;
  2326. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2327. begin
  2328. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2329. LongestSegmentName:=max(LongestSegmentName,Length(UniSeg.SegName));
  2330. LongestClassName:=max(LongestClassName,Length(UniSeg.SegClass));
  2331. end;
  2332. GroupColumnSize:=max(32,LongestGroupName+1);
  2333. SegmentColumnSize:=max(23,LongestSegmentName+1);
  2334. ClassColumnSize:=max(15,LongestClassName+1);
  2335. exemap.AddHeader('Groups list');
  2336. exemap.Add('');
  2337. exemap.Add(PadSpace('Group',GroupColumnSize)+PadSpace('Address',21)+'Size');
  2338. exemap.Add(PadSpace('=====',GroupColumnSize)+PadSpace('=======',21)+'====');
  2339. exemap.Add('');
  2340. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2341. begin
  2342. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2343. exemap.Add(PadSpace(UniGrp.Name,GroupColumnSize)+PadSpace(UniGrp.MemPosStr,21)+HexStr(UniGrp.Size,8));
  2344. end;
  2345. exemap.Add('');
  2346. GroupColumnSize:=max(15,LongestGroupName+1);
  2347. exemap.AddHeader('Segments list');
  2348. exemap.Add('');
  2349. exemap.Add(PadSpace('Segment',SegmentColumnSize)+PadSpace('Class',ClassColumnSize)+PadSpace('Group',GroupColumnSize)+PadSpace('Address',16)+'Size');
  2350. exemap.Add(PadSpace('=======',SegmentColumnSize)+PadSpace('=====',ClassColumnSize)+PadSpace('=====',GroupColumnSize)+PadSpace('=======',16)+'====');
  2351. exemap.Add('');
  2352. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2353. begin
  2354. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2355. exemap.Add(PadSpace(UniSeg.SegName,SegmentColumnSize)+PadSpace(UniSeg.SegClass,ClassColumnSize)+PadSpace(UniSeg.PrimaryGroup,GroupColumnSize)+PadSpace(UniSeg.MemPosStr,16)+HexStr(UniSeg.Size,8));
  2356. end;
  2357. exemap.Add('');
  2358. end;
  2359. procedure TMZExeOutput.WriteMap_HeaderData;
  2360. begin
  2361. exemap.AddHeader('Header data');
  2362. exemap.Add('Loadable image size: '+HexStr(Header.LoadableImageSize,8));
  2363. exemap.Add('Min extra paragraphs: '+HexStr(Header.MinExtraParagraphs,4));
  2364. exemap.Add('Max extra paragraphs: '+HexStr(Header.MaxExtraParagraphs,4));
  2365. exemap.Add('Initial stack pointer: '+HexStr(Header.InitialSS,4)+':'+HexStr(Header.InitialSP,4));
  2366. exemap.Add('Entry point address: '+HexStr(Header.InitialCS,4)+':'+HexStr(Header.InitialIP,4));
  2367. end;
  2368. function TMZExeOutput.FindStackSegment: TMZExeUnifiedLogicalSegment;
  2369. var
  2370. i: Integer;
  2371. stackseg_wannabe: TMZExeUnifiedLogicalSegment;
  2372. begin
  2373. Result:=nil;
  2374. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2375. begin
  2376. stackseg_wannabe:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2377. { if there are multiple stack segments, choose the largest one.
  2378. In theory, we're probably supposed to combine them all and put
  2379. them in a contiguous location in memory, but we don't care }
  2380. if stackseg_wannabe.IsStack and
  2381. (not assigned(result) or (Result.Size<stackseg_wannabe.Size)) then
  2382. Result:=stackseg_wannabe;
  2383. end;
  2384. end;
  2385. procedure TMZExeOutput.FillLoadableImageSize;
  2386. var
  2387. i: Integer;
  2388. ExeSec: TMZExeSection;
  2389. ObjSec: TOmfObjSection;
  2390. StartDataPos: LongWord;
  2391. buf: array [0..1023] of byte;
  2392. bytesread: LongWord;
  2393. begin
  2394. Header.LoadableImageSize:=0;
  2395. ExeSec:=MZFlatContentSection;
  2396. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2397. begin
  2398. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2399. if (ObjSec.Size>0) and assigned(ObjSec.Data) then
  2400. if (ObjSec.MemPos+ObjSec.Size)>Header.LoadableImageSize then
  2401. Header.LoadableImageSize:=ObjSec.MemPos+ObjSec.Size;
  2402. end;
  2403. end;
  2404. procedure TMZExeOutput.FillMinExtraParagraphs;
  2405. var
  2406. ExeSec: TMZExeSection;
  2407. begin
  2408. ExeSec:=MZFlatContentSection;
  2409. Header.MinExtraParagraphs:=(align(ExeSec.Size,16)-align(Header.LoadableImageSize,16)) div 16;
  2410. end;
  2411. procedure TMZExeOutput.FillMaxExtraParagraphs;
  2412. var
  2413. heapmin_paragraphs: Integer;
  2414. heapmax_paragraphs: Integer;
  2415. begin
  2416. if current_settings.x86memorymodel in x86_far_data_models then
  2417. begin
  2418. { calculate the additional number of paragraphs needed }
  2419. heapmin_paragraphs:=(heapsize + 15) div 16;
  2420. heapmax_paragraphs:=(maxheapsize + 15) div 16;
  2421. Header.MaxExtraParagraphs:=min(Header.MinExtraParagraphs-heapmin_paragraphs+heapmax_paragraphs,$FFFF);
  2422. end
  2423. else
  2424. Header.MaxExtraParagraphs:=$FFFF;
  2425. end;
  2426. procedure TMZExeOutput.FillStartAddress;
  2427. var
  2428. EntryMemPos: qword;
  2429. EntryMemBasePos: qword;
  2430. begin
  2431. EntryMemPos:=EntrySym.address;
  2432. if assigned(EntrySym.group) then
  2433. EntryMemBasePos:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(EntrySym.group.Name)).MemPos
  2434. else
  2435. EntryMemBasePos:=TOmfObjSection(EntrySym.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2436. Header.InitialIP:=EntryMemPos-EntryMemBasePos;
  2437. Header.InitialCS:=EntryMemBasePos shr 4;
  2438. end;
  2439. procedure TMZExeOutput.FillStackAddress;
  2440. var
  2441. stackseg: TMZExeUnifiedLogicalSegment;
  2442. begin
  2443. stackseg:=FindStackSegment;
  2444. if assigned(stackseg) then
  2445. begin
  2446. Header.InitialSS:=stackseg.MemBasePos shr 4;
  2447. Header.InitialSP:=stackseg.MemPos+stackseg.Size-stackseg.MemBasePos;
  2448. end
  2449. else
  2450. begin
  2451. Header.InitialSS:=0;
  2452. Header.InitialSP:=0;
  2453. end;
  2454. end;
  2455. procedure TMZExeOutput.FillHeaderData;
  2456. begin
  2457. Header.MaxExtraParagraphs:=$FFFF;
  2458. FillLoadableImageSize;
  2459. FillMinExtraParagraphs;
  2460. FillMaxExtraParagraphs;
  2461. FillStartAddress;
  2462. FillStackAddress;
  2463. if assigned(exemap) then
  2464. WriteMap_HeaderData;
  2465. end;
  2466. function TMZExeOutput.writeExe: boolean;
  2467. var
  2468. ExeSec: TMZExeSection;
  2469. i: Integer;
  2470. ObjSec: TOmfObjSection;
  2471. begin
  2472. Result:=False;
  2473. FillHeaderData;
  2474. Header.WriteTo(FWriter);
  2475. ExeSec:=MZFlatContentSection;
  2476. ExeSec.DataPos:=FWriter.Size;
  2477. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2478. begin
  2479. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2480. if ObjSec.MemPos<Header.LoadableImageSize then
  2481. begin
  2482. FWriter.WriteZeros(max(0,ObjSec.MemPos-FWriter.Size+ExeSec.DataPos));
  2483. if assigned(ObjSec.Data) then
  2484. FWriter.writearray(ObjSec.Data);
  2485. end;
  2486. end;
  2487. Result:=True;
  2488. end;
  2489. function TMZExeOutput.writeCom: boolean;
  2490. const
  2491. ComFileOffset=$100;
  2492. var
  2493. i: Integer;
  2494. ExeSec: TMZExeSection;
  2495. ObjSec: TOmfObjSection;
  2496. StartDataPos: LongWord;
  2497. buf: array [0..1023] of byte;
  2498. bytesread: LongWord;
  2499. begin
  2500. FillHeaderData;
  2501. if Length(Header.Relocations)>0 then
  2502. begin
  2503. Message(link_e_com_program_uses_segment_relocations);
  2504. exit(False);
  2505. end;
  2506. ExeSec:=MZFlatContentSection;
  2507. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2508. begin
  2509. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2510. if ObjSec.MemPos<Header.LoadableImageSize then
  2511. begin
  2512. FWriter.WriteZeros(max(0,int64(ObjSec.MemPos)-ComFileOffset-int64(FWriter.Size)));
  2513. if assigned(ObjSec.Data) then
  2514. begin
  2515. if ObjSec.MemPos<ComFileOffset then
  2516. begin
  2517. ObjSec.Data.seek(ComFileOffset-ObjSec.MemPos);
  2518. repeat
  2519. bytesread:=ObjSec.Data.read(buf,sizeof(buf));
  2520. if bytesread<>0 then
  2521. FWriter.write(buf,bytesread);
  2522. until bytesread=0;
  2523. end
  2524. else
  2525. FWriter.writearray(ObjSec.Data);
  2526. end;
  2527. end;
  2528. end;
  2529. Result:=True;
  2530. end;
  2531. function TMZExeOutput.writeDebugElf: boolean;
  2532. label
  2533. cleanup;
  2534. var
  2535. debugsections: array of TMZExeSection;
  2536. debugsections_count: Word;
  2537. elfsections_count: Word;
  2538. elfsechdrs: array of TElf32sechdr;
  2539. shstrndx: Word;
  2540. next_section_ofs, elf_start_pos, elf_end_pos: LongWord;
  2541. ElfHeader: TElf32header;
  2542. shstrtabsect_data: TDynamicArray=Nil;
  2543. I, elfsecidx, J: Integer;
  2544. ObjSec: TOmfObjSection;
  2545. tis_trailer: TTISTrailer;
  2546. begin
  2547. debugsections:=nil;
  2548. elfsechdrs:=nil;
  2549. { mark the offset of the start of the ELF image }
  2550. elf_start_pos:=Writer.Size;
  2551. { count the debug sections }
  2552. debugsections_count:=0;
  2553. for I:=0 to ExeSectionList.Count-1 do
  2554. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  2555. Inc(debugsections_count);
  2556. { extract them into the debugsections array }
  2557. SetLength(debugsections,debugsections_count);
  2558. debugsections_count:=0;
  2559. for I:=0 to ExeSectionList.Count-1 do
  2560. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  2561. begin
  2562. debugsections[debugsections_count]:=TMZExeSection(ExeSectionList[I]);
  2563. Inc(debugsections_count);
  2564. end;
  2565. { prepare/allocate elf section headers }
  2566. elfsections_count:=debugsections_count+2;
  2567. SetLength(elfsechdrs,elfsections_count);
  2568. for I:=0 to elfsections_count-1 do
  2569. FillChar(elfsechdrs[I],SizeOf(elfsechdrs[I]),0);
  2570. shstrndx:=elfsections_count-1;
  2571. shstrtabsect_data:=tdynamicarray.Create(SectionDataMaxGrow);
  2572. shstrtabsect_data.writestr(#0);
  2573. next_section_ofs:=SizeOf(ElfHeader)+elfsections_count*SizeOf(TElf32sechdr);
  2574. for I:=0 to debugsections_count-1 do
  2575. begin
  2576. elfsecidx:=I+1;
  2577. with elfsechdrs[elfsecidx] do
  2578. begin
  2579. sh_name:=shstrtabsect_data.Pos;
  2580. sh_type:=SHT_PROGBITS;
  2581. sh_flags:=0;
  2582. sh_addr:=0;
  2583. sh_offset:=next_section_ofs;
  2584. sh_size:=debugsections[I].Size;
  2585. sh_link:=0;
  2586. sh_info:=0;
  2587. sh_addralign:=0;
  2588. sh_entsize:=0;
  2589. end;
  2590. Inc(next_section_ofs,debugsections[I].Size);
  2591. shstrtabsect_data.writestr(debugsections[I].Name+#0);
  2592. end;
  2593. with elfsechdrs[shstrndx] do
  2594. begin
  2595. sh_name:=shstrtabsect_data.Pos;
  2596. shstrtabsect_data.writestr('.shstrtab'#0);
  2597. sh_type:=SHT_STRTAB;
  2598. sh_flags:=0;
  2599. sh_addr:=0;
  2600. sh_offset:=next_section_ofs;
  2601. sh_size:=shstrtabsect_data.Size;
  2602. sh_link:=0;
  2603. sh_info:=0;
  2604. sh_addralign:=0;
  2605. sh_entsize:=0;
  2606. end;
  2607. { write header }
  2608. FillChar(ElfHeader,SizeOf(ElfHeader),0);
  2609. ElfHeader.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  2610. ElfHeader.e_ident[EI_MAG1]:=ELFMAG1;
  2611. ElfHeader.e_ident[EI_MAG2]:=ELFMAG2;
  2612. ElfHeader.e_ident[EI_MAG3]:=ELFMAG3;
  2613. ElfHeader.e_ident[EI_CLASS]:=ELFCLASS32;
  2614. ElfHeader.e_ident[EI_DATA]:=ELFDATA2LSB;
  2615. ElfHeader.e_ident[EI_VERSION]:=1;
  2616. ElfHeader.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  2617. ElfHeader.e_ident[EI_ABIVERSION]:=0;
  2618. ElfHeader.e_type:=ET_EXEC;
  2619. ElfHeader.e_machine:=EM_386;
  2620. ElfHeader.e_version:=1;
  2621. ElfHeader.e_entry:=0;
  2622. ElfHeader.e_phoff:=0;
  2623. ElfHeader.e_shoff:=SizeOf(ElfHeader);
  2624. ElfHeader.e_flags:=0;
  2625. ElfHeader.e_ehsize:=SizeOf(ElfHeader);
  2626. ElfHeader.e_phentsize:=SizeOf(TElf32proghdr);
  2627. ElfHeader.e_phnum:=0;
  2628. ElfHeader.e_shentsize:=SizeOf(TElf32sechdr);
  2629. ElfHeader.e_shnum:=elfsections_count;
  2630. ElfHeader.e_shstrndx:=shstrndx;
  2631. MaybeSwapHeader(ElfHeader);
  2632. Writer.write(ElfHeader,sizeof(ElfHeader));
  2633. { write section headers }
  2634. for I:=0 to elfsections_count-1 do
  2635. begin
  2636. MaybeSwapSecHeader(elfsechdrs[I]);
  2637. Writer.write(elfsechdrs[I],SizeOf(elfsechdrs[I]));
  2638. end;
  2639. { write section data }
  2640. for J:=0 to debugsections_count-1 do
  2641. begin
  2642. debugsections[J].DataPos:=Writer.Size;
  2643. for i:=0 to debugsections[J].ObjSectionList.Count-1 do
  2644. begin
  2645. ObjSec:=TOmfObjSection(debugsections[J].ObjSectionList[i]);
  2646. if assigned(ObjSec.Data) then
  2647. FWriter.writearray(ObjSec.Data);
  2648. end;
  2649. end;
  2650. { write .shstrtab section data }
  2651. Writer.writearray(shstrtabsect_data);
  2652. { mark the offset past the end of the ELF image }
  2653. elf_end_pos:=Writer.Size;
  2654. { write TIS trailer (not part of the ELF image) }
  2655. FillChar(tis_trailer,sizeof(tis_trailer),0);
  2656. with tis_trailer do
  2657. begin
  2658. tis_signature:=TIS_TRAILER_SIGNATURE;
  2659. tis_vendor:=TIS_TRAILER_VENDOR_TIS;
  2660. tis_type:=TIS_TRAILER_TYPE_TIS_DWARF;
  2661. tis_size:=(elf_end_pos-elf_start_pos)+sizeof(tis_trailer);
  2662. end;
  2663. MayBeSwapTISTrailer(tis_trailer);
  2664. Writer.write(tis_trailer,sizeof(tis_trailer));
  2665. Result:=True;
  2666. cleanup:
  2667. shstrtabsect_data.Free;
  2668. end;
  2669. procedure TMZExeOutput.Load_Symbol(const aname: string);
  2670. var
  2671. dgroup: TObjSectionGroup;
  2672. sym: TObjSymbol;
  2673. begin
  2674. { special handling for the '_edata' and '_end' symbols, which are
  2675. internally added by the linker }
  2676. if (aname='_edata') or (aname='_end') then
  2677. begin
  2678. { create an internal segment with the 'BSS' class }
  2679. internalObjData.createsection('*'+aname+'||BSS',0,[]);
  2680. { add to group 'DGROUP' }
  2681. dgroup:=nil;
  2682. if assigned(internalObjData.GroupsList) then
  2683. dgroup:=TObjSectionGroup(internalObjData.GroupsList.Find('DGROUP'));
  2684. if dgroup=nil then
  2685. dgroup:=internalObjData.createsectiongroup('DGROUP');
  2686. SetLength(dgroup.members,Length(dgroup.members)+1);
  2687. dgroup.members[Length(dgroup.members)-1]:=internalObjData.CurrObjSec;
  2688. { define the symbol itself }
  2689. sym:=internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  2690. sym.group:=dgroup;
  2691. end
  2692. else
  2693. inherited;
  2694. end;
  2695. procedure TMZExeOutput.DoRelocationFixup(objsec: TObjSection);
  2696. var
  2697. i: Integer;
  2698. omfsec: TOmfObjSection absolute objsec;
  2699. objreloc: TOmfRelocation;
  2700. target: DWord;
  2701. framebase: DWord;
  2702. fixupamount: Integer;
  2703. target_group: TMZExeUnifiedLogicalGroup;
  2704. procedure FixupOffset;
  2705. var
  2706. w: Word;
  2707. begin
  2708. omfsec.Data.seek(objreloc.DataOffset);
  2709. omfsec.Data.read(w,2);
  2710. w:=LEtoN(w);
  2711. Inc(w,fixupamount);
  2712. w:=LEtoN(w);
  2713. omfsec.Data.seek(objreloc.DataOffset);
  2714. omfsec.Data.write(w,2);
  2715. end;
  2716. procedure FixupOffset32;
  2717. var
  2718. lw: LongWord;
  2719. begin
  2720. omfsec.Data.seek(objreloc.DataOffset);
  2721. omfsec.Data.read(lw,4);
  2722. lw:=LEtoN(lw);
  2723. Inc(lw,fixupamount);
  2724. lw:=LEtoN(lw);
  2725. omfsec.Data.seek(objreloc.DataOffset);
  2726. omfsec.Data.write(lw,4);
  2727. end;
  2728. procedure FixupBase(DataOffset: LongWord);
  2729. var
  2730. w: Word;
  2731. begin
  2732. omfsec.Data.seek(DataOffset);
  2733. omfsec.Data.read(w,2);
  2734. w:=LEtoN(w);
  2735. Inc(w,framebase shr 4);
  2736. w:=LEtoN(w);
  2737. omfsec.Data.seek(DataOffset);
  2738. omfsec.Data.write(w,2);
  2739. Header.AddRelocation(omfsec.MZExeUnifiedLogicalSegment.MemBasePos shr 4,
  2740. omfsec.MemPos+DataOffset-omfsec.MZExeUnifiedLogicalSegment.MemBasePos);
  2741. end;
  2742. begin
  2743. for i:=0 to objsec.ObjRelocations.Count-1 do
  2744. begin
  2745. objreloc:=TOmfRelocation(objsec.ObjRelocations[i]);
  2746. if assigned(objreloc.symbol) then
  2747. begin
  2748. target:=objreloc.symbol.address;
  2749. if objreloc.FrameGroup<>'' then
  2750. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2751. else if assigned(objreloc.symbol.group) then
  2752. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.symbol.group.Name)).MemPos
  2753. else
  2754. framebase:=TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2755. case objreloc.typ of
  2756. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  2757. fixupamount:=target-framebase;
  2758. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  2759. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2760. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  2761. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  2762. else
  2763. internalerror(2015082402);
  2764. end;
  2765. case objreloc.typ of
  2766. RELOC_ABSOLUTE16,
  2767. RELOC_RELATIVE16:
  2768. FixupOffset;
  2769. RELOC_ABSOLUTE32,
  2770. RELOC_RELATIVE32:
  2771. FixupOffset32;
  2772. RELOC_SEG,
  2773. RELOC_SEGREL:
  2774. FixupBase(objreloc.DataOffset);
  2775. RELOC_FARPTR,
  2776. RELOC_FARPTR_RELATIVEOFFSET:
  2777. begin
  2778. FixupOffset;
  2779. FixupBase(objreloc.DataOffset+2);
  2780. end;
  2781. RELOC_FARPTR48,
  2782. RELOC_FARPTR48_RELATIVEOFFSET:
  2783. begin
  2784. FixupOffset32;
  2785. FixupBase(objreloc.DataOffset+4);
  2786. end;
  2787. else
  2788. internalerror(2015082403);
  2789. end;
  2790. end
  2791. else if assigned(objreloc.objsection) then
  2792. begin
  2793. target:=objreloc.objsection.MemPos;
  2794. if objreloc.FrameGroup<>'' then
  2795. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2796. else
  2797. begin
  2798. if assigned(TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment) then
  2799. framebase:=TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment.MemBasePos
  2800. else
  2801. begin
  2802. framebase:=0;
  2803. Comment(V_Warning,'Encountered an OMF reference to a section, that has been removed by smartlinking: '+TOmfObjSection(objreloc.objsection).Name);
  2804. end;
  2805. end;
  2806. case objreloc.typ of
  2807. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  2808. fixupamount:=target-framebase;
  2809. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  2810. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2811. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  2812. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  2813. else
  2814. internalerror(2015082405);
  2815. end;
  2816. case objreloc.typ of
  2817. RELOC_ABSOLUTE16,
  2818. RELOC_RELATIVE16:
  2819. FixupOffset;
  2820. RELOC_ABSOLUTE32,
  2821. RELOC_RELATIVE32:
  2822. FixupOffset32;
  2823. RELOC_SEG,
  2824. RELOC_SEGREL:
  2825. FixupBase(objreloc.DataOffset);
  2826. RELOC_FARPTR,
  2827. RELOC_FARPTR_RELATIVEOFFSET:
  2828. begin
  2829. FixupOffset;
  2830. FixupBase(objreloc.DataOffset+2);
  2831. end;
  2832. RELOC_FARPTR48,
  2833. RELOC_FARPTR48_RELATIVEOFFSET:
  2834. begin
  2835. FixupOffset32;
  2836. FixupBase(objreloc.DataOffset+4);
  2837. end;
  2838. else
  2839. internalerror(2015082406);
  2840. end;
  2841. end
  2842. else if assigned(objreloc.group) then
  2843. begin
  2844. target_group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.group.Name));
  2845. target:=target_group.MemPos;
  2846. if objreloc.FrameGroup<>'' then
  2847. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2848. else
  2849. framebase:=target_group.MemPos;
  2850. case objreloc.typ of
  2851. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  2852. fixupamount:=target-framebase;
  2853. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  2854. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2855. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  2856. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  2857. else
  2858. internalerror(2015111202);
  2859. end;
  2860. case objreloc.typ of
  2861. RELOC_ABSOLUTE16,
  2862. RELOC_RELATIVE16:
  2863. FixupOffset;
  2864. RELOC_ABSOLUTE32,
  2865. RELOC_RELATIVE32:
  2866. FixupOffset32;
  2867. RELOC_SEG,
  2868. RELOC_SEGREL:
  2869. FixupBase(objreloc.DataOffset);
  2870. RELOC_FARPTR,
  2871. RELOC_FARPTR_RELATIVEOFFSET:
  2872. begin
  2873. FixupOffset;
  2874. FixupBase(objreloc.DataOffset+2);
  2875. end;
  2876. RELOC_FARPTR48,
  2877. RELOC_FARPTR48_RELATIVEOFFSET:
  2878. begin
  2879. FixupOffset32;
  2880. FixupBase(objreloc.DataOffset+4);
  2881. end;
  2882. else
  2883. internalerror(2015111203);
  2884. end;
  2885. end
  2886. else
  2887. internalerror(2015082407);
  2888. end;
  2889. end;
  2890. function IOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  2891. var
  2892. I1 : TOmfObjSection absolute Item1;
  2893. I2 : TOmfObjSection absolute Item2;
  2894. begin
  2895. Result:=CompareStr(I1.ClassName,I2.ClassName);
  2896. if Result=0 then
  2897. Result:=CompareStr(I1.Name,I2.Name);
  2898. if Result=0 then
  2899. Result:=I1.SortOrder-I2.SortOrder;
  2900. end;
  2901. procedure TMZExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList; const aPattern: string);
  2902. var
  2903. i: Integer;
  2904. begin
  2905. for i:=0 to ObjSectionList.Count-1 do
  2906. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  2907. ObjSectionList.Sort(@IOmfObjSectionClassNameCompare);
  2908. end;
  2909. procedure TMZExeOutput.MemPos_ExeSection(const aname: string);
  2910. begin
  2911. { overlay all .exe sections on top of each other. In practice, the MZ
  2912. formats doesn't have sections, so really, everything goes to a single
  2913. section, called .MZ_flat_content. All the remaining sections, that we
  2914. use are the debug sections, which go to a separate ELF file, appended
  2915. after the end of the .exe. They live in a separate address space, with
  2916. each section starting at virtual offset 0. So, that's why we always
  2917. set CurrMemPos to 0 before each section here. }
  2918. CurrMemPos:=0;
  2919. inherited MemPos_ExeSection(aname);
  2920. end;
  2921. procedure TMZExeOutput.MemPos_EndExeSection;
  2922. var
  2923. SecName: TSymStr='';
  2924. begin
  2925. if assigned(CurrExeSec) then
  2926. SecName:=CurrExeSec.Name;
  2927. inherited MemPos_EndExeSection;
  2928. case SecName of
  2929. '.MZ_flat_content':
  2930. begin
  2931. CalcExeUnifiedLogicalSegments;
  2932. CalcExeGroups;
  2933. CalcSegments_MemBasePos;
  2934. if assigned(exemap) then
  2935. WriteMap_SegmentsAndGroups;
  2936. end;
  2937. '.debug_info',
  2938. '.debug_abbrev',
  2939. '.debug_line',
  2940. '.debug_aranges':
  2941. begin
  2942. CalcDwarfUnifiedLogicalSegmentsForSection(SecName);
  2943. with TMZExeSection(FindExeSection(SecName)) do
  2944. SecOptions:=SecOptions+[oso_debug];
  2945. end;
  2946. '':
  2947. {nothing to do};
  2948. else
  2949. internalerror(2018061401);
  2950. end;
  2951. end;
  2952. function TMZExeOutput.writeData: boolean;
  2953. begin
  2954. Result:=False;
  2955. if ExeWriteMode in [ewm_exefull,ewm_exeonly] then
  2956. begin
  2957. if apptype=app_com then
  2958. Result:=WriteCom
  2959. else
  2960. Result:=WriteExe;
  2961. if not Result then
  2962. exit;
  2963. end;
  2964. if ((cs_debuginfo in current_settings.moduleswitches) and
  2965. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) and
  2966. ((ExeWriteMode=ewm_dbgonly) or
  2967. ((ExeWriteMode=ewm_exefull) and
  2968. not(cs_link_strip in current_settings.globalswitches))) then
  2969. Result:=writeDebugElf;
  2970. end;
  2971. constructor TMZExeOutput.create;
  2972. begin
  2973. inherited create;
  2974. CExeSection:=TMZExeSection;
  2975. CObjData:=TOmfObjData;
  2976. CObjSymbol:=TOmfObjSymbol;
  2977. { "640K ought to be enough for anybody" :) }
  2978. MaxMemPos:=$9FFFF;
  2979. FExeUnifiedLogicalSegments:=TFPHashObjectList.Create;
  2980. FExeUnifiedLogicalGroups:=TFPHashObjectList.Create;
  2981. FDwarfUnifiedLogicalSegments:=TFPHashObjectList.Create;
  2982. FHeader:=TMZExeHeader.Create;
  2983. end;
  2984. destructor TMZExeOutput.destroy;
  2985. begin
  2986. FHeader.Free;
  2987. FDwarfUnifiedLogicalSegments.Free;
  2988. FExeUnifiedLogicalGroups.Free;
  2989. FExeUnifiedLogicalSegments.Free;
  2990. inherited destroy;
  2991. end;
  2992. {****************************************************************************
  2993. TOmfAssembler
  2994. ****************************************************************************}
  2995. constructor TOmfAssembler.Create(info: pasminfo; smart:boolean);
  2996. begin
  2997. inherited;
  2998. CObjOutput:=TOmfObjOutput;
  2999. CInternalAr:=TOmfLibObjectWriter;
  3000. end;
  3001. {*****************************************************************************
  3002. Initialize
  3003. *****************************************************************************}
  3004. {$ifdef i8086}
  3005. const
  3006. as_i8086_omf_info : tasminfo =
  3007. (
  3008. id : as_i8086_omf;
  3009. idtxt : 'OMF';
  3010. asmbin : '';
  3011. asmcmd : '';
  3012. supported_targets : [system_i8086_msdos,system_i8086_embedded];
  3013. flags : [af_outputbinary,af_smartlink_sections];
  3014. labelprefix : '..@';
  3015. comment : '; ';
  3016. dollarsign: '$';
  3017. );
  3018. {$endif i8086}
  3019. initialization
  3020. {$ifdef i8086}
  3021. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  3022. {$endif i8086}
  3023. end.