ogomf.pas 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577
  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. function GetGroupIndex(const groupname: string): Integer;
  46. public
  47. destructor Destroy; override;
  48. procedure BuildOmfFixup;
  49. property FrameGroup: string read FFrameGroup write FFrameGroup;
  50. property OmfFixup: TOmfSubRecord_FIXUP read FOmfFixup;
  51. end;
  52. TMZExeUnifiedLogicalSegment=class;
  53. { TOmfObjSection }
  54. TOmfObjSection = class(TObjSection)
  55. private
  56. FClassName: string;
  57. FOverlayName: string;
  58. FCombination: TOmfSegmentCombination;
  59. FUse: TOmfSegmentUse;
  60. FPrimaryGroup: string;
  61. FSortOrder: Integer;
  62. FMZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment;
  63. function GetOmfAlignment: TOmfSegmentAlignment;
  64. public
  65. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);override;
  66. function MemPosStr(AImageBase: qword): string;override;
  67. property ClassName: string read FClassName;
  68. property OverlayName: string read FOverlayName;
  69. property OmfAlignment: TOmfSegmentAlignment read GetOmfAlignment;
  70. property Combination: TOmfSegmentCombination read FCombination;
  71. property Use: TOmfSegmentUse read FUse;
  72. property PrimaryGroup: string read FPrimaryGroup;
  73. property SortOrder: Integer read FSortOrder write FSortOrder;
  74. property MZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment read FMZExeUnifiedLogicalSegment write FMZExeUnifiedLogicalSegment;
  75. end;
  76. { TOmfObjData }
  77. TOmfObjData = class(TObjData)
  78. private
  79. class function CodeSectionName(const aname:string): string;
  80. public
  81. constructor create(const n:string);override;
  82. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;override;
  83. function sectiontype2align(atype:TAsmSectiontype):shortint;override;
  84. function sectiontype2class(atype:TAsmSectiontype):string;
  85. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  86. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;override;
  87. function reffardatasection:TObjSection;
  88. procedure writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  89. end;
  90. { TOmfObjOutput }
  91. TOmfObjOutput = class(tObjOutput)
  92. private
  93. FLNames: TOmfOrderedNameCollection;
  94. FSegments: TFPHashObjectList;
  95. FGroups: TFPHashObjectList;
  96. procedure AddSegment(const name,segclass,ovlname: string;
  97. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  98. Use: TOmfSegmentUse; Size: aword);
  99. procedure AddGroup(const groupname: string; seglist: array of const);
  100. procedure AddGroup(const groupname: string; seglist: TSegmentList);
  101. procedure WriteSections(Data:TObjData);
  102. procedure WriteSectionContentAndFixups(sec: TObjSection);
  103. procedure section_count_sections(p:TObject;arg:pointer);
  104. procedure WritePUBDEFs(Data: TObjData);
  105. procedure WriteEXTDEFs(Data: TObjData);
  106. property LNames: TOmfOrderedNameCollection read FLNames;
  107. property Segments: TFPHashObjectList read FSegments;
  108. property Groups: TFPHashObjectList read FGroups;
  109. protected
  110. function writeData(Data:TObjData):boolean;override;
  111. public
  112. constructor create(AWriter:TObjectWriter);override;
  113. destructor Destroy;override;
  114. procedure WriteDllImport(const dllname,afuncname,mangledname:string;ordnr:longint;isvar:boolean);
  115. end;
  116. { TOmfObjInput }
  117. TOmfObjInput = class(TObjInput)
  118. private
  119. FLNames: TOmfOrderedNameCollection;
  120. FExtDefs: TFPHashObjectList;
  121. FPubDefs: TFPHashObjectList;
  122. FRawRecord: TOmfRawRecord;
  123. FCaseSensitive: Boolean;
  124. function PeekNextRecordType: Byte;
  125. function ReadLNames(RawRec: TOmfRawRecord): Boolean;
  126. function ReadSegDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  127. function ReadGrpDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  128. function ReadExtDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  129. function ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  130. function ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  131. function ReadLEDataAndFixups(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  132. function ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  133. property LNames: TOmfOrderedNameCollection read FLNames;
  134. property ExtDefs: TFPHashObjectList read FExtDefs;
  135. property PubDefs: TFPHashObjectList read FPubDefs;
  136. { Specifies whether we're case sensitive in regards to segment, class, overlay and group names.
  137. Symbols (in EXTDEF and PUBDEF records) are always case sensitive, regardless of the value of this property. }
  138. property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive;
  139. public
  140. constructor create;override;
  141. destructor destroy;override;
  142. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  143. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  144. end;
  145. { TMZExeRelocation }
  146. TMZExeRelocation = record
  147. offset: Word;
  148. segment: Word;
  149. end;
  150. TMZExeRelocations = array of TMZExeRelocation;
  151. TMZExeExtraHeaderData = array of Byte;
  152. { TMZExeHeader }
  153. TMZExeHeader = class
  154. private
  155. FChecksum: Word;
  156. FExtraHeaderData: TMZExeExtraHeaderData;
  157. FHeaderSizeAlignment: Integer;
  158. FInitialCS: Word;
  159. FInitialIP: Word;
  160. FInitialSP: Word;
  161. FInitialSS: Word;
  162. FLoadableImageSize: DWord;
  163. FMaxExtraParagraphs: Word;
  164. FMinExtraParagraphs: Word;
  165. FOverlayNumber: Word;
  166. FRelocations: TMZExeRelocations;
  167. procedure SetHeaderSizeAlignment(AValue: Integer);
  168. public
  169. constructor Create;
  170. procedure WriteTo(aWriter: TObjectWriter);
  171. procedure AddRelocation(aSegment,aOffset: Word);
  172. property HeaderSizeAlignment: Integer read FHeaderSizeAlignment write SetHeaderSizeAlignment; {default=16, must be multiple of 16}
  173. property Relocations: TMZExeRelocations read FRelocations write FRelocations;
  174. property ExtraHeaderData: TMZExeExtraHeaderData read FExtraHeaderData write FExtraHeaderData;
  175. property LoadableImageSize: DWord read FLoadableImageSize write FLoadableImageSize;
  176. property MinExtraParagraphs: Word read FMinExtraParagraphs write FMinExtraParagraphs;
  177. property MaxExtraParagraphs: Word read FMaxExtraParagraphs write FMaxExtraParagraphs;
  178. property InitialSS: Word read FInitialSS write FInitialSS;
  179. property InitialSP: Word read FInitialSP write FInitialSP;
  180. property Checksum: Word read FChecksum write FChecksum;
  181. property InitialIP: Word read FInitialIP write FInitialIP;
  182. property InitialCS: Word read FInitialCS write FInitialCS;
  183. property OverlayNumber: Word read FOverlayNumber write FOverlayNumber;
  184. end;
  185. { TMZExeSection }
  186. TMZExeSection=class(TExeSection)
  187. public
  188. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  189. end;
  190. { TMZExeUnifiedLogicalSegment }
  191. TMZExeUnifiedLogicalSegment=class(TFPHashObject)
  192. private
  193. FObjSectionList: TFPObjectList;
  194. FSegName: TSymStr;
  195. FSegClass: TSymStr;
  196. FPrimaryGroup: string;
  197. public
  198. Size,
  199. MemPos,
  200. MemBasePos: qword;
  201. IsStack: Boolean;
  202. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  203. destructor destroy;override;
  204. procedure AddObjSection(ObjSec: TOmfObjSection);
  205. procedure CalcMemPos;
  206. function MemPosStr:string;
  207. property ObjSectionList: TFPObjectList read FObjSectionList;
  208. property SegName: TSymStr read FSegName;
  209. property SegClass: TSymStr read FSegClass;
  210. property PrimaryGroup: string read FPrimaryGroup write FPrimaryGroup;
  211. end;
  212. { TMZExeUnifiedLogicalGroup }
  213. TMZExeUnifiedLogicalGroup=class(TFPHashObject)
  214. private
  215. FSegmentList: TFPHashObjectList;
  216. public
  217. Size,
  218. MemPos: qword;
  219. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  220. destructor destroy;override;
  221. procedure CalcMemPos;
  222. function MemPosStr:string;
  223. procedure AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  224. property SegmentList: TFPHashObjectList read FSegmentList;
  225. end;
  226. { TMZExeOutput }
  227. TMZExeOutput = class(TExeOutput)
  228. private
  229. FMZFlatContentSection: TMZExeSection;
  230. FExeUnifiedLogicalSegments: TFPHashObjectList;
  231. FExeUnifiedLogicalGroups: TFPHashObjectList;
  232. FHeader: TMZExeHeader;
  233. function GetMZFlatContentSection: TMZExeSection;
  234. procedure CalcExeUnifiedLogicalSegments;
  235. procedure CalcExeGroups;
  236. procedure CalcSegments_MemBasePos;
  237. procedure WriteMap_SegmentsAndGroups;
  238. procedure WriteMap_HeaderData;
  239. function FindStackSegment: TMZExeUnifiedLogicalSegment;
  240. procedure FillLoadableImageSize;
  241. procedure FillMinExtraParagraphs;
  242. procedure FillMaxExtraParagraphs;
  243. procedure FillStartAddress;
  244. procedure FillStackAddress;
  245. procedure FillHeaderData;
  246. function writeExe:boolean;
  247. function writeCom:boolean;
  248. property ExeUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  249. property ExeUnifiedLogicalGroups: TFPHashObjectList read FExeUnifiedLogicalGroups;
  250. property Header: TMZExeHeader read FHeader;
  251. protected
  252. procedure Load_Symbol(const aname:string);override;
  253. procedure DoRelocationFixup(objsec:TObjSection);override;
  254. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  255. procedure MemPos_EndExeSection;override;
  256. function writeData:boolean;override;
  257. public
  258. constructor create;override;
  259. destructor destroy;override;
  260. property MZFlatContentSection: TMZExeSection read GetMZFlatContentSection;
  261. end;
  262. TOmfAssembler = class(tinternalassembler)
  263. constructor create(info: pasminfo; smart:boolean);override;
  264. end;
  265. implementation
  266. uses
  267. SysUtils,
  268. cutils,verbose,globals,
  269. fmodule,aasmtai,aasmdata,
  270. ogmap,owomflib,
  271. version
  272. ;
  273. {****************************************************************************
  274. TOmfObjSymbol
  275. ****************************************************************************}
  276. function TOmfObjSymbol.AddressStr(AImageBase: qword): string;
  277. var
  278. base: qword;
  279. begin
  280. if assigned(TOmfObjSection(objsection).MZExeUnifiedLogicalSegment) then
  281. base:=TOmfObjSection(objsection).MZExeUnifiedLogicalSegment.MemBasePos
  282. else
  283. base:=(address shr 4) shl 4;
  284. Result:=HexStr(base shr 4,4)+':'+HexStr(address-base,4);
  285. end;
  286. {****************************************************************************
  287. TOmfRelocation
  288. ****************************************************************************}
  289. function TOmfRelocation.GetGroupIndex(const groupname: string): Integer;
  290. begin
  291. if groupname='DGROUP' then
  292. Result:=1
  293. else
  294. internalerror(2014040703);
  295. end;
  296. destructor TOmfRelocation.Destroy;
  297. begin
  298. FOmfFixup.Free;
  299. inherited Destroy;
  300. end;
  301. procedure TOmfRelocation.BuildOmfFixup;
  302. begin
  303. FreeAndNil(FOmfFixup);
  304. FOmfFixup:=TOmfSubRecord_FIXUP.Create;
  305. if ObjSection<>nil then
  306. begin
  307. FOmfFixup.LocationOffset:=DataOffset;
  308. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  309. FOmfFixup.LocationType:=fltOffset
  310. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  311. FOmfFixup.LocationType:=fltBase
  312. else
  313. internalerror(2015041501);
  314. FOmfFixup.FrameDeterminedByThread:=False;
  315. FOmfFixup.TargetDeterminedByThread:=False;
  316. if typ in [RELOC_ABSOLUTE,RELOC_SEG] then
  317. FOmfFixup.Mode:=fmSegmentRelative
  318. else if typ in [RELOC_RELATIVE,RELOC_SEGREL] then
  319. FOmfFixup.Mode:=fmSelfRelative
  320. else
  321. internalerror(2015041401);
  322. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  323. begin
  324. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  325. FOmfFixup.TargetDatum:=ObjSection.Index;
  326. if TOmfObjSection(ObjSection).PrimaryGroup<>'' then
  327. begin
  328. FOmfFixup.FrameMethod:=ffmGroupIndex;
  329. FOmfFixup.FrameDatum:=GetGroupIndex(TOmfObjSection(ObjSection).PrimaryGroup);
  330. end
  331. else
  332. FOmfFixup.FrameMethod:=ffmTarget;
  333. end
  334. else
  335. begin
  336. FOmfFixup.FrameMethod:=ffmTarget;
  337. if TOmfObjSection(ObjSection).PrimaryGroup<>'' then
  338. begin
  339. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  340. FOmfFixup.TargetDatum:=GetGroupIndex(TOmfObjSection(ObjSection).PrimaryGroup);
  341. end
  342. else
  343. begin
  344. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  345. FOmfFixup.TargetDatum:=ObjSection.Index;
  346. end;
  347. end;
  348. end
  349. else if symbol<>nil then
  350. begin
  351. FOmfFixup.LocationOffset:=DataOffset;
  352. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  353. FOmfFixup.LocationType:=fltOffset
  354. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  355. FOmfFixup.LocationType:=fltBase
  356. else
  357. internalerror(2015041501);
  358. FOmfFixup.FrameDeterminedByThread:=False;
  359. FOmfFixup.TargetDeterminedByThread:=False;
  360. if typ in [RELOC_ABSOLUTE,RELOC_SEG] then
  361. FOmfFixup.Mode:=fmSegmentRelative
  362. else if typ in [RELOC_RELATIVE,RELOC_SEGREL] then
  363. FOmfFixup.Mode:=fmSelfRelative
  364. else
  365. internalerror(2015041401);
  366. FOmfFixup.TargetMethod:=ftmExternalIndexNoDisp;
  367. FOmfFixup.TargetDatum:=symbol.symidx;
  368. FOmfFixup.FrameMethod:=ffmTarget;
  369. end
  370. else if group<>nil then
  371. begin
  372. FOmfFixup.LocationOffset:=DataOffset;
  373. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  374. FOmfFixup.LocationType:=fltOffset
  375. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  376. FOmfFixup.LocationType:=fltBase
  377. else
  378. internalerror(2015041501);
  379. FOmfFixup.FrameDeterminedByThread:=False;
  380. FOmfFixup.TargetDeterminedByThread:=False;
  381. if typ in [RELOC_ABSOLUTE,RELOC_SEG] then
  382. FOmfFixup.Mode:=fmSegmentRelative
  383. else if typ in [RELOC_RELATIVE,RELOC_SEGREL] then
  384. FOmfFixup.Mode:=fmSelfRelative
  385. else
  386. internalerror(2015041401);
  387. FOmfFixup.FrameMethod:=ffmTarget;
  388. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  389. FOmfFixup.TargetDatum:=GetGroupIndex(group.Name);
  390. end
  391. else
  392. internalerror(2015040702);
  393. end;
  394. {****************************************************************************
  395. TOmfObjSection
  396. ****************************************************************************}
  397. function TOmfObjSection.GetOmfAlignment: TOmfSegmentAlignment;
  398. begin
  399. case SecAlign of
  400. 1:
  401. result:=saRelocatableByteAligned;
  402. 2:
  403. result:=saRelocatableWordAligned;
  404. 4:
  405. result:=saRelocatableDWordAligned;
  406. 16:
  407. result:=saRelocatableParaAligned;
  408. else
  409. internalerror(2015041504);
  410. end;
  411. end;
  412. constructor TOmfObjSection.create(AList: TFPHashObjectList;
  413. const Aname: string; Aalign: shortint; Aoptions: TObjSectionOptions);
  414. begin
  415. inherited create(AList, Aname, Aalign, Aoptions);
  416. FCombination:=scPublic;
  417. FUse:=suUse16;
  418. end;
  419. function TOmfObjSection.MemPosStr(AImageBase: qword): string;
  420. begin
  421. Result:=HexStr(MZExeUnifiedLogicalSegment.MemBasePos shr 4,4)+':'+
  422. HexStr(MemPos-MZExeUnifiedLogicalSegment.MemBasePos,4);
  423. end;
  424. {****************************************************************************
  425. TOmfObjData
  426. ****************************************************************************}
  427. class function TOmfObjData.CodeSectionName(const aname: string): string;
  428. begin
  429. {$ifdef i8086}
  430. if current_settings.x86memorymodel in x86_far_code_models then
  431. begin
  432. if cs_huge_code in current_settings.moduleswitches then
  433. result:=aname + '_TEXT'
  434. else
  435. result:=current_module.modulename^ + '_TEXT';
  436. end
  437. else
  438. {$endif}
  439. result:='_TEXT';
  440. end;
  441. constructor TOmfObjData.create(const n: string);
  442. begin
  443. inherited create(n);
  444. CObjSymbol:=TOmfObjSymbol;
  445. CObjSection:=TOmfObjSection;
  446. createsectiongroup('DGROUP');
  447. end;
  448. function TOmfObjData.sectiontype2options(atype: TAsmSectiontype): TObjSectionOptions;
  449. begin
  450. Result:=inherited sectiontype2options(atype);
  451. { in the huge memory model, BSS data is actually written in the regular
  452. FAR_DATA segment of the module }
  453. if sectiontype2class(atype)='FAR_DATA' then
  454. Result:=Result+[oso_data,oso_sparse_data];
  455. end;
  456. function TOmfObjData.sectiontype2align(atype: TAsmSectiontype): shortint;
  457. begin
  458. Result:=omf_sectiontype2align(atype);
  459. end;
  460. function TOmfObjData.sectiontype2class(atype: TAsmSectiontype): string;
  461. begin
  462. Result:=omf_segclass(atype);
  463. end;
  464. function TOmfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  465. begin
  466. if (atype=sec_user) then
  467. Result:=aname
  468. else if omf_secnames[atype]=omf_secnames[sec_code] then
  469. Result:=CodeSectionName(aname)
  470. else if omf_segclass(atype)='FAR_DATA' then
  471. Result:=current_module.modulename^ + '_DATA'
  472. else
  473. Result:=omf_secnames[atype];
  474. end;
  475. function TOmfObjData.createsection(atype: TAsmSectionType; const aname: string; aorder: TAsmSectionOrder): TObjSection;
  476. begin
  477. Result:=inherited createsection(atype, aname, aorder);
  478. TOmfObjSection(Result).FClassName:=sectiontype2class(atype);
  479. if atype=sec_stack then
  480. TOmfObjSection(Result).FCombination:=scStack
  481. else if atype in [sec_debug_frame,sec_debug_info,sec_debug_line,sec_debug_abbrev] then
  482. TOmfObjSection(Result).FUse:=suUse32;
  483. if section_belongs_to_dgroup(atype) then
  484. TOmfObjSection(Result).FPrimaryGroup:='DGROUP';
  485. end;
  486. function TOmfObjData.reffardatasection: TObjSection;
  487. var
  488. secname: string;
  489. begin
  490. secname:=current_module.modulename^ + '_DATA';
  491. result:=TObjSection(ObjSectionList.Find(secname));
  492. if not assigned(result) then
  493. begin
  494. result:=CObjSection.create(ObjSectionList,secname,2,[oso_Data,oso_load,oso_write]);
  495. result.ObjData:=self;
  496. TOmfObjSection(Result).FClassName:='FAR_DATA';
  497. end;
  498. end;
  499. procedure TOmfObjData.writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  500. var
  501. objreloc: TOmfRelocation;
  502. symaddr: AWord;
  503. begin
  504. { RELOC_FARPTR = RELOC_ABSOLUTE+RELOC_SEG }
  505. if Reloctype=RELOC_FARPTR then
  506. begin
  507. if len<>4 then
  508. internalerror(2015041502);
  509. writeReloc(Data,2,p,RELOC_ABSOLUTE);
  510. writeReloc(0,2,p,RELOC_SEG);
  511. exit;
  512. end;
  513. if CurrObjSec=nil then
  514. internalerror(200403072);
  515. objreloc:=nil;
  516. if Reloctype in [RELOC_FARDATASEG,RELOC_FARDATASEGREL] then
  517. begin
  518. if Reloctype=RELOC_FARDATASEG then
  519. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEG)
  520. else
  521. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEGREL);
  522. CurrObjSec.ObjRelocations.Add(objreloc);
  523. end
  524. else if assigned(p) then
  525. begin
  526. { real address of the symbol }
  527. symaddr:=p.address;
  528. if p.bind=AB_EXTERNAL then
  529. begin
  530. objreloc:=TOmfRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  531. CurrObjSec.ObjRelocations.Add(objreloc);
  532. end
  533. { relative relocations within the same section can be calculated directly,
  534. without the need to emit a relocation entry }
  535. else if (p.objsection=CurrObjSec) and
  536. (p.bind<>AB_COMMON) and
  537. (Reloctype=RELOC_RELATIVE) then
  538. begin
  539. data:=data+symaddr-len-CurrObjSec.Size;
  540. end
  541. else
  542. begin
  543. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,p.objsection,Reloctype);
  544. CurrObjSec.ObjRelocations.Add(objreloc);
  545. if not (Reloctype in [RELOC_SEG,RELOC_SEGREL]) then
  546. inc(data,symaddr);
  547. end;
  548. end
  549. else if Reloctype in [RELOC_DGROUP,RELOC_DGROUPREL] then
  550. begin
  551. if Reloctype=RELOC_DGROUP then
  552. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEG)
  553. else
  554. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEGREL);
  555. CurrObjSec.ObjRelocations.Add(objreloc);
  556. end;
  557. CurrObjSec.write(data,len);
  558. end;
  559. {****************************************************************************
  560. TOmfObjOutput
  561. ****************************************************************************}
  562. procedure TOmfObjOutput.AddSegment(const name, segclass, ovlname: string;
  563. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  564. Use: TOmfSegmentUse; Size: aword);
  565. var
  566. s: TOmfRecord_SEGDEF;
  567. begin
  568. s:=TOmfRecord_SEGDEF.Create;
  569. Segments.Add(name,s);
  570. s.SegmentNameIndex:=LNames.Add(name);
  571. s.ClassNameIndex:=LNames.Add(segclass);
  572. s.OverlayNameIndex:=LNames.Add(ovlname);
  573. s.Alignment:=Alignment;
  574. s.Combination:=Combination;
  575. s.Use:=Use;
  576. s.SegmentLength:=Size;
  577. end;
  578. procedure TOmfObjOutput.AddGroup(const groupname: string; seglist: array of const);
  579. var
  580. g: TOmfRecord_GRPDEF;
  581. I: Integer;
  582. SegListStr: TSegmentList;
  583. begin
  584. g:=TOmfRecord_GRPDEF.Create;
  585. Groups.Add(groupname,g);
  586. g.GroupNameIndex:=LNames.Add(groupname);
  587. SetLength(SegListStr,Length(seglist));
  588. for I:=0 to High(seglist) do
  589. begin
  590. case seglist[I].VType of
  591. vtString:
  592. SegListStr[I]:=Segments.FindIndexOf(seglist[I].VString^);
  593. vtAnsiString:
  594. SegListStr[I]:=Segments.FindIndexOf(AnsiString(seglist[I].VAnsiString));
  595. vtWideString:
  596. SegListStr[I]:=Segments.FindIndexOf(AnsiString(WideString(seglist[I].VWideString)));
  597. vtUnicodeString:
  598. SegListStr[I]:=Segments.FindIndexOf(AnsiString(UnicodeString(seglist[I].VUnicodeString)));
  599. else
  600. internalerror(2015040402);
  601. end;
  602. end;
  603. g.SegmentList:=SegListStr;
  604. end;
  605. procedure TOmfObjOutput.AddGroup(const groupname: string; seglist: TSegmentList);
  606. var
  607. g: TOmfRecord_GRPDEF;
  608. begin
  609. g:=TOmfRecord_GRPDEF.Create;
  610. Groups.Add(groupname,g);
  611. g.GroupNameIndex:=LNames.Add(groupname);
  612. g.SegmentList:=Copy(seglist);
  613. end;
  614. procedure TOmfObjOutput.WriteSections(Data: TObjData);
  615. var
  616. i:longint;
  617. sec:TObjSection;
  618. begin
  619. for i:=0 to Data.ObjSectionList.Count-1 do
  620. begin
  621. sec:=TObjSection(Data.ObjSectionList[i]);
  622. WriteSectionContentAndFixups(sec);
  623. end;
  624. end;
  625. procedure TOmfObjOutput.WriteSectionContentAndFixups(sec: TObjSection);
  626. const
  627. MaxChunkSize=$3fa;
  628. var
  629. RawRecord: TOmfRawRecord;
  630. ChunkStart,ChunkLen: DWord;
  631. ChunkFixupStart,ChunkFixupEnd: Integer;
  632. SegIndex: Integer;
  633. NextOfs: Integer;
  634. I: Integer;
  635. begin
  636. if (oso_data in sec.SecOptions) then
  637. begin
  638. if sec.Data=nil then
  639. internalerror(200403073);
  640. for I:=0 to sec.ObjRelocations.Count-1 do
  641. TOmfRelocation(sec.ObjRelocations[I]).BuildOmfFixup;
  642. SegIndex:=Segments.FindIndexOf(sec.Name);
  643. RawRecord:=TOmfRawRecord.Create;
  644. sec.data.seek(0);
  645. ChunkFixupStart:=0;
  646. ChunkFixupEnd:=-1;
  647. ChunkStart:=0;
  648. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  649. while ChunkLen>0 do
  650. begin
  651. { find last fixup in the chunk }
  652. while (ChunkFixupEnd<(sec.ObjRelocations.Count-1)) and
  653. (TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd+1]).DataOffset<(ChunkStart+ChunkLen)) do
  654. inc(ChunkFixupEnd);
  655. { check if last chunk is crossing the chunk boundary, and trim ChunkLen if necessary }
  656. if (ChunkFixupEnd>=ChunkFixupStart) and
  657. ((TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset+
  658. TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).OmfFixup.LocationSize)>(ChunkStart+ChunkLen)) then
  659. begin
  660. ChunkLen:=TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset-ChunkStart;
  661. Dec(ChunkFixupEnd);
  662. end;
  663. { write LEDATA record }
  664. RawRecord.RecordType:=RT_LEDATA;
  665. NextOfs:=RawRecord.WriteIndexedRef(0,SegIndex);
  666. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  667. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  668. Inc(NextOfs,2);
  669. sec.data.read(RawRecord.RawData[NextOfs], ChunkLen);
  670. Inc(NextOfs, ChunkLen);
  671. RawRecord.RecordLength:=NextOfs+1;
  672. RawRecord.CalculateChecksumByte;
  673. RawRecord.WriteTo(FWriter);
  674. { write FIXUPP record }
  675. if ChunkFixupEnd>=ChunkFixupStart then
  676. begin
  677. RawRecord.RecordType:=RT_FIXUPP;
  678. NextOfs:=0;
  679. for I:=ChunkFixupStart to ChunkFixupEnd do
  680. begin
  681. TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.DataRecordStartOffset:=ChunkStart;
  682. NextOfs:=TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.WriteAt(RawRecord,NextOfs);
  683. end;
  684. RawRecord.RecordLength:=NextOfs+1;
  685. RawRecord.CalculateChecksumByte;
  686. RawRecord.WriteTo(FWriter);
  687. end;
  688. { prepare next chunk }
  689. Inc(ChunkStart, ChunkLen);
  690. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  691. ChunkFixupStart:=ChunkFixupEnd+1;
  692. end;
  693. RawRecord.Free;
  694. end;
  695. end;
  696. procedure TOmfObjOutput.section_count_sections(p: TObject; arg: pointer);
  697. begin
  698. TOmfObjSection(p).index:=pinteger(arg)^;
  699. inc(pinteger(arg)^);
  700. end;
  701. procedure TOmfObjOutput.WritePUBDEFs(Data: TObjData);
  702. var
  703. PubNamesForSection: array of TFPHashObjectList;
  704. i: Integer;
  705. objsym: TObjSymbol;
  706. PublicNameElem: TOmfPublicNameElement;
  707. RawRecord: TOmfRawRecord;
  708. PubDefRec: TOmfRecord_PUBDEF;
  709. PrimaryGroupName: string;
  710. begin
  711. RawRecord:=TOmfRawRecord.Create;
  712. SetLength(PubNamesForSection,Data.ObjSectionList.Count);
  713. for i:=0 to Data.ObjSectionList.Count-1 do
  714. PubNamesForSection[i]:=TFPHashObjectList.Create;
  715. for i:=0 to Data.ObjSymbolList.Count-1 do
  716. begin
  717. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  718. if objsym.bind=AB_GLOBAL then
  719. begin
  720. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  721. PublicNameElem.PublicOffset:=objsym.offset;
  722. end;
  723. end;
  724. for i:=0 to Data.ObjSectionList.Count-1 do
  725. if PubNamesForSection[i].Count>0 then
  726. begin
  727. PubDefRec:=TOmfRecord_PUBDEF.Create;
  728. PubDefRec.BaseSegmentIndex:=i+1;
  729. PrimaryGroupName:=TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup;
  730. if PrimaryGroupName<>'' then
  731. PubDefRec.BaseGroupIndex:=Groups.FindIndexOf(PrimaryGroupName)
  732. else
  733. PubDefRec.BaseGroupIndex:=0;
  734. PubDefRec.PublicNames:=PubNamesForSection[i];
  735. while PubDefRec.NextIndex<PubDefRec.PublicNames.Count do
  736. begin
  737. PubDefRec.EncodeTo(RawRecord);
  738. RawRecord.WriteTo(FWriter);
  739. end;
  740. PubDefRec.Free;
  741. end;
  742. for i:=0 to Data.ObjSectionList.Count-1 do
  743. FreeAndNil(PubNamesForSection[i]);
  744. RawRecord.Free;
  745. end;
  746. procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
  747. var
  748. ExtNames: TFPHashObjectList;
  749. RawRecord: TOmfRawRecord;
  750. i,idx: Integer;
  751. objsym: TObjSymbol;
  752. ExternalNameElem: TOmfExternalNameElement;
  753. ExtDefRec: TOmfRecord_EXTDEF;
  754. begin
  755. ExtNames:=TFPHashObjectList.Create;
  756. RawRecord:=TOmfRawRecord.Create;
  757. idx:=1;
  758. for i:=0 to Data.ObjSymbolList.Count-1 do
  759. begin
  760. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  761. if objsym.bind=AB_EXTERNAL then
  762. begin
  763. ExternalNameElem:=TOmfExternalNameElement.Create(ExtNames,objsym.Name);
  764. objsym.symidx:=idx;
  765. Inc(idx);
  766. end;
  767. end;
  768. if ExtNames.Count>0 then
  769. begin
  770. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  771. ExtDefRec.ExternalNames:=ExtNames;
  772. while ExtDefRec.NextIndex<ExtDefRec.ExternalNames.Count do
  773. begin
  774. ExtDefRec.EncodeTo(RawRecord);
  775. RawRecord.WriteTo(FWriter);
  776. end;
  777. ExtDefRec.Free;
  778. end;
  779. ExtNames.Free;
  780. RawRecord.Free;
  781. end;
  782. function TOmfObjOutput.writeData(Data:TObjData):boolean;
  783. var
  784. RawRecord: TOmfRawRecord;
  785. Header: TOmfRecord_THEADR;
  786. Translator_COMENT: TOmfRecord_COMENT;
  787. LinkPassSeparator_COMENT: TOmfRecord_COMENT;
  788. LNamesRec: TOmfRecord_LNAMES;
  789. ModEnd: TOmfRecord_MODEND;
  790. I: Integer;
  791. SegDef: TOmfRecord_SEGDEF;
  792. GrpDef: TOmfRecord_GRPDEF;
  793. DGroupSegments: TSegmentList;
  794. nsections: Integer;
  795. begin
  796. { calc amount of sections we have and set their index, starting with 1 }
  797. nsections:=1;
  798. data.ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  799. { maximum amount of sections supported in the omf format is $7fff }
  800. if (nsections-1)>$7fff then
  801. internalerror(2015040701);
  802. { write header record }
  803. RawRecord:=TOmfRawRecord.Create;
  804. Header:=TOmfRecord_THEADR.Create;
  805. Header.ModuleName:=Data.Name;
  806. Header.EncodeTo(RawRecord);
  807. RawRecord.WriteTo(FWriter);
  808. Header.Free;
  809. { write translator COMENT header }
  810. Translator_COMENT:=TOmfRecord_COMENT.Create;
  811. Translator_COMENT.CommentClass:=CC_Translator;
  812. Translator_COMENT.CommentString:='FPC '+full_version_string+
  813. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  814. Translator_COMENT.EncodeTo(RawRecord);
  815. RawRecord.WriteTo(FWriter);
  816. Translator_COMENT.Free;
  817. LNames.Clear;
  818. LNames.Add(''); { insert an empty string, which has index 1 }
  819. FSegments.Clear;
  820. FSegments.Add('',nil);
  821. FGroups.Clear;
  822. FGroups.Add('',nil);
  823. for i:=0 to Data.ObjSectionList.Count-1 do
  824. with TOmfObjSection(Data.ObjSectionList[I]) do
  825. AddSegment(Name,ClassName,OverlayName,OmfAlignment,Combination,Use,Size);
  826. { create group "DGROUP" }
  827. SetLength(DGroupSegments,0);
  828. for i:=0 to Data.ObjSectionList.Count-1 do
  829. with TOmfObjSection(Data.ObjSectionList[I]) do
  830. if PrimaryGroup='DGROUP' then
  831. begin
  832. SetLength(DGroupSegments,Length(DGroupSegments)+1);
  833. DGroupSegments[High(DGroupSegments)]:=index;
  834. end;
  835. AddGroup('DGROUP',DGroupSegments);
  836. { write LNAMES record(s) }
  837. LNamesRec:=TOmfRecord_LNAMES.Create;
  838. LNamesRec.Names:=LNames;
  839. while LNamesRec.NextIndex<=LNames.Count do
  840. begin
  841. LNamesRec.EncodeTo(RawRecord);
  842. RawRecord.WriteTo(FWriter);
  843. end;
  844. LNamesRec.Free;
  845. { write SEGDEF record(s) }
  846. for I:=1 to Segments.Count-1 do
  847. begin
  848. SegDef:=TOmfRecord_SEGDEF(Segments[I]);
  849. SegDef.EncodeTo(RawRecord);
  850. RawRecord.WriteTo(FWriter);
  851. end;
  852. { write GRPDEF record(s) }
  853. for I:=1 to Groups.Count-1 do
  854. begin
  855. GrpDef:=TOmfRecord_GRPDEF(Groups[I]);
  856. GrpDef.EncodeTo(RawRecord);
  857. RawRecord.WriteTo(FWriter);
  858. end;
  859. { write PUBDEF record(s) }
  860. WritePUBDEFs(Data);
  861. { write EXTDEF record(s) }
  862. WriteEXTDEFs(Data);
  863. { write link pass separator }
  864. LinkPassSeparator_COMENT:=TOmfRecord_COMENT.Create;
  865. LinkPassSeparator_COMENT.CommentClass:=CC_LinkPassSeparator;
  866. LinkPassSeparator_COMENT.CommentString:=#1;
  867. LinkPassSeparator_COMENT.NoList:=True;
  868. LinkPassSeparator_COMENT.EncodeTo(RawRecord);
  869. RawRecord.WriteTo(FWriter);
  870. LinkPassSeparator_COMENT.Free;
  871. { write section content, interleaved with fixups }
  872. WriteSections(Data);
  873. { write MODEND record }
  874. ModEnd:=TOmfRecord_MODEND.Create;
  875. ModEnd.EncodeTo(RawRecord);
  876. RawRecord.WriteTo(FWriter);
  877. ModEnd.Free;
  878. RawRecord.Free;
  879. result:=true;
  880. end;
  881. constructor TOmfObjOutput.create(AWriter:TObjectWriter);
  882. begin
  883. inherited create(AWriter);
  884. cobjdata:=TOmfObjData;
  885. FLNames:=TOmfOrderedNameCollection.Create;
  886. FSegments:=TFPHashObjectList.Create;
  887. FSegments.Add('',nil);
  888. FGroups:=TFPHashObjectList.Create;
  889. FGroups.Add('',nil);
  890. end;
  891. destructor TOmfObjOutput.Destroy;
  892. begin
  893. FGroups.Free;
  894. FSegments.Free;
  895. FLNames.Free;
  896. inherited Destroy;
  897. end;
  898. procedure TOmfObjOutput.WriteDllImport(const dllname,afuncname,mangledname: string; ordnr: longint; isvar: boolean);
  899. var
  900. RawRecord: TOmfRawRecord;
  901. Header: TOmfRecord_THEADR;
  902. DllImport_COMENT: TOmfRecord_COMENT;
  903. ModEnd: TOmfRecord_MODEND;
  904. begin
  905. { write header record }
  906. RawRecord:=TOmfRawRecord.Create;
  907. Header:=TOmfRecord_THEADR.Create;
  908. Header.ModuleName:=mangledname;
  909. Header.EncodeTo(RawRecord);
  910. RawRecord.WriteTo(FWriter);
  911. Header.Free;
  912. { write IMPDEF record }
  913. DllImport_COMENT:=TOmfRecord_COMENT.Create;
  914. DllImport_COMENT.CommentClass:=CC_OmfExtension;
  915. if ordnr <= 0 then
  916. begin
  917. if afuncname=mangledname then
  918. DllImport_COMENT.CommentString:=#1#0+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+#0
  919. else
  920. DllImport_COMENT.CommentString:=#1#0+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+Chr(Length(afuncname))+afuncname;
  921. end
  922. else
  923. DllImport_COMENT.CommentString:=#1#1+Chr(Length(mangledname))+mangledname+Chr(Length(dllname))+dllname+Chr(ordnr and $ff)+Chr((ordnr shr 8) and $ff);
  924. DllImport_COMENT.EncodeTo(RawRecord);
  925. RawRecord.WriteTo(FWriter);
  926. DllImport_COMENT.Free;
  927. { write MODEND record }
  928. ModEnd:=TOmfRecord_MODEND.Create;
  929. ModEnd.EncodeTo(RawRecord);
  930. RawRecord.WriteTo(FWriter);
  931. ModEnd.Free;
  932. RawRecord.Free;
  933. end;
  934. {****************************************************************************
  935. TOmfObjInput
  936. ****************************************************************************}
  937. function TOmfObjInput.PeekNextRecordType: Byte;
  938. var
  939. OldPos: LongInt;
  940. begin
  941. OldPos:=FReader.Pos;
  942. if not FReader.read(Result, 1) then
  943. begin
  944. InputError('Unexpected end of file');
  945. Result:=0;
  946. exit;
  947. end;
  948. FReader.seek(OldPos);
  949. end;
  950. function TOmfObjInput.ReadLNames(RawRec: TOmfRawRecord): Boolean;
  951. var
  952. LNamesRec: TOmfRecord_LNAMES;
  953. begin
  954. Result:=False;
  955. LNamesRec:=TOmfRecord_LNAMES.Create;
  956. LNamesRec.Names:=LNames;
  957. LNamesRec.DecodeFrom(RawRec);
  958. LNamesRec.Free;
  959. Result:=True;
  960. end;
  961. function TOmfObjInput.ReadSegDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  962. var
  963. SegDefRec: TOmfRecord_SEGDEF;
  964. SegmentName,SegClassName,OverlayName: string;
  965. SecAlign: ShortInt;
  966. secoptions: TObjSectionOptions;
  967. objsec: TOmfObjSection;
  968. begin
  969. Result:=False;
  970. SegDefRec:=TOmfRecord_SEGDEF.Create;
  971. SegDefRec.DecodeFrom(RawRec);
  972. if (SegDefRec.SegmentNameIndex<1) or (SegDefRec.SegmentNameIndex>LNames.Count) then
  973. begin
  974. InputError('Segment name index out of range');
  975. SegDefRec.Free;
  976. exit;
  977. end;
  978. SegmentName:=LNames[SegDefRec.SegmentNameIndex];
  979. if (SegDefRec.ClassNameIndex<1) or (SegDefRec.ClassNameIndex>LNames.Count) then
  980. begin
  981. InputError('Segment class name index out of range');
  982. SegDefRec.Free;
  983. exit;
  984. end;
  985. SegClassName:=LNames[SegDefRec.ClassNameIndex];
  986. if (SegDefRec.OverlayNameIndex<1) or (SegDefRec.OverlayNameIndex>LNames.Count) then
  987. begin
  988. InputError('Segment overlay name index out of range');
  989. SegDefRec.Free;
  990. exit;
  991. end;
  992. OverlayName:=LNames[SegDefRec.OverlayNameIndex];
  993. SecAlign:=1; // otherwise warning prohibits compilation
  994. case SegDefRec.Alignment of
  995. saRelocatableByteAligned:
  996. SecAlign:=1;
  997. saRelocatableWordAligned:
  998. SecAlign:=2;
  999. saRelocatableParaAligned:
  1000. SecAlign:=16;
  1001. saRelocatableDWordAligned:
  1002. SecAlign:=4;
  1003. saRelocatablePageAligned:
  1004. begin
  1005. InputError('Page segment alignment not supported');
  1006. SegDefRec.Free;
  1007. exit;
  1008. end;
  1009. saAbsolute:
  1010. begin
  1011. InputError('Absolute segment alignment not supported');
  1012. SegDefRec.Free;
  1013. exit;
  1014. end;
  1015. saNotSupported,
  1016. saNotDefined:
  1017. begin
  1018. InputError('Invalid (unsupported/undefined) OMF segment alignment');
  1019. SegDefRec.Free;
  1020. exit;
  1021. end;
  1022. end;
  1023. if not CaseSensitive then
  1024. begin
  1025. SegmentName:=UpCase(SegmentName);
  1026. SegClassName:=UpCase(SegClassName);
  1027. OverlayName:=UpCase(OverlayName);
  1028. end;
  1029. secoptions:=[];
  1030. objsec:=TOmfObjSection(objdata.createsection(SegmentName+'||'+SegClassName,SecAlign,secoptions,false));
  1031. objsec.FClassName:=SegClassName;
  1032. objsec.FOverlayName:=OverlayName;
  1033. objsec.FCombination:=SegDefRec.Combination;
  1034. objsec.FUse:=SegDefRec.Use;
  1035. if SegDefRec.SegmentLength>High(objsec.Size) then
  1036. begin
  1037. InputError('Segment too large');
  1038. SegDefRec.Free;
  1039. exit;
  1040. end;
  1041. objsec.Size:=SegDefRec.SegmentLength;
  1042. if (SegClassName='HEAP') or
  1043. (SegClassName='STACK') or (SegDefRec.Combination=scStack) or
  1044. (SegClassName='BEGDATA') or
  1045. (SegmentName='FPC') then
  1046. objsec.SecOptions:=objsec.SecOptions+[oso_keep];
  1047. SegDefRec.Free;
  1048. Result:=True;
  1049. end;
  1050. function TOmfObjInput.ReadGrpDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1051. var
  1052. GrpDefRec: TOmfRecord_GRPDEF;
  1053. GroupName: string;
  1054. SecGroup: TObjSectionGroup;
  1055. i,SegIndex: Integer;
  1056. begin
  1057. Result:=False;
  1058. GrpDefRec:=TOmfRecord_GRPDEF.Create;
  1059. GrpDefRec.DecodeFrom(RawRec);
  1060. if (GrpDefRec.GroupNameIndex<1) or (GrpDefRec.GroupNameIndex>LNames.Count) then
  1061. begin
  1062. InputError('Group name index out of range');
  1063. GrpDefRec.Free;
  1064. exit;
  1065. end;
  1066. GroupName:=LNames[GrpDefRec.GroupNameIndex];
  1067. if not CaseSensitive then
  1068. GroupName:=UpCase(GroupName);
  1069. SecGroup:=objdata.createsectiongroup(GroupName);
  1070. SetLength(SecGroup.members,Length(GrpDefRec.SegmentList));
  1071. for i:=0 to Length(GrpDefRec.SegmentList)-1 do
  1072. begin
  1073. SegIndex:=GrpDefRec.SegmentList[i];
  1074. if (SegIndex<1) or (SegIndex>objdata.ObjSectionList.Count) then
  1075. begin
  1076. InputError('Segment name index out of range in group definition');
  1077. GrpDefRec.Free;
  1078. exit;
  1079. end;
  1080. SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
  1081. end;
  1082. GrpDefRec.Free;
  1083. Result:=True;
  1084. end;
  1085. function TOmfObjInput.ReadExtDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1086. var
  1087. ExtDefRec: TOmfRecord_EXTDEF;
  1088. ExtDefElem: TOmfExternalNameElement;
  1089. OldCount,NewCount,i: Integer;
  1090. objsym: TObjSymbol;
  1091. begin
  1092. Result:=False;
  1093. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1094. ExtDefRec.ExternalNames:=ExtDefs;
  1095. OldCount:=ExtDefs.Count;
  1096. ExtDefRec.DecodeFrom(RawRec);
  1097. NewCount:=ExtDefs.Count;
  1098. for i:=OldCount to NewCount-1 do
  1099. begin
  1100. ExtDefElem:=TOmfExternalNameElement(ExtDefs[i]);
  1101. objsym:=objdata.CreateSymbol(ExtDefElem.Name);
  1102. objsym.bind:=AB_EXTERNAL;
  1103. objsym.typ:=AT_FUNCTION;
  1104. objsym.objsection:=nil;
  1105. objsym.offset:=0;
  1106. objsym.size:=0;
  1107. end;
  1108. ExtDefRec.Free;
  1109. Result:=True;
  1110. end;
  1111. function TOmfObjInput.ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1112. var
  1113. PubDefRec: TOmfRecord_PUBDEF;
  1114. PubDefElem: TOmfPublicNameElement;
  1115. OldCount,NewCount,i: Integer;
  1116. basegroup: TObjSectionGroup;
  1117. objsym: TObjSymbol;
  1118. objsec: TOmfObjSection;
  1119. begin
  1120. Result:=False;
  1121. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1122. PubDefRec.PublicNames:=PubDefs;
  1123. OldCount:=PubDefs.Count;
  1124. PubDefRec.DecodeFrom(RawRec);
  1125. NewCount:=PubDefs.Count;
  1126. if (PubDefRec.BaseGroupIndex<0) or (PubDefRec.BaseGroupIndex>objdata.GroupsList.Count) then
  1127. begin
  1128. InputError('Public symbol''s group name index out of range');
  1129. PubDefRec.Free;
  1130. exit;
  1131. end;
  1132. if PubDefRec.BaseGroupIndex<>0 then
  1133. basegroup:=TObjSectionGroup(objdata.GroupsList[PubDefRec.BaseGroupIndex-1])
  1134. else
  1135. basegroup:=nil;
  1136. if (PubDefRec.BaseSegmentIndex<0) or (PubDefRec.BaseSegmentIndex>objdata.ObjSectionList.Count) then
  1137. begin
  1138. InputError('Public symbol''s segment name index out of range');
  1139. PubDefRec.Free;
  1140. exit;
  1141. end;
  1142. if PubDefRec.BaseSegmentIndex=0 then
  1143. begin
  1144. InputError('Public symbol uses absolute addressing, which is not supported by this linker');
  1145. PubDefRec.Free;
  1146. exit;
  1147. end;
  1148. objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
  1149. for i:=OldCount to NewCount-1 do
  1150. begin
  1151. PubDefElem:=TOmfPublicNameElement(PubDefs[i]);
  1152. objsym:=objdata.CreateSymbol(PubDefElem.Name);
  1153. objsym.bind:=AB_GLOBAL;
  1154. objsym.typ:=AT_FUNCTION;
  1155. objsym.group:=basegroup;
  1156. objsym.objsection:=objsec;
  1157. objsym.offset:=PubDefElem.PublicOffset;
  1158. objsym.size:=0;
  1159. end;
  1160. PubDefRec.Free;
  1161. Result:=True;
  1162. end;
  1163. function TOmfObjInput.ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1164. var
  1165. ModEndRec: TOmfRecord_MODEND;
  1166. objsym: TObjSymbol;
  1167. objsec: TOmfObjSection;
  1168. basegroup: TObjSectionGroup;
  1169. begin
  1170. Result:=False;
  1171. ModEndRec:=TOmfRecord_MODEND.Create;
  1172. ModEndRec.DecodeFrom(RawRec);
  1173. if ModEndRec.HasStartAddress then
  1174. begin
  1175. if not ModEndRec.LogicalStartAddress then
  1176. begin
  1177. InputError('Physical start address not supported');
  1178. ModEndRec.Free;
  1179. exit;
  1180. end;
  1181. if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
  1182. begin
  1183. InputError('Target method for start address other than "Segment Index" is not supported');
  1184. ModEndRec.Free;
  1185. exit;
  1186. end;
  1187. if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
  1188. begin
  1189. InputError('Segment name index for start address out of range');
  1190. ModEndRec.Free;
  1191. exit;
  1192. end;
  1193. case ModEndRec.FrameMethod of
  1194. ffmSegmentIndex:
  1195. begin
  1196. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.ObjSectionList.Count) then
  1197. begin
  1198. InputError('Frame segment name index for start address out of range');
  1199. ModEndRec.Free;
  1200. exit;
  1201. end;
  1202. if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
  1203. begin
  1204. InputError('Frame segment different than target segment is not supported supported for start address');
  1205. ModEndRec.Free;
  1206. exit;
  1207. end;
  1208. basegroup:=nil;
  1209. end;
  1210. ffmGroupIndex:
  1211. begin
  1212. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.GroupsList.Count) then
  1213. begin
  1214. InputError('Frame group name index for start address out of range');
  1215. ModEndRec.Free;
  1216. exit;
  1217. end;
  1218. basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
  1219. end;
  1220. else
  1221. begin
  1222. InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
  1223. ModEndRec.Free;
  1224. exit;
  1225. end;
  1226. end;
  1227. objsec:=TOmfObjSection(objdata.ObjSectionList[ModEndRec.TargetDatum-1]);
  1228. objsym:=objdata.CreateSymbol('..start');
  1229. objsym.bind:=AB_GLOBAL;
  1230. objsym.typ:=AT_FUNCTION;
  1231. objsym.group:=basegroup;
  1232. objsym.objsection:=objsec;
  1233. objsym.offset:=ModEndRec.TargetDisplacement;
  1234. objsym.size:=0;
  1235. end;
  1236. ModEndRec.Free;
  1237. Result:=True;
  1238. end;
  1239. function TOmfObjInput.ReadLEDataAndFixups(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1240. var
  1241. Is32Bit: Boolean;
  1242. NextOfs: Integer;
  1243. SegmentIndex: Integer;
  1244. EnumeratedDataOffset: DWord;
  1245. BlockLength: Integer;
  1246. objsec: TOmfObjSection;
  1247. FixupRawRec: TOmfRawRecord;
  1248. Fixup: TOmfSubRecord_FIXUP;
  1249. begin
  1250. Result:=False;
  1251. if not (RawRec.RecordType in [RT_LEDATA,RT_LEDATA32]) then
  1252. internalerror(2015040301);
  1253. Is32Bit:=RawRec.RecordType=RT_LEDATA32;
  1254. NextOfs:=RawRec.ReadIndexedRef(0,SegmentIndex);
  1255. if Is32Bit then
  1256. begin
  1257. if (NextOfs+3)>=RawRec.RecordLength then
  1258. internalerror(2015040504);
  1259. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1260. (RawRec.RawData[NextOfs+1] shl 8)+
  1261. (RawRec.RawData[NextOfs+2] shl 16)+
  1262. (RawRec.RawData[NextOfs+3] shl 24);
  1263. Inc(NextOfs,4);
  1264. end
  1265. else
  1266. begin
  1267. if (NextOfs+1)>=RawRec.RecordLength then
  1268. internalerror(2015040504);
  1269. EnumeratedDataOffset := RawRec.RawData[NextOfs]+
  1270. (RawRec.RawData[NextOfs+1] shl 8);
  1271. Inc(NextOfs,2);
  1272. end;
  1273. BlockLength:=RawRec.RecordLength-NextOfs-1;
  1274. if BlockLength<0 then
  1275. internalerror(2015060501);
  1276. if BlockLength>1024 then
  1277. begin
  1278. InputError('LEDATA contains more than 1024 bytes of data');
  1279. exit;
  1280. end;
  1281. if (SegmentIndex<1) or (SegmentIndex>objdata.ObjSectionList.Count) then
  1282. begin
  1283. InputError('Segment index in LEDATA field is out of range');
  1284. exit;
  1285. end;
  1286. objsec:=TOmfObjSection(objdata.ObjSectionList[SegmentIndex-1]);
  1287. objsec.SecOptions:=objsec.SecOptions+[oso_Data];
  1288. if (objsec.Data.Size>EnumeratedDataOffset) then
  1289. begin
  1290. InputError('LEDATA enumerated data offset field out of sequence');
  1291. exit;
  1292. end;
  1293. if (EnumeratedDataOffset+BlockLength)>objsec.Size then
  1294. begin
  1295. InputError('LEDATA goes beyond the segment size declared in the SEGDEF record');
  1296. exit;
  1297. end;
  1298. objsec.Data.seek(EnumeratedDataOffset);
  1299. objsec.Data.write(RawRec.RawData[NextOfs],BlockLength);
  1300. { also read all the FIXUPP records that may follow }
  1301. while PeekNextRecordType in [RT_FIXUPP,RT_FIXUPP32] do
  1302. begin
  1303. FixupRawRec:=TOmfRawRecord.Create;
  1304. FixupRawRec.ReadFrom(FReader);
  1305. if not FRawRecord.VerifyChecksumByte then
  1306. begin
  1307. InputError('Invalid checksum in OMF record');
  1308. FixupRawRec.Free;
  1309. exit;
  1310. end;
  1311. NextOfs:=0;
  1312. Fixup:=TOmfSubRecord_FIXUP.Create;
  1313. Fixup.Is32Bit:=FixupRawRec.RecordType=RT_FIXUPP32;
  1314. Fixup.DataRecordStartOffset:=EnumeratedDataOffset;
  1315. while NextOfs<(FixupRawRec.RecordLength-1) do
  1316. begin
  1317. NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
  1318. if Fixup.FrameDeterminedByThread or Fixup.TargetDeterminedByThread then
  1319. begin
  1320. InputError('Fixups determined by thread not supported');
  1321. Fixup.Free;
  1322. FixupRawRec.Free;
  1323. exit;
  1324. end;
  1325. ImportOmfFixup(objdata,objsec,Fixup);
  1326. end;
  1327. Fixup.Free;
  1328. FixupRawRec.Free;
  1329. end;
  1330. Result:=True;
  1331. end;
  1332. function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  1333. var
  1334. reloc: TOmfRelocation;
  1335. sym: TObjSymbol;
  1336. RelocType: TObjRelocationType;
  1337. target_section: TOmfObjSection;
  1338. target_group: TObjSectionGroup;
  1339. begin
  1340. Result:=False;
  1341. { range check location }
  1342. if (Fixup.LocationOffset+Fixup.LocationSize)>objsec.Size then
  1343. begin
  1344. InputError('Fixup location exceeds the current segment boundary');
  1345. exit;
  1346. end;
  1347. { range check target datum }
  1348. case Fixup.TargetMethod of
  1349. ftmSegmentIndex:
  1350. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  1351. begin
  1352. InputError('Segment name index in SI(<segment name>),<displacement> fixup target is out of range');
  1353. exit;
  1354. end;
  1355. ftmSegmentIndexNoDisp:
  1356. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  1357. begin
  1358. InputError('Segment name index in SI(<segment name>) fixup target is out of range');
  1359. exit;
  1360. end;
  1361. ftmGroupIndex:
  1362. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  1363. begin
  1364. InputError('Group name index in GI(<group name>),<displacement> fixup target is out of range');
  1365. exit;
  1366. end;
  1367. ftmGroupIndexNoDisp:
  1368. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  1369. begin
  1370. InputError('Group name index in GI(<group name>) fixup target is out of range');
  1371. exit;
  1372. end;
  1373. ftmExternalIndex:
  1374. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1375. begin
  1376. InputError('External symbol name index in EI(<symbol name>),<displacement> fixup target is out of range');
  1377. exit;
  1378. end;
  1379. ftmExternalIndexNoDisp:
  1380. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1381. begin
  1382. InputError('External symbol name index in EI(<symbol name>) fixup target is out of range');
  1383. exit;
  1384. end;
  1385. end;
  1386. { range check frame datum }
  1387. case Fixup.FrameMethod of
  1388. ffmSegmentIndex:
  1389. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.ObjSectionList.Count) then
  1390. begin
  1391. InputError('Segment name index in SI(<segment name>) fixup frame is out of range');
  1392. exit;
  1393. end;
  1394. ffmGroupIndex:
  1395. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.GroupsList.Count) then
  1396. begin
  1397. InputError('Group name index in GI(<group name>) fixup frame is out of range');
  1398. exit;
  1399. end;
  1400. ffmExternalIndex:
  1401. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  1402. begin
  1403. InputError('External symbol name index in EI(<symbol name>) fixup frame is out of range');
  1404. exit;
  1405. end;
  1406. end;
  1407. if Fixup.TargetMethod in [ftmExternalIndex,ftmExternalIndexNoDisp] then
  1408. begin
  1409. sym:=objdata.symbolref(TOmfExternalNameElement(ExtDefs[Fixup.TargetDatum-1]).Name);
  1410. RelocType:=RELOC_NONE;
  1411. case Fixup.LocationType of
  1412. fltOffset:
  1413. case Fixup.Mode of
  1414. fmSegmentRelative:
  1415. RelocType:=RELOC_ABSOLUTE;
  1416. fmSelfRelative:
  1417. RelocType:=RELOC_RELATIVE;
  1418. end;
  1419. fltBase:
  1420. case Fixup.Mode of
  1421. fmSegmentRelative:
  1422. RelocType:=RELOC_SEG;
  1423. fmSelfRelative:
  1424. RelocType:=RELOC_SEGREL;
  1425. end;
  1426. end;
  1427. if RelocType=RELOC_NONE then
  1428. begin
  1429. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode))+' in external reference to '+sym.Name);
  1430. exit;
  1431. end;
  1432. reloc:=TOmfRelocation.CreateSymbol(Fixup.LocationOffset,sym,RelocType);
  1433. objsec.ObjRelocations.Add(reloc);
  1434. case Fixup.FrameMethod of
  1435. ffmTarget:
  1436. {nothing};
  1437. ffmGroupIndex:
  1438. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  1439. else
  1440. begin
  1441. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in external reference to '+sym.Name);
  1442. exit;
  1443. end;
  1444. end;
  1445. if Fixup.TargetDisplacement<>0 then
  1446. begin
  1447. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in external reference to '+sym.Name);
  1448. exit;
  1449. end;
  1450. end
  1451. else if Fixup.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp] then
  1452. begin
  1453. target_section:=TOmfObjSection(objdata.ObjSectionList[Fixup.TargetDatum-1]);
  1454. RelocType:=RELOC_NONE;
  1455. case Fixup.LocationType of
  1456. fltOffset:
  1457. case Fixup.Mode of
  1458. fmSegmentRelative:
  1459. RelocType:=RELOC_ABSOLUTE;
  1460. fmSelfRelative:
  1461. RelocType:=RELOC_RELATIVE;
  1462. end;
  1463. fltBase:
  1464. case Fixup.Mode of
  1465. fmSegmentRelative:
  1466. RelocType:=RELOC_SEG;
  1467. fmSelfRelative:
  1468. RelocType:=RELOC_SEGREL;
  1469. end;
  1470. end;
  1471. if RelocType=RELOC_NONE then
  1472. begin
  1473. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with location type '+tostr(ord(Fixup.LocationType))+' in reference to segment '+target_section.Name);
  1474. exit;
  1475. end;
  1476. reloc:=TOmfRelocation.CreateSection(Fixup.LocationOffset,target_section,RelocType);
  1477. objsec.ObjRelocations.Add(reloc);
  1478. case Fixup.FrameMethod of
  1479. ffmTarget:
  1480. {nothing};
  1481. ffmGroupIndex:
  1482. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  1483. else
  1484. begin
  1485. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to segment '+target_section.Name);
  1486. exit;
  1487. end;
  1488. end;
  1489. if Fixup.TargetDisplacement<>0 then
  1490. begin
  1491. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to segment '+target_section.Name);
  1492. exit;
  1493. end;
  1494. end
  1495. else if Fixup.TargetMethod in [ftmGroupIndex,ftmGroupIndexNoDisp] then
  1496. begin
  1497. target_group:=TObjSectionGroup(objdata.GroupsList[Fixup.TargetDatum-1]);
  1498. RelocType:=RELOC_NONE;
  1499. case Fixup.LocationType of
  1500. fltOffset:
  1501. case Fixup.Mode of
  1502. fmSegmentRelative:
  1503. RelocType:=RELOC_ABSOLUTE;
  1504. fmSelfRelative:
  1505. RelocType:=RELOC_RELATIVE;
  1506. end;
  1507. fltBase:
  1508. case Fixup.Mode of
  1509. fmSegmentRelative:
  1510. RelocType:=RELOC_SEG;
  1511. fmSelfRelative:
  1512. RelocType:=RELOC_SEGREL;
  1513. end;
  1514. end;
  1515. if RelocType=RELOC_NONE then
  1516. begin
  1517. InputError('Unsupported fixup location type '+IntToStr(Ord(Fixup.LocationType))+'with mode '+tostr(Ord(Fixup.Mode))+' in reference to group '+target_group.Name);
  1518. exit;
  1519. end;
  1520. reloc:=TOmfRelocation.CreateGroup(Fixup.LocationOffset,target_group,RelocType);
  1521. objsec.ObjRelocations.Add(reloc);
  1522. case Fixup.FrameMethod of
  1523. ffmTarget:
  1524. {nothing};
  1525. else
  1526. begin
  1527. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to group '+target_group.Name);
  1528. exit;
  1529. end;
  1530. end;
  1531. if Fixup.TargetDisplacement<>0 then
  1532. begin
  1533. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to group '+target_group.Name);
  1534. exit;
  1535. end;
  1536. end
  1537. else
  1538. begin
  1539. {todo: convert other fixup types as well }
  1540. InputError('Unsupported fixup target method '+IntToStr(Ord(Fixup.TargetMethod)));
  1541. exit;
  1542. end;
  1543. Result:=True;
  1544. end;
  1545. constructor TOmfObjInput.create;
  1546. begin
  1547. inherited create;
  1548. cobjdata:=TOmfObjData;
  1549. FLNames:=TOmfOrderedNameCollection.Create;
  1550. FExtDefs:=TFPHashObjectList.Create;
  1551. FPubDefs:=TFPHashObjectList.Create;
  1552. FRawRecord:=TOmfRawRecord.Create;
  1553. CaseSensitive:=False;
  1554. end;
  1555. destructor TOmfObjInput.destroy;
  1556. begin
  1557. FRawRecord.Free;
  1558. FPubDefs.Free;
  1559. FExtDefs.Free;
  1560. FLNames.Free;
  1561. inherited destroy;
  1562. end;
  1563. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  1564. var
  1565. b: Byte;
  1566. begin
  1567. result:=false;
  1568. if AReader.Read(b,sizeof(b)) then
  1569. begin
  1570. if b=RT_THEADR then
  1571. { TODO: check additional fields }
  1572. result:=true;
  1573. end;
  1574. AReader.Seek(0);
  1575. end;
  1576. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  1577. begin
  1578. FReader:=AReader;
  1579. InputFileName:=AReader.FileName;
  1580. objdata:=CObjData.Create(InputFileName);
  1581. result:=false;
  1582. LNames.Clear;
  1583. ExtDefs.Clear;
  1584. FRawRecord.ReadFrom(FReader);
  1585. if not FRawRecord.VerifyChecksumByte then
  1586. begin
  1587. InputError('Invalid checksum in OMF record');
  1588. exit;
  1589. end;
  1590. if FRawRecord.RecordType<>RT_THEADR then
  1591. begin
  1592. InputError('Can''t read OMF header');
  1593. exit;
  1594. end;
  1595. repeat
  1596. FRawRecord.ReadFrom(FReader);
  1597. if not FRawRecord.VerifyChecksumByte then
  1598. begin
  1599. InputError('Invalid checksum in OMF record');
  1600. exit;
  1601. end;
  1602. case FRawRecord.RecordType of
  1603. RT_LNAMES:
  1604. if not ReadLNames(FRawRecord) then
  1605. exit;
  1606. RT_SEGDEF,RT_SEGDEF32:
  1607. if not ReadSegDef(FRawRecord,objdata) then
  1608. exit;
  1609. RT_GRPDEF:
  1610. if not ReadGrpDef(FRawRecord,objdata) then
  1611. exit;
  1612. RT_COMENT:
  1613. begin
  1614. {todo}
  1615. end;
  1616. RT_EXTDEF:
  1617. if not ReadExtDef(FRawRecord,objdata) then
  1618. exit;
  1619. RT_PUBDEF,RT_PUBDEF32:
  1620. if not ReadPubDef(FRawRecord,objdata) then
  1621. exit;
  1622. RT_LEDATA,RT_LEDATA32:
  1623. if not ReadLEDataAndFixups(FRawRecord,objdata) then
  1624. exit;
  1625. RT_LIDATA,RT_LIDATA32:
  1626. begin
  1627. InputError('LIDATA records are not supported');
  1628. exit;
  1629. end;
  1630. RT_FIXUPP,RT_FIXUPP32:
  1631. begin
  1632. InputError('FIXUPP record is invalid, because it does not follow a LEDATA or LIDATA record');
  1633. exit;
  1634. end;
  1635. RT_MODEND,RT_MODEND32:
  1636. if not ReadModEnd(FRawRecord,objdata) then
  1637. exit;
  1638. else
  1639. begin
  1640. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  1641. exit;
  1642. end;
  1643. end;
  1644. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  1645. result:=true;
  1646. end;
  1647. {****************************************************************************
  1648. TMZExeHeader
  1649. ****************************************************************************}
  1650. procedure TMZExeHeader.SetHeaderSizeAlignment(AValue: Integer);
  1651. begin
  1652. if (AValue<16) or ((AValue mod 16) <> 0) then
  1653. Internalerror(2015060601);
  1654. FHeaderSizeAlignment:=AValue;
  1655. end;
  1656. constructor TMZExeHeader.Create;
  1657. begin
  1658. FHeaderSizeAlignment:=16;
  1659. end;
  1660. procedure TMZExeHeader.WriteTo(aWriter: TObjectWriter);
  1661. var
  1662. NumRelocs: Word;
  1663. HeaderSizeInBytes: DWord;
  1664. HeaderParagraphs: Word;
  1665. RelocTableOffset: Word;
  1666. BytesInLastBlock: Word;
  1667. BlocksInFile: Word;
  1668. HeaderBytes: array [0..$1B] of Byte;
  1669. RelocBytes: array [0..3] of Byte;
  1670. TotalExeSize: DWord;
  1671. i: Integer;
  1672. begin
  1673. NumRelocs:=Length(Relocations);
  1674. RelocTableOffset:=$1C+Length(ExtraHeaderData);
  1675. HeaderSizeInBytes:=Align(RelocTableOffset+4*NumRelocs,16);
  1676. HeaderParagraphs:=HeaderSizeInBytes div 16;
  1677. TotalExeSize:=HeaderSizeInBytes+LoadableImageSize;
  1678. BlocksInFile:=(TotalExeSize+511) div 512;
  1679. BytesInLastBlock:=TotalExeSize mod 512;
  1680. HeaderBytes[$00]:=$4D; { 'M' }
  1681. HeaderBytes[$01]:=$5A; { 'Z' }
  1682. HeaderBytes[$02]:=Byte(BytesInLastBlock);
  1683. HeaderBytes[$03]:=Byte(BytesInLastBlock shr 8);
  1684. HeaderBytes[$04]:=Byte(BlocksInFile);
  1685. HeaderBytes[$05]:=Byte(BlocksInFile shr 8);
  1686. HeaderBytes[$06]:=Byte(NumRelocs);
  1687. HeaderBytes[$07]:=Byte(NumRelocs shr 8);
  1688. HeaderBytes[$08]:=Byte(HeaderParagraphs);
  1689. HeaderBytes[$09]:=Byte(HeaderParagraphs shr 8);
  1690. HeaderBytes[$0A]:=Byte(MinExtraParagraphs);
  1691. HeaderBytes[$0B]:=Byte(MinExtraParagraphs shr 8);
  1692. HeaderBytes[$0C]:=Byte(MaxExtraParagraphs);
  1693. HeaderBytes[$0D]:=Byte(MaxExtraParagraphs shr 8);
  1694. HeaderBytes[$0E]:=Byte(InitialSS);
  1695. HeaderBytes[$0F]:=Byte(InitialSS shr 8);
  1696. HeaderBytes[$10]:=Byte(InitialSP);
  1697. HeaderBytes[$11]:=Byte(InitialSP shr 8);
  1698. HeaderBytes[$12]:=Byte(Checksum);
  1699. HeaderBytes[$13]:=Byte(Checksum shr 8);
  1700. HeaderBytes[$14]:=Byte(InitialIP);
  1701. HeaderBytes[$15]:=Byte(InitialIP shr 8);
  1702. HeaderBytes[$16]:=Byte(InitialCS);
  1703. HeaderBytes[$17]:=Byte(InitialCS shr 8);
  1704. HeaderBytes[$18]:=Byte(RelocTableOffset);
  1705. HeaderBytes[$19]:=Byte(RelocTableOffset shr 8);
  1706. HeaderBytes[$1A]:=Byte(OverlayNumber);
  1707. HeaderBytes[$1B]:=Byte(OverlayNumber shr 8);
  1708. aWriter.write(HeaderBytes[0],$1C);
  1709. aWriter.write(ExtraHeaderData[0],Length(ExtraHeaderData));
  1710. for i:=0 to NumRelocs-1 do
  1711. with Relocations[i] do
  1712. begin
  1713. RelocBytes[0]:=Byte(offset);
  1714. RelocBytes[1]:=Byte(offset shr 8);
  1715. RelocBytes[2]:=Byte(segment);
  1716. RelocBytes[3]:=Byte(segment shr 8);
  1717. aWriter.write(RelocBytes[0],4);
  1718. end;
  1719. { pad with zeros until the end of header (paragraph aligned) }
  1720. aWriter.WriteZeros(HeaderSizeInBytes-aWriter.Size);
  1721. end;
  1722. procedure TMZExeHeader.AddRelocation(aSegment, aOffset: Word);
  1723. begin
  1724. SetLength(FRelocations,Length(FRelocations)+1);
  1725. with FRelocations[High(FRelocations)] do
  1726. begin
  1727. segment:=aSegment;
  1728. offset:=aOffset;
  1729. end;
  1730. end;
  1731. {****************************************************************************
  1732. TMZExeSection
  1733. ****************************************************************************}
  1734. procedure TMZExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  1735. begin
  1736. { allow mixing initialized and uninitialized data in the same section
  1737. => set ignoreprops=true }
  1738. inherited AddObjSection(objsec,true);
  1739. end;
  1740. {****************************************************************************
  1741. TMZExeUnifiedLogicalSegment
  1742. ****************************************************************************}
  1743. constructor TMZExeUnifiedLogicalSegment.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  1744. var
  1745. Separator: SizeInt;
  1746. begin
  1747. inherited create(HashObjectList,s);
  1748. FObjSectionList:=TFPObjectList.Create(false);
  1749. { name format is 'SegName||ClassName' }
  1750. Separator:=Pos('||',s);
  1751. if Separator>0 then
  1752. begin
  1753. FSegName:=Copy(s,1,Separator-1);
  1754. FSegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  1755. end
  1756. else
  1757. begin
  1758. FSegName:=Name;
  1759. FSegClass:='';
  1760. end;
  1761. { wlink recognizes the stack segment by the class name 'STACK' }
  1762. { let's be compatible with wlink }
  1763. IsStack:=FSegClass='STACK';
  1764. end;
  1765. destructor TMZExeUnifiedLogicalSegment.destroy;
  1766. begin
  1767. FObjSectionList.Free;
  1768. inherited destroy;
  1769. end;
  1770. procedure TMZExeUnifiedLogicalSegment.AddObjSection(ObjSec: TOmfObjSection);
  1771. begin
  1772. ObjSectionList.Add(ObjSec);
  1773. ObjSec.MZExeUnifiedLogicalSegment:=self;
  1774. { tlink (and ms link?) use the scStack segment combination to recognize
  1775. the stack segment.
  1776. let's be compatible with tlink as well }
  1777. if ObjSec.Combination=scStack then
  1778. IsStack:=True;
  1779. end;
  1780. procedure TMZExeUnifiedLogicalSegment.CalcMemPos;
  1781. var
  1782. MinMemPos: qword=high(qword);
  1783. MaxMemPos: qword=0;
  1784. objsec: TOmfObjSection;
  1785. i: Integer;
  1786. begin
  1787. if ObjSectionList.Count=0 then
  1788. internalerror(2015082201);
  1789. for i:=0 to ObjSectionList.Count-1 do
  1790. begin
  1791. objsec:=TOmfObjSection(ObjSectionList[i]);
  1792. if objsec.MemPos<MinMemPos then
  1793. MinMemPos:=objsec.MemPos;
  1794. if (objsec.MemPos+objsec.Size)>MaxMemPos then
  1795. MaxMemPos:=objsec.MemPos+objsec.Size;
  1796. end;
  1797. MemPos:=MinMemPos;
  1798. Size:=MaxMemPos-MemPos;
  1799. end;
  1800. function TMZExeUnifiedLogicalSegment.MemPosStr: string;
  1801. begin
  1802. Result:=HexStr(MemBasePos shr 4,4)+':'+HexStr((MemPos-MemBasePos),4);
  1803. end;
  1804. {****************************************************************************
  1805. TMZExeUnifiedLogicalGroup
  1806. ****************************************************************************}
  1807. constructor TMZExeUnifiedLogicalGroup.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  1808. begin
  1809. inherited create(HashObjectList,s);
  1810. FSegmentList:=TFPHashObjectList.Create(false);
  1811. end;
  1812. destructor TMZExeUnifiedLogicalGroup.destroy;
  1813. begin
  1814. FSegmentList.Free;
  1815. inherited destroy;
  1816. end;
  1817. procedure TMZExeUnifiedLogicalGroup.CalcMemPos;
  1818. var
  1819. MinMemPos: qword=high(qword);
  1820. MaxMemPos: qword=0;
  1821. UniSeg: TMZExeUnifiedLogicalSegment;
  1822. i: Integer;
  1823. begin
  1824. if SegmentList.Count=0 then
  1825. internalerror(2015082201);
  1826. for i:=0 to SegmentList.Count-1 do
  1827. begin
  1828. UniSeg:=TMZExeUnifiedLogicalSegment(SegmentList[i]);
  1829. if UniSeg.MemPos<MinMemPos then
  1830. MinMemPos:=UniSeg.MemPos;
  1831. if (UniSeg.MemPos+UniSeg.Size)>MaxMemPos then
  1832. MaxMemPos:=UniSeg.MemPos+UniSeg.Size;
  1833. end;
  1834. { align *down* on a paragraph boundary }
  1835. MemPos:=(MinMemPos shr 4) shl 4;
  1836. Size:=MaxMemPos-MemPos;
  1837. end;
  1838. function TMZExeUnifiedLogicalGroup.MemPosStr: string;
  1839. begin
  1840. Result:=HexStr(MemPos shr 4,4)+':'+HexStr(MemPos and $f,4);
  1841. end;
  1842. procedure TMZExeUnifiedLogicalGroup.AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  1843. begin
  1844. SegmentList.Add(UniSeg.Name,UniSeg);
  1845. if UniSeg.PrimaryGroup='' then
  1846. UniSeg.PrimaryGroup:=Name;
  1847. end;
  1848. {****************************************************************************
  1849. TMZExeOutput
  1850. ****************************************************************************}
  1851. function TMZExeOutput.GetMZFlatContentSection: TMZExeSection;
  1852. begin
  1853. if not assigned(FMZFlatContentSection) then
  1854. FMZFlatContentSection:=TMZExeSection(FindExeSection('.MZ_flat_content'));
  1855. result:=FMZFlatContentSection;
  1856. end;
  1857. procedure TMZExeOutput.CalcExeUnifiedLogicalSegments;
  1858. var
  1859. ExeSec: TMZExeSection;
  1860. ObjSec: TOmfObjSection;
  1861. UniSeg: TMZExeUnifiedLogicalSegment;
  1862. i: Integer;
  1863. begin
  1864. ExeSec:=MZFlatContentSection;
  1865. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  1866. begin
  1867. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  1868. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments.Find(ObjSec.Name));
  1869. if not assigned(UniSeg) then
  1870. UniSeg:=TMZExeUnifiedLogicalSegment.Create(ExeUnifiedLogicalSegments,ObjSec.Name);
  1871. UniSeg.AddObjSection(ObjSec);
  1872. end;
  1873. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  1874. begin
  1875. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  1876. UniSeg.CalcMemPos;
  1877. if UniSeg.Size>$10000 then
  1878. begin
  1879. if current_settings.x86memorymodel=mm_tiny then
  1880. Message1(link_e_program_segment_too_large,IntToStr(UniSeg.Size-$10000))
  1881. else if UniSeg.SegClass='CODE' then
  1882. Message1(link_e_code_segment_too_large,IntToStr(UniSeg.Size-$10000))
  1883. else if UniSeg.SegClass='DATA' then
  1884. Message1(link_e_data_segment_too_large,IntToStr(UniSeg.Size-$10000))
  1885. else
  1886. Message2(link_e_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000));
  1887. end;
  1888. end;
  1889. end;
  1890. procedure TMZExeOutput.CalcExeGroups;
  1891. procedure AddToGroup(UniSeg:TMZExeUnifiedLogicalSegment;GroupName:TSymStr);
  1892. var
  1893. Group: TMZExeUnifiedLogicalGroup;
  1894. begin
  1895. Group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(GroupName));
  1896. if not assigned(Group) then
  1897. Group:=TMZExeUnifiedLogicalGroup.Create(ExeUnifiedLogicalGroups,GroupName);
  1898. Group.AddSegment(UniSeg);
  1899. end;
  1900. var
  1901. objdataidx,groupidx,secidx: Integer;
  1902. ObjData: TObjData;
  1903. ObjGroup: TObjSectionGroup;
  1904. ObjSec: TOmfObjSection;
  1905. UniGrp: TMZExeUnifiedLogicalGroup;
  1906. begin
  1907. for objdataidx:=0 to ObjDataList.Count-1 do
  1908. begin
  1909. ObjData:=TObjData(ObjDataList[objdataidx]);
  1910. if assigned(ObjData.GroupsList) then
  1911. for groupidx:=0 to ObjData.GroupsList.Count-1 do
  1912. begin
  1913. ObjGroup:=TObjSectionGroup(ObjData.GroupsList[groupidx]);
  1914. for secidx:=low(ObjGroup.members) to high(ObjGroup.members) do
  1915. begin
  1916. ObjSec:=TOmfObjSection(ObjGroup.members[secidx]);
  1917. if assigned(ObjSec.MZExeUnifiedLogicalSegment) then
  1918. AddToGroup(ObjSec.MZExeUnifiedLogicalSegment,ObjGroup.Name);
  1919. end;
  1920. end;
  1921. end;
  1922. for groupidx:=0 to ExeUnifiedLogicalGroups.Count-1 do
  1923. begin
  1924. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[groupidx]);
  1925. UniGrp.CalcMemPos;
  1926. if UniGrp.Size>$10000 then
  1927. begin
  1928. if current_settings.x86memorymodel=mm_tiny then
  1929. Message1(link_e_program_segment_too_large,IntToStr(UniGrp.Size-$10000))
  1930. else if UniGrp.Name='DGROUP' then
  1931. Message1(link_e_data_segment_too_large,IntToStr(UniGrp.Size-$10000))
  1932. else
  1933. Message2(link_e_group_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000));
  1934. end;
  1935. end;
  1936. end;
  1937. procedure TMZExeOutput.CalcSegments_MemBasePos;
  1938. var
  1939. lastbase:qword=0;
  1940. i: Integer;
  1941. UniSeg: TMZExeUnifiedLogicalSegment;
  1942. begin
  1943. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  1944. begin
  1945. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  1946. if (UniSeg.PrimaryGroup<>'') or (UniSeg.IsStack) or
  1947. (((UniSeg.MemPos+UniSeg.Size-1)-lastbase)>$ffff) then
  1948. lastbase:=(UniSeg.MemPos shr 4) shl 4;
  1949. UniSeg.MemBasePos:=lastbase;
  1950. end;
  1951. end;
  1952. procedure TMZExeOutput.WriteMap_SegmentsAndGroups;
  1953. var
  1954. i: Integer;
  1955. UniSeg: TMZExeUnifiedLogicalSegment;
  1956. UniGrp: TMZExeUnifiedLogicalGroup;
  1957. begin
  1958. exemap.AddHeader('Groups list');
  1959. exemap.Add('');
  1960. exemap.Add(PadSpace('Group',32)+PadSpace('Address',21)+'Size');
  1961. exemap.Add(PadSpace('=====',32)+PadSpace('=======',21)+'====');
  1962. exemap.Add('');
  1963. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  1964. begin
  1965. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  1966. exemap.Add(PadSpace(UniGrp.Name,32)+PadSpace(UniGrp.MemPosStr,21)+HexStr(UniGrp.Size,8));
  1967. end;
  1968. exemap.Add('');
  1969. exemap.AddHeader('Segments list');
  1970. exemap.Add('');
  1971. exemap.Add(PadSpace('Segment',23)+PadSpace('Class',15)+PadSpace('Group',15)+PadSpace('Address',16)+'Size');
  1972. exemap.Add(PadSpace('=======',23)+PadSpace('=====',15)+PadSpace('=====',15)+PadSpace('=======',16)+'====');
  1973. exemap.Add('');
  1974. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  1975. begin
  1976. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  1977. exemap.Add(PadSpace(UniSeg.SegName,23)+PadSpace(UniSeg.SegClass,15)+PadSpace(UniSeg.PrimaryGroup,15)+PadSpace(UniSeg.MemPosStr,16)+HexStr(UniSeg.Size,8));
  1978. end;
  1979. exemap.Add('');
  1980. end;
  1981. procedure TMZExeOutput.WriteMap_HeaderData;
  1982. begin
  1983. exemap.AddHeader('Header data');
  1984. exemap.Add('Loadable image size: '+HexStr(Header.LoadableImageSize,8));
  1985. exemap.Add('Min extra paragraphs: '+HexStr(Header.MinExtraParagraphs,4));
  1986. exemap.Add('Max extra paragraphs: '+HexStr(Header.MaxExtraParagraphs,4));
  1987. exemap.Add('Initial stack pointer: '+HexStr(Header.InitialSS,4)+':'+HexStr(Header.InitialSP,4));
  1988. exemap.Add('Entry point address: '+HexStr(Header.InitialCS,4)+':'+HexStr(Header.InitialIP,4));
  1989. end;
  1990. function TMZExeOutput.FindStackSegment: TMZExeUnifiedLogicalSegment;
  1991. var
  1992. i: Integer;
  1993. stackseg_wannabe: TMZExeUnifiedLogicalSegment;
  1994. begin
  1995. Result:=nil;
  1996. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  1997. begin
  1998. stackseg_wannabe:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  1999. { if there are multiple stack segments, choose the largest one.
  2000. In theory, we're probably supposed to combine them all and put
  2001. them in a contiguous location in memory, but we don't care }
  2002. if stackseg_wannabe.IsStack and
  2003. (not assigned(result) or (Result.Size<stackseg_wannabe.Size)) then
  2004. Result:=stackseg_wannabe;
  2005. end;
  2006. end;
  2007. procedure TMZExeOutput.FillLoadableImageSize;
  2008. var
  2009. i: Integer;
  2010. ExeSec: TMZExeSection;
  2011. ObjSec: TOmfObjSection;
  2012. StartDataPos: LongWord;
  2013. buf: array [0..1023] of byte;
  2014. bytesread: LongWord;
  2015. begin
  2016. Header.LoadableImageSize:=0;
  2017. ExeSec:=MZFlatContentSection;
  2018. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2019. begin
  2020. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2021. if (ObjSec.Size>0) and assigned(ObjSec.Data) then
  2022. if (ObjSec.MemPos+ObjSec.Size)>Header.LoadableImageSize then
  2023. Header.LoadableImageSize:=ObjSec.MemPos+ObjSec.Size;
  2024. end;
  2025. end;
  2026. procedure TMZExeOutput.FillMinExtraParagraphs;
  2027. var
  2028. ExeSec: TMZExeSection;
  2029. begin
  2030. ExeSec:=MZFlatContentSection;
  2031. Header.MinExtraParagraphs:=(align(ExeSec.Size,16)-align(Header.LoadableImageSize,16)) div 16;
  2032. end;
  2033. procedure TMZExeOutput.FillMaxExtraParagraphs;
  2034. var
  2035. heapmin_paragraphs: Integer;
  2036. heapmax_paragraphs: Integer;
  2037. begin
  2038. if current_settings.x86memorymodel in x86_far_data_models then
  2039. begin
  2040. { calculate the additional number of paragraphs needed }
  2041. heapmin_paragraphs:=(heapsize + 15) div 16;
  2042. heapmax_paragraphs:=(maxheapsize + 15) div 16;
  2043. Header.MaxExtraParagraphs:=min(Header.MinExtraParagraphs-heapmin_paragraphs+heapmax_paragraphs,$FFFF);
  2044. end
  2045. else
  2046. Header.MaxExtraParagraphs:=$FFFF;
  2047. end;
  2048. procedure TMZExeOutput.FillStartAddress;
  2049. var
  2050. EntryMemPos: qword;
  2051. EntryMemBasePos: qword;
  2052. begin
  2053. EntryMemPos:=EntrySym.address;
  2054. if assigned(EntrySym.group) then
  2055. EntryMemBasePos:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(EntrySym.group.Name)).MemPos
  2056. else
  2057. EntryMemBasePos:=TOmfObjSection(EntrySym.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2058. Header.InitialIP:=EntryMemPos-EntryMemBasePos;
  2059. Header.InitialCS:=EntryMemBasePos shr 4;
  2060. end;
  2061. procedure TMZExeOutput.FillStackAddress;
  2062. var
  2063. stackseg: TMZExeUnifiedLogicalSegment;
  2064. begin
  2065. stackseg:=FindStackSegment;
  2066. if assigned(stackseg) then
  2067. begin
  2068. Header.InitialSS:=stackseg.MemBasePos shr 4;
  2069. Header.InitialSP:=stackseg.MemPos+stackseg.Size-stackseg.MemBasePos;
  2070. end
  2071. else
  2072. begin
  2073. Header.InitialSS:=0;
  2074. Header.InitialSP:=0;
  2075. end;
  2076. end;
  2077. procedure TMZExeOutput.FillHeaderData;
  2078. begin
  2079. Header.MaxExtraParagraphs:=$FFFF;
  2080. FillLoadableImageSize;
  2081. FillMinExtraParagraphs;
  2082. FillMaxExtraParagraphs;
  2083. FillStartAddress;
  2084. FillStackAddress;
  2085. if assigned(exemap) then
  2086. WriteMap_HeaderData;
  2087. end;
  2088. function TMZExeOutput.writeExe: boolean;
  2089. var
  2090. ExeSec: TMZExeSection;
  2091. i: Integer;
  2092. ObjSec: TOmfObjSection;
  2093. begin
  2094. Result:=False;
  2095. FillHeaderData;
  2096. Header.WriteTo(FWriter);
  2097. ExeSec:=MZFlatContentSection;
  2098. ExeSec.DataPos:=FWriter.Size;
  2099. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2100. begin
  2101. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2102. if ObjSec.MemPos<Header.LoadableImageSize then
  2103. begin
  2104. FWriter.WriteZeros(max(0,ObjSec.MemPos-FWriter.Size+ExeSec.DataPos));
  2105. if assigned(ObjSec.Data) then
  2106. FWriter.writearray(ObjSec.Data);
  2107. end;
  2108. end;
  2109. Result:=True;
  2110. end;
  2111. function TMZExeOutput.writeCom: boolean;
  2112. const
  2113. ComFileOffset=$100;
  2114. var
  2115. i: Integer;
  2116. ExeSec: TMZExeSection;
  2117. ObjSec: TOmfObjSection;
  2118. StartDataPos: LongWord;
  2119. buf: array [0..1023] of byte;
  2120. bytesread: LongWord;
  2121. begin
  2122. FillHeaderData;
  2123. if Length(Header.Relocations)>0 then
  2124. begin
  2125. Message(link_e_com_program_uses_segment_relocations);
  2126. exit(False);
  2127. end;
  2128. ExeSec:=MZFlatContentSection;
  2129. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2130. begin
  2131. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2132. if ObjSec.MemPos<Header.LoadableImageSize then
  2133. begin
  2134. FWriter.WriteZeros(max(0,ObjSec.MemPos-ComFileOffset-FWriter.Size));
  2135. if assigned(ObjSec.Data) then
  2136. begin
  2137. if ObjSec.MemPos<ComFileOffset then
  2138. begin
  2139. ObjSec.Data.seek(ComFileOffset-ObjSec.MemPos);
  2140. repeat
  2141. bytesread:=ObjSec.Data.read(buf,sizeof(buf));
  2142. if bytesread<>0 then
  2143. FWriter.write(buf,bytesread);
  2144. until bytesread=0;
  2145. end
  2146. else
  2147. FWriter.writearray(ObjSec.Data);
  2148. end;
  2149. end;
  2150. end;
  2151. Result:=True;
  2152. end;
  2153. procedure TMZExeOutput.Load_Symbol(const aname: string);
  2154. var
  2155. dgroup: TObjSectionGroup;
  2156. sym: TObjSymbol;
  2157. begin
  2158. { special handling for the '_edata' and '_end' symbols, which are
  2159. internally added by the linker }
  2160. if (aname='_edata') or (aname='_end') then
  2161. begin
  2162. { create an internal segment with the 'BSS' class }
  2163. internalObjData.createsection('*'+aname+'||BSS',0,[]);
  2164. { add to group 'DGROUP' }
  2165. dgroup:=nil;
  2166. if assigned(internalObjData.GroupsList) then
  2167. dgroup:=TObjSectionGroup(internalObjData.GroupsList.Find('DGROUP'));
  2168. if dgroup=nil then
  2169. dgroup:=internalObjData.createsectiongroup('DGROUP');
  2170. SetLength(dgroup.members,Length(dgroup.members)+1);
  2171. dgroup.members[Length(dgroup.members)-1]:=internalObjData.CurrObjSec;
  2172. { define the symbol itself }
  2173. sym:=internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  2174. sym.group:=dgroup;
  2175. end
  2176. else
  2177. inherited;
  2178. end;
  2179. procedure TMZExeOutput.DoRelocationFixup(objsec: TObjSection);
  2180. var
  2181. i: Integer;
  2182. omfsec: TOmfObjSection absolute objsec;
  2183. objreloc: TOmfRelocation;
  2184. target: DWord;
  2185. framebase: DWord;
  2186. fixupamount: Integer;
  2187. target_group: TMZExeUnifiedLogicalGroup;
  2188. procedure FixupOffset;
  2189. var
  2190. w: Word;
  2191. begin
  2192. omfsec.Data.seek(objreloc.DataOffset);
  2193. omfsec.Data.read(w,2);
  2194. w:=LEtoN(w);
  2195. Inc(w,fixupamount);
  2196. w:=LEtoN(w);
  2197. omfsec.Data.seek(objreloc.DataOffset);
  2198. omfsec.Data.write(w,2);
  2199. end;
  2200. procedure FixupBase;
  2201. var
  2202. w: Word;
  2203. begin
  2204. omfsec.Data.seek(objreloc.DataOffset);
  2205. omfsec.Data.read(w,2);
  2206. w:=LEtoN(w);
  2207. Inc(w,framebase shr 4);
  2208. w:=LEtoN(w);
  2209. omfsec.Data.seek(objreloc.DataOffset);
  2210. omfsec.Data.write(w,2);
  2211. Header.AddRelocation(omfsec.MZExeUnifiedLogicalSegment.MemBasePos shr 4,
  2212. omfsec.MemPos+objreloc.DataOffset-omfsec.MZExeUnifiedLogicalSegment.MemBasePos);
  2213. end;
  2214. begin
  2215. for i:=0 to objsec.ObjRelocations.Count-1 do
  2216. begin
  2217. objreloc:=TOmfRelocation(objsec.ObjRelocations[i]);
  2218. if assigned(objreloc.symbol) then
  2219. begin
  2220. target:=objreloc.symbol.address;
  2221. if objreloc.FrameGroup<>'' then
  2222. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2223. else if assigned(objreloc.symbol.group) then
  2224. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.symbol.group.Name)).MemPos
  2225. else
  2226. framebase:=TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2227. case objreloc.typ of
  2228. RELOC_ABSOLUTE,RELOC_SEG:
  2229. fixupamount:=target-framebase;
  2230. RELOC_RELATIVE,RELOC_SEGREL:
  2231. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2232. else
  2233. internalerror(2015082402);
  2234. end;
  2235. case objreloc.typ of
  2236. RELOC_ABSOLUTE,
  2237. RELOC_RELATIVE:
  2238. FixupOffset;
  2239. RELOC_SEG,
  2240. RELOC_SEGREL:
  2241. FixupBase;
  2242. else
  2243. internalerror(2015082403);
  2244. end;
  2245. end
  2246. else if assigned(objreloc.objsection) then
  2247. begin
  2248. target:=objreloc.objsection.MemPos;
  2249. if objreloc.FrameGroup<>'' then
  2250. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2251. else
  2252. framebase:=TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2253. case objreloc.typ of
  2254. RELOC_ABSOLUTE,RELOC_SEG:
  2255. fixupamount:=target-framebase;
  2256. RELOC_RELATIVE,RELOC_SEGREL:
  2257. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2258. else
  2259. internalerror(2015082405);
  2260. end;
  2261. case objreloc.typ of
  2262. RELOC_ABSOLUTE,
  2263. RELOC_RELATIVE:
  2264. FixupOffset;
  2265. RELOC_SEG,
  2266. RELOC_SEGREL:
  2267. FixupBase;
  2268. else
  2269. internalerror(2015082406);
  2270. end;
  2271. end
  2272. else if assigned(objreloc.group) then
  2273. begin
  2274. target_group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.group.Name));
  2275. target:=target_group.MemPos;
  2276. if objreloc.FrameGroup<>'' then
  2277. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  2278. else
  2279. framebase:=target_group.MemPos;
  2280. case objreloc.typ of
  2281. RELOC_ABSOLUTE,RELOC_SEG:
  2282. fixupamount:=target-framebase;
  2283. RELOC_RELATIVE,RELOC_SEGREL:
  2284. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  2285. else
  2286. internalerror(2015111202);
  2287. end;
  2288. case objreloc.typ of
  2289. RELOC_ABSOLUTE,
  2290. RELOC_RELATIVE:
  2291. FixupOffset;
  2292. RELOC_SEG,
  2293. RELOC_SEGREL:
  2294. FixupBase;
  2295. else
  2296. internalerror(2015111203);
  2297. end;
  2298. end
  2299. else
  2300. internalerror(2015082407);
  2301. end;
  2302. end;
  2303. function IOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  2304. var
  2305. I1 : TOmfObjSection absolute Item1;
  2306. I2 : TOmfObjSection absolute Item2;
  2307. begin
  2308. Result:=CompareStr(I1.ClassName,I2.ClassName);
  2309. if Result=0 then
  2310. Result:=CompareStr(I1.Name,I2.Name);
  2311. if Result=0 then
  2312. Result:=I1.SortOrder-I2.SortOrder;
  2313. end;
  2314. procedure TMZExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList; const aPattern: string);
  2315. var
  2316. i: Integer;
  2317. begin
  2318. for i:=0 to ObjSectionList.Count-1 do
  2319. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  2320. ObjSectionList.Sort(@IOmfObjSectionClassNameCompare);
  2321. end;
  2322. procedure TMZExeOutput.MemPos_EndExeSection;
  2323. var
  2324. SecName: TSymStr='';
  2325. begin
  2326. if assigned(CurrExeSec) then
  2327. SecName:=CurrExeSec.Name;
  2328. inherited MemPos_EndExeSection;
  2329. if SecName='.MZ_flat_content' then
  2330. begin
  2331. CalcExeUnifiedLogicalSegments;
  2332. CalcExeGroups;
  2333. CalcSegments_MemBasePos;
  2334. if assigned(exemap) then
  2335. WriteMap_SegmentsAndGroups;
  2336. end;
  2337. end;
  2338. function TMZExeOutput.writeData: boolean;
  2339. begin
  2340. if apptype=app_com then
  2341. Result:=WriteCom
  2342. else
  2343. Result:=WriteExe;
  2344. end;
  2345. constructor TMZExeOutput.create;
  2346. begin
  2347. inherited create;
  2348. CExeSection:=TMZExeSection;
  2349. CObjData:=TOmfObjData;
  2350. CObjSymbol:=TOmfObjSymbol;
  2351. { "640K ought to be enough for anybody" :) }
  2352. MaxMemPos:=$9FFFF;
  2353. FExeUnifiedLogicalSegments:=TFPHashObjectList.Create;
  2354. FExeUnifiedLogicalGroups:=TFPHashObjectList.Create;
  2355. FHeader:=TMZExeHeader.Create;
  2356. end;
  2357. destructor TMZExeOutput.destroy;
  2358. begin
  2359. FHeader.Free;
  2360. FExeUnifiedLogicalGroups.Free;
  2361. FExeUnifiedLogicalSegments.Free;
  2362. inherited destroy;
  2363. end;
  2364. {****************************************************************************
  2365. TOmfAssembler
  2366. ****************************************************************************}
  2367. constructor TOmfAssembler.Create(info: pasminfo; smart:boolean);
  2368. begin
  2369. inherited;
  2370. CObjOutput:=TOmfObjOutput;
  2371. CInternalAr:=TOmfLibObjectWriter;
  2372. end;
  2373. {*****************************************************************************
  2374. Initialize
  2375. *****************************************************************************}
  2376. {$ifdef i8086}
  2377. const
  2378. as_i8086_omf_info : tasminfo =
  2379. (
  2380. id : as_i8086_omf;
  2381. idtxt : 'OMF';
  2382. asmbin : '';
  2383. asmcmd : '';
  2384. supported_targets : [system_i8086_msdos];
  2385. flags : [af_outputbinary,af_no_debug];
  2386. labelprefix : '..@';
  2387. comment : '; ';
  2388. dollarsign: '$';
  2389. );
  2390. {$endif i8086}
  2391. initialization
  2392. {$ifdef i8086}
  2393. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  2394. {$endif i8086}
  2395. end.