ogomf.pas 121 KB

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