ogomf.pas 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. { TOmfRelocation }
  35. TOmfRelocation = class(TObjRelocation)
  36. private
  37. FOmfFixup: TOmfSubRecord_FIXUP;
  38. function GetGroupIndex(const groupname: string): Integer;
  39. public
  40. constructor CreateSection(ADataOffset:aword;aobjsec:TObjSection;Atyp:TObjRelocationType);
  41. destructor Destroy; override;
  42. procedure BuildOmfFixup;
  43. property OmfFixup: TOmfSubRecord_FIXUP read FOmfFixup;
  44. end;
  45. { TOmfObjSection }
  46. TOmfObjSection = class(TObjSection)
  47. private
  48. FClassName: string;
  49. FOverlayName: string;
  50. FCombination: TOmfSegmentCombination;
  51. FUse: TOmfSegmentUse;
  52. FPrimaryGroup: string;
  53. function GetOmfAlignment: TOmfSegmentAlignment;
  54. public
  55. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);override;
  56. property ClassName: string read FClassName;
  57. property OverlayName: string read FOverlayName;
  58. property OmfAlignment: TOmfSegmentAlignment read GetOmfAlignment;
  59. property Combination: TOmfSegmentCombination read FCombination;
  60. property Use: TOmfSegmentUse read FUse;
  61. property PrimaryGroup: string read FPrimaryGroup;
  62. end;
  63. { TOmfObjData }
  64. TOmfObjData = class(TObjData)
  65. private
  66. class function CodeSectionName(const aname:string): string;
  67. public
  68. constructor create(const n:string);override;
  69. function sectiontype2align(atype:TAsmSectiontype):shortint;override;
  70. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  71. procedure writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  72. end;
  73. { TOmfObjOutput }
  74. TOmfObjOutput = class(tObjOutput)
  75. private
  76. FLNames: TOmfOrderedNameCollection;
  77. FSegments: TFPHashObjectList;
  78. FGroups: TFPHashObjectList;
  79. procedure AddSegment(const name,segclass,ovlname: string;
  80. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  81. Use: TOmfSegmentUse; Size: aword);
  82. procedure AddGroup(const groupname: string; seglist: array of const);
  83. procedure AddGroup(const groupname: string; seglist: TSegmentList);
  84. procedure WriteSections(Data:TObjData);
  85. procedure WriteSectionContentAndFixups(sec: TObjSection);
  86. procedure section_count_sections(p:TObject;arg:pointer);
  87. procedure WritePUBDEFs(Data: TObjData);
  88. procedure WriteEXTDEFs(Data: TObjData);
  89. property LNames: TOmfOrderedNameCollection read FLNames;
  90. property Segments: TFPHashObjectList read FSegments;
  91. property Groups: TFPHashObjectList read FGroups;
  92. protected
  93. function writeData(Data:TObjData):boolean;override;
  94. public
  95. constructor create(AWriter:TObjectWriter);override;
  96. destructor Destroy;override;
  97. end;
  98. { TOmfObjInput }
  99. TOmfObjInput = class(TObjInput)
  100. private
  101. FLNames: TOmfOrderedNameCollection;
  102. FRawRecord: TOmfRawRecord;
  103. function ReadLNames(RawRec: TOmfRawRecord): Boolean;
  104. property LNames: TOmfOrderedNameCollection read FLNames;
  105. public
  106. constructor create;override;
  107. destructor destroy;override;
  108. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  109. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  110. end;
  111. { TMZExeOutput }
  112. TMZExeOutput = class(TExeOutput)
  113. constructor create;override;
  114. end;
  115. TOmfAssembler = class(tinternalassembler)
  116. constructor create(smart:boolean);override;
  117. end;
  118. implementation
  119. uses
  120. SysUtils,
  121. cutils,verbose,globals,
  122. fmodule,aasmtai,aasmdata,
  123. ogmap,owomflib,
  124. version
  125. ;
  126. {****************************************************************************
  127. TOmfRelocation
  128. ****************************************************************************}
  129. function TOmfRelocation.GetGroupIndex(const groupname: string): Integer;
  130. begin
  131. if groupname='dgroup' then
  132. Result:=1
  133. else
  134. internalerror(2014040703);
  135. end;
  136. constructor TOmfRelocation.CreateSection(ADataOffset: aword; aobjsec: TObjSection; Atyp: TObjRelocationType);
  137. begin
  138. if not (Atyp in [RELOC_DGROUP,RELOC_DGROUPREL]) and not assigned(aobjsec) then
  139. internalerror(200603036);
  140. DataOffset:=ADataOffset;
  141. Symbol:=nil;
  142. OrgSize:=0;
  143. ObjSection:=aobjsec;
  144. ftype:=ord(Atyp);
  145. end;
  146. destructor TOmfRelocation.Destroy;
  147. begin
  148. FOmfFixup.Free;
  149. inherited Destroy;
  150. end;
  151. procedure TOmfRelocation.BuildOmfFixup;
  152. begin
  153. FreeAndNil(FOmfFixup);
  154. FOmfFixup:=TOmfSubRecord_FIXUP.Create;
  155. if ObjSection<>nil then
  156. begin
  157. FOmfFixup.LocationOffset:=DataOffset;
  158. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  159. FOmfFixup.LocationType:=fltOffset
  160. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  161. FOmfFixup.LocationType:=fltBase
  162. else
  163. internalerror(2015041501);
  164. FOmfFixup.FrameDeterminedByThread:=False;
  165. FOmfFixup.TargetDeterminedByThread:=False;
  166. if typ in [RELOC_ABSOLUTE,RELOC_SEG] then
  167. FOmfFixup.Mode:=fmSegmentRelative
  168. else if typ in [RELOC_RELATIVE,RELOC_SEGREL] then
  169. FOmfFixup.Mode:=fmSelfRelative
  170. else
  171. internalerror(2015041401);
  172. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  173. begin
  174. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  175. FOmfFixup.TargetDatum:=ObjSection.Index;
  176. if TOmfObjSection(ObjSection).PrimaryGroup<>'' then
  177. begin
  178. FOmfFixup.FrameMethod:=ffmGroupIndex;
  179. FOmfFixup.FrameDatum:=GetGroupIndex(TOmfObjSection(ObjSection).PrimaryGroup);
  180. end
  181. else
  182. FOmfFixup.FrameMethod:=ffmTarget;
  183. end
  184. else
  185. begin
  186. FOmfFixup.FrameMethod:=ffmTarget;
  187. if TOmfObjSection(ObjSection).PrimaryGroup<>'' then
  188. begin
  189. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  190. FOmfFixup.TargetDatum:=GetGroupIndex(TOmfObjSection(ObjSection).PrimaryGroup);
  191. end
  192. else
  193. begin
  194. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  195. FOmfFixup.TargetDatum:=ObjSection.Index;
  196. end;
  197. end;
  198. end
  199. else if symbol<>nil then
  200. begin
  201. FOmfFixup.LocationOffset:=DataOffset;
  202. if typ in [RELOC_ABSOLUTE,RELOC_RELATIVE] then
  203. FOmfFixup.LocationType:=fltOffset
  204. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  205. FOmfFixup.LocationType:=fltBase
  206. else
  207. internalerror(2015041501);
  208. FOmfFixup.FrameDeterminedByThread:=False;
  209. FOmfFixup.TargetDeterminedByThread:=False;
  210. if typ in [RELOC_ABSOLUTE,RELOC_SEG] then
  211. FOmfFixup.Mode:=fmSegmentRelative
  212. else if typ in [RELOC_RELATIVE,RELOC_SEGREL] then
  213. FOmfFixup.Mode:=fmSelfRelative
  214. else
  215. internalerror(2015041401);
  216. FOmfFixup.TargetMethod:=ftmExternalIndexNoDisp;
  217. FOmfFixup.TargetDatum:=symbol.symidx;
  218. FOmfFixup.FrameMethod:=ffmTarget;
  219. end
  220. else if typ in [RELOC_DGROUP,RELOC_DGROUPREL] then
  221. begin
  222. FOmfFixup.LocationOffset:=DataOffset;
  223. FOmfFixup.LocationType:=fltBase;
  224. FOmfFixup.FrameDeterminedByThread:=False;
  225. FOmfFixup.TargetDeterminedByThread:=False;
  226. if typ=RELOC_DGROUP then
  227. FOmfFixup.Mode:=fmSegmentRelative
  228. else if typ=RELOC_DGROUPREL then
  229. FOmfFixup.Mode:=fmSelfRelative
  230. else
  231. internalerror(2015041401);
  232. FOmfFixup.FrameMethod:=ffmTarget;
  233. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  234. FOmfFixup.TargetDatum:=GetGroupIndex('dgroup');
  235. end
  236. else
  237. internalerror(2015040702);
  238. end;
  239. {****************************************************************************
  240. TOmfObjSection
  241. ****************************************************************************}
  242. function TOmfObjSection.GetOmfAlignment: TOmfSegmentAlignment;
  243. begin
  244. case SecAlign of
  245. 1:
  246. result:=saRelocatableByteAligned;
  247. 2:
  248. result:=saRelocatableWordAligned;
  249. 4:
  250. result:=saRelocatableDWordAligned;
  251. 16:
  252. result:=saRelocatableParaAligned;
  253. else
  254. internalerror(2015041504);
  255. end;
  256. end;
  257. constructor TOmfObjSection.create(AList: TFPHashObjectList;
  258. const Aname: string; Aalign: shortint; Aoptions: TObjSectionOptions);
  259. var
  260. dgroup: Boolean;
  261. begin
  262. inherited create(AList, Aname, Aalign, Aoptions);
  263. FCombination:=scPublic;
  264. FUse:=suUse16;
  265. if oso_executable in Aoptions then
  266. begin
  267. FClassName:='code';
  268. dgroup:=(current_settings.x86memorymodel=mm_tiny);
  269. end
  270. else if Aname='stack' then
  271. begin
  272. FClassName:='stack';
  273. FCombination:=scStack;
  274. dgroup:=current_settings.x86memorymodel in (x86_near_data_models-[mm_tiny]);
  275. end
  276. else if Aname='heap' then
  277. begin
  278. FClassName:='heap';
  279. dgroup:=current_settings.x86memorymodel in x86_near_data_models;
  280. end
  281. else if Aname='bss' then
  282. begin
  283. FClassName:='bss';
  284. dgroup:=true;
  285. end
  286. else if Aname='data' then
  287. begin
  288. FClassName:='data';
  289. dgroup:=true;
  290. end
  291. else if (Aname='debug_frame') or
  292. (Aname='debug_info') or
  293. (Aname='debug_line') or
  294. (Aname='debug_abbrev') then
  295. begin
  296. FClassName:='DWARF';
  297. FUse:=suUse32;
  298. dgroup:=false;
  299. end
  300. else
  301. begin
  302. FClassName:='data';
  303. dgroup:=true;
  304. end;
  305. if dgroup then
  306. FPrimaryGroup:='dgroup'
  307. else
  308. FPrimaryGroup:='';
  309. end;
  310. {****************************************************************************
  311. TOmfObjData
  312. ****************************************************************************}
  313. class function TOmfObjData.CodeSectionName(const aname: string): string;
  314. begin
  315. {$ifdef i8086}
  316. if current_settings.x86memorymodel in x86_far_code_models then
  317. begin
  318. if cs_huge_code in current_settings.moduleswitches then
  319. result:=aname + '_TEXT'
  320. else
  321. result:=current_module.modulename^ + '_TEXT';
  322. end
  323. else
  324. {$endif}
  325. result:='text';
  326. end;
  327. constructor TOmfObjData.create(const n: string);
  328. begin
  329. inherited create(n);
  330. CObjSection:=TOmfObjSection;
  331. end;
  332. function TOmfObjData.sectiontype2align(atype: TAsmSectiontype): shortint;
  333. begin
  334. case atype of
  335. sec_stabstr:
  336. result:=1;
  337. sec_code:
  338. result:=1;
  339. sec_data,
  340. sec_rodata,
  341. sec_rodata_norel,
  342. sec_bss:
  343. result:=2;
  344. { For idata (at least idata2) it must be 4 bytes, because
  345. an entry is always (also in win64) 20 bytes and aligning
  346. on 8 bytes will insert 4 bytes between the entries resulting
  347. in a corrupt idata section.
  348. Same story with .pdata, it has 4-byte elements which should
  349. be packed without gaps. }
  350. sec_idata2,sec_idata4,sec_idata5,sec_idata6,sec_idata7,sec_pdata:
  351. result:=4;
  352. sec_debug_frame,sec_debug_info,sec_debug_line,sec_debug_abbrev:
  353. result:=4;
  354. sec_stack,
  355. sec_heap:
  356. result:=16;
  357. else
  358. result:=1;
  359. end;
  360. end;
  361. function TOmfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  362. const
  363. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  364. 'text',
  365. 'data',
  366. 'data',
  367. 'rodata',
  368. 'bss',
  369. 'tbss',
  370. 'pdata',
  371. 'text','data','data','data','data',
  372. 'stab',
  373. 'stabstr',
  374. 'idata2','idata4','idata5','idata6','idata7','edata',
  375. 'eh_frame',
  376. 'debug_frame','debug_info','debug_line','debug_abbrev',
  377. 'fpc',
  378. '',
  379. 'init',
  380. 'fini',
  381. 'objc_class',
  382. 'objc_meta_class',
  383. 'objc_cat_cls_meth',
  384. 'objc_cat_inst_meth',
  385. 'objc_protocol',
  386. 'objc_string_object',
  387. 'objc_cls_meth',
  388. 'objc_inst_meth',
  389. 'objc_cls_refs',
  390. 'objc_message_refs',
  391. 'objc_symbols',
  392. 'objc_category',
  393. 'objc_class_vars',
  394. 'objc_instance_vars',
  395. 'objc_module_info',
  396. 'objc_class_names',
  397. 'objc_meth_var_types',
  398. 'objc_meth_var_names',
  399. 'objc_selector_strs',
  400. 'objc_protocol_ext',
  401. 'objc_class_ext',
  402. 'objc_property',
  403. 'objc_image_info',
  404. 'objc_cstring_object',
  405. 'objc_sel_fixup',
  406. '__DATA,__objc_data',
  407. '__DATA,__objc_const',
  408. 'objc_superrefs',
  409. '__DATA, __datacoal_nt,coalesced',
  410. 'objc_classlist',
  411. 'objc_nlclasslist',
  412. 'objc_catlist',
  413. 'obcj_nlcatlist',
  414. 'objc_protolist',
  415. 'stack',
  416. 'heap'
  417. );
  418. begin
  419. if (atype=sec_user) then
  420. Result:=aname
  421. else if secnames[atype]='text' then
  422. Result:=CodeSectionName(aname)
  423. else
  424. Result:=secnames[atype];
  425. end;
  426. procedure TOmfObjData.writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  427. var
  428. objreloc: TOmfRelocation;
  429. symaddr: AWord;
  430. begin
  431. { RELOC_FARPTR = RELOC_ABSOLUTE+RELOC_SEG }
  432. if Reloctype=RELOC_FARPTR then
  433. begin
  434. if len<>4 then
  435. internalerror(2015041502);
  436. writeReloc(Data,2,p,RELOC_ABSOLUTE);
  437. writeReloc(0,2,p,RELOC_SEG);
  438. exit;
  439. end;
  440. if CurrObjSec=nil then
  441. internalerror(200403072);
  442. objreloc:=nil;
  443. if assigned(p) then
  444. begin
  445. { real address of the symbol }
  446. symaddr:=p.address;
  447. if p.bind=AB_EXTERNAL then
  448. begin
  449. objreloc:=TOmfRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  450. CurrObjSec.ObjRelocations.Add(objreloc);
  451. end
  452. { relative relocations within the same section can be calculated directly,
  453. without the need to emit a relocation entry }
  454. else if (p.objsection=CurrObjSec) and
  455. (p.bind<>AB_COMMON) and
  456. (Reloctype=RELOC_RELATIVE) then
  457. begin
  458. data:=data+symaddr-len-CurrObjSec.Size;
  459. end
  460. else
  461. begin
  462. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,p.objsection,Reloctype);
  463. CurrObjSec.ObjRelocations.Add(objreloc);
  464. if not (Reloctype in [RELOC_SEG,RELOC_SEGREL]) then
  465. inc(data,symaddr);
  466. end;
  467. end
  468. else if Reloctype in [RELOC_DGROUP,RELOC_DGROUPREL] then
  469. begin
  470. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,nil,Reloctype);
  471. CurrObjSec.ObjRelocations.Add(objreloc);
  472. end;
  473. CurrObjSec.write(data,len);
  474. end;
  475. {****************************************************************************
  476. TOmfObjOutput
  477. ****************************************************************************}
  478. procedure TOmfObjOutput.AddSegment(const name, segclass, ovlname: string;
  479. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  480. Use: TOmfSegmentUse; Size: aword);
  481. var
  482. s: TOmfRecord_SEGDEF;
  483. begin
  484. s:=TOmfRecord_SEGDEF.Create;
  485. Segments.Add(name,s);
  486. s.SegmentNameIndex:=LNames.Add(name);
  487. s.ClassNameIndex:=LNames.Add(segclass);
  488. s.OverlayNameIndex:=LNames.Add(ovlname);
  489. s.Alignment:=Alignment;
  490. s.Combination:=Combination;
  491. s.Use:=Use;
  492. s.SegmentLength:=Size;
  493. end;
  494. procedure TOmfObjOutput.AddGroup(const groupname: string; seglist: array of const);
  495. var
  496. g: TOmfRecord_GRPDEF;
  497. I: Integer;
  498. SegListStr: TSegmentList;
  499. begin
  500. g:=TOmfRecord_GRPDEF.Create;
  501. Groups.Add(groupname,g);
  502. g.GroupNameIndex:=LNames.Add(groupname);
  503. SetLength(SegListStr,Length(seglist));
  504. for I:=0 to High(seglist) do
  505. begin
  506. case seglist[I].VType of
  507. vtString:
  508. SegListStr[I]:=Segments.FindIndexOf(seglist[I].VString^);
  509. vtAnsiString:
  510. SegListStr[I]:=Segments.FindIndexOf(AnsiString(seglist[I].VAnsiString));
  511. vtWideString:
  512. SegListStr[I]:=Segments.FindIndexOf(AnsiString(WideString(seglist[I].VWideString)));
  513. vtUnicodeString:
  514. SegListStr[I]:=Segments.FindIndexOf(AnsiString(UnicodeString(seglist[I].VUnicodeString)));
  515. else
  516. internalerror(2015040402);
  517. end;
  518. end;
  519. g.SegmentList:=SegListStr;
  520. end;
  521. procedure TOmfObjOutput.AddGroup(const groupname: string; seglist: TSegmentList);
  522. var
  523. g: TOmfRecord_GRPDEF;
  524. begin
  525. g:=TOmfRecord_GRPDEF.Create;
  526. Groups.Add(groupname,g);
  527. g.GroupNameIndex:=LNames.Add(groupname);
  528. g.SegmentList:=Copy(seglist);
  529. end;
  530. procedure TOmfObjOutput.WriteSections(Data: TObjData);
  531. var
  532. i:longint;
  533. sec:TObjSection;
  534. begin
  535. for i:=0 to Data.ObjSectionList.Count-1 do
  536. begin
  537. sec:=TObjSection(Data.ObjSectionList[i]);
  538. WriteSectionContentAndFixups(sec);
  539. end;
  540. end;
  541. procedure TOmfObjOutput.WriteSectionContentAndFixups(sec: TObjSection);
  542. const
  543. MaxChunkSize=$3fa;
  544. var
  545. RawRecord: TOmfRawRecord;
  546. ChunkStart,ChunkLen: DWord;
  547. ChunkFixupStart,ChunkFixupEnd: Integer;
  548. SegIndex: Integer;
  549. NextOfs: Integer;
  550. I: Integer;
  551. begin
  552. if (oso_data in sec.SecOptions) then
  553. begin
  554. if sec.Data=nil then
  555. internalerror(200403073);
  556. for I:=0 to sec.ObjRelocations.Count-1 do
  557. TOmfRelocation(sec.ObjRelocations[I]).BuildOmfFixup;
  558. SegIndex:=Segments.FindIndexOf(sec.Name);
  559. RawRecord:=TOmfRawRecord.Create;
  560. sec.data.seek(0);
  561. ChunkFixupStart:=0;
  562. ChunkFixupEnd:=-1;
  563. ChunkStart:=0;
  564. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  565. while ChunkLen>0 do
  566. begin
  567. { find last fixup in the chunk }
  568. while (ChunkFixupEnd<(sec.ObjRelocations.Count-1)) and
  569. (TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd+1]).DataOffset<(ChunkStart+ChunkLen)) do
  570. inc(ChunkFixupEnd);
  571. { check if last chunk is crossing the chunk boundary, and trim ChunkLen if necessary }
  572. if (ChunkFixupEnd>=ChunkFixupStart) and
  573. ((TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset+
  574. TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).OmfFixup.LocationSize)>(ChunkStart+ChunkLen)) then
  575. begin
  576. ChunkLen:=TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset-ChunkStart;
  577. Dec(ChunkFixupEnd);
  578. end;
  579. { write LEDATA record }
  580. RawRecord.RecordType:=RT_LEDATA;
  581. NextOfs:=RawRecord.WriteIndexedRef(0,SegIndex);
  582. RawRecord.RawData[NextOfs]:=Byte(ChunkStart);
  583. RawRecord.RawData[NextOfs+1]:=Byte(ChunkStart shr 8);
  584. Inc(NextOfs,2);
  585. sec.data.read(RawRecord.RawData[NextOfs], ChunkLen);
  586. Inc(NextOfs, ChunkLen);
  587. RawRecord.RecordLength:=NextOfs+1;
  588. RawRecord.CalculateChecksumByte;
  589. RawRecord.WriteTo(FWriter);
  590. { write FIXUPP record }
  591. if ChunkFixupEnd>=ChunkFixupStart then
  592. begin
  593. RawRecord.RecordType:=RT_FIXUPP;
  594. NextOfs:=0;
  595. for I:=ChunkFixupStart to ChunkFixupEnd do
  596. begin
  597. TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.DataRecordStartOffset:=ChunkStart;
  598. NextOfs:=TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.WriteAt(RawRecord,NextOfs);
  599. end;
  600. RawRecord.RecordLength:=NextOfs+1;
  601. RawRecord.CalculateChecksumByte;
  602. RawRecord.WriteTo(FWriter);
  603. end;
  604. { prepare next chunk }
  605. Inc(ChunkStart, ChunkLen);
  606. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  607. ChunkFixupStart:=ChunkFixupEnd+1;
  608. end;
  609. RawRecord.Free;
  610. end;
  611. end;
  612. procedure TOmfObjOutput.section_count_sections(p: TObject; arg: pointer);
  613. begin
  614. TOmfObjSection(p).index:=pinteger(arg)^;
  615. inc(pinteger(arg)^);
  616. end;
  617. procedure TOmfObjOutput.WritePUBDEFs(Data: TObjData);
  618. var
  619. PubNamesForSection: array of TFPHashObjectList;
  620. i: Integer;
  621. objsym: TObjSymbol;
  622. PublicNameElem: TOmfPublicNameElement;
  623. RawRecord: TOmfRawRecord;
  624. PubDefRec: TOmfRecord_PUBDEF;
  625. PrimaryGroupName: string;
  626. begin
  627. RawRecord:=TOmfRawRecord.Create;
  628. SetLength(PubNamesForSection,Data.ObjSectionList.Count);
  629. for i:=0 to Data.ObjSectionList.Count-1 do
  630. PubNamesForSection[i]:=TFPHashObjectList.Create;
  631. for i:=0 to Data.ObjSymbolList.Count-1 do
  632. begin
  633. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  634. if objsym.bind=AB_GLOBAL then
  635. begin
  636. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  637. PublicNameElem.PublicOffset:=objsym.offset;
  638. end;
  639. end;
  640. for i:=0 to Data.ObjSectionList.Count-1 do
  641. if PubNamesForSection[i].Count>0 then
  642. begin
  643. PubDefRec:=TOmfRecord_PUBDEF.Create;
  644. PubDefRec.BaseSegmentIndex:=i+1;
  645. PrimaryGroupName:=TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup;
  646. if PrimaryGroupName<>'' then
  647. PubDefRec.BaseGroupIndex:=Groups.FindIndexOf(PrimaryGroupName)
  648. else
  649. PubDefRec.BaseGroupIndex:=0;
  650. PubDefRec.PublicNames:=PubNamesForSection[i];
  651. while PubDefRec.NextIndex<PubDefRec.PublicNames.Count do
  652. begin
  653. PubDefRec.EncodeTo(RawRecord);
  654. RawRecord.WriteTo(FWriter);
  655. end;
  656. PubDefRec.Free;
  657. end;
  658. for i:=0 to Data.ObjSectionList.Count-1 do
  659. FreeAndNil(PubNamesForSection[i]);
  660. RawRecord.Free;
  661. end;
  662. procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
  663. var
  664. ExtNames: TFPHashObjectList;
  665. RawRecord: TOmfRawRecord;
  666. i,idx: Integer;
  667. objsym: TObjSymbol;
  668. ExternalNameElem: TOmfExternalNameElement;
  669. ExtDefRec: TOmfRecord_EXTDEF;
  670. begin
  671. ExtNames:=TFPHashObjectList.Create;
  672. RawRecord:=TOmfRawRecord.Create;
  673. idx:=1;
  674. for i:=0 to Data.ObjSymbolList.Count-1 do
  675. begin
  676. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  677. if objsym.bind=AB_EXTERNAL then
  678. begin
  679. ExternalNameElem:=TOmfExternalNameElement.Create(ExtNames,objsym.Name);
  680. objsym.symidx:=idx;
  681. Inc(idx);
  682. end;
  683. end;
  684. if ExtNames.Count>0 then
  685. begin
  686. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  687. ExtDefRec.ExternalNames:=ExtNames;
  688. while ExtDefRec.NextIndex<ExtDefRec.ExternalNames.Count do
  689. begin
  690. ExtDefRec.EncodeTo(RawRecord);
  691. RawRecord.WriteTo(FWriter);
  692. end;
  693. ExtDefRec.Free;
  694. end;
  695. ExtNames.Free;
  696. RawRecord.Free;
  697. end;
  698. function TOmfObjOutput.writeData(Data:TObjData):boolean;
  699. var
  700. RawRecord: TOmfRawRecord;
  701. Header: TOmfRecord_THEADR;
  702. Translator_COMENT: TOmfRecord_COMENT;
  703. LinkPassSeparator_COMENT: TOmfRecord_COMENT;
  704. LNamesRec: TOmfRecord_LNAMES;
  705. ModEnd: TOmfRecord_MODEND;
  706. I: Integer;
  707. SegDef: TOmfRecord_SEGDEF;
  708. GrpDef: TOmfRecord_GRPDEF;
  709. DGroupSegments: TSegmentList;
  710. nsections: Integer;
  711. begin
  712. { calc amount of sections we have and set their index, starting with 1 }
  713. nsections:=1;
  714. data.ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  715. { maximum amount of sections supported in the omf format is $7fff }
  716. if (nsections-1)>$7fff then
  717. internalerror(2015040701);
  718. { write header record }
  719. RawRecord:=TOmfRawRecord.Create;
  720. Header:=TOmfRecord_THEADR.Create;
  721. Header.ModuleName:=Data.Name;
  722. Header.EncodeTo(RawRecord);
  723. RawRecord.WriteTo(FWriter);
  724. Header.Free;
  725. { write translator COMENT header }
  726. Translator_COMENT:=TOmfRecord_COMENT.Create;
  727. Translator_COMENT.CommentClass:=CC_Translator;
  728. Translator_COMENT.CommentString:='FPC '+full_version_string+
  729. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  730. Translator_COMENT.EncodeTo(RawRecord);
  731. RawRecord.WriteTo(FWriter);
  732. Translator_COMENT.Free;
  733. LNames.Clear;
  734. LNames.Add(''); { insert an empty string, which has index 1 }
  735. FSegments.Clear;
  736. FSegments.Add('',nil);
  737. FGroups.Clear;
  738. FGroups.Add('',nil);
  739. for i:=0 to Data.ObjSectionList.Count-1 do
  740. with TOmfObjSection(Data.ObjSectionList[I]) do
  741. AddSegment(Name,ClassName,OverlayName,OmfAlignment,Combination,Use,Size);
  742. { create group "dgroup" }
  743. SetLength(DGroupSegments,0);
  744. for i:=0 to Data.ObjSectionList.Count-1 do
  745. with TOmfObjSection(Data.ObjSectionList[I]) do
  746. if PrimaryGroup='dgroup' then
  747. begin
  748. SetLength(DGroupSegments,Length(DGroupSegments)+1);
  749. DGroupSegments[High(DGroupSegments)]:=index;
  750. end;
  751. AddGroup('dgroup',DGroupSegments);
  752. { write LNAMES record(s) }
  753. LNamesRec:=TOmfRecord_LNAMES.Create;
  754. LNamesRec.Names:=LNames;
  755. while LNamesRec.NextIndex<=LNames.Count do
  756. begin
  757. LNamesRec.EncodeTo(RawRecord);
  758. RawRecord.WriteTo(FWriter);
  759. end;
  760. LNamesRec.Free;
  761. { write SEGDEF record(s) }
  762. for I:=1 to Segments.Count-1 do
  763. begin
  764. SegDef:=TOmfRecord_SEGDEF(Segments[I]);
  765. SegDef.EncodeTo(RawRecord);
  766. RawRecord.WriteTo(FWriter);
  767. end;
  768. { write GRPDEF record(s) }
  769. for I:=1 to Groups.Count-1 do
  770. begin
  771. GrpDef:=TOmfRecord_GRPDEF(Groups[I]);
  772. GrpDef.EncodeTo(RawRecord);
  773. RawRecord.WriteTo(FWriter);
  774. end;
  775. { write PUBDEF record(s) }
  776. WritePUBDEFs(Data);
  777. { write EXTDEF record(s) }
  778. WriteEXTDEFs(Data);
  779. { write link pass separator }
  780. LinkPassSeparator_COMENT:=TOmfRecord_COMENT.Create;
  781. LinkPassSeparator_COMENT.CommentClass:=CC_LinkPassSeparator;
  782. LinkPassSeparator_COMENT.CommentString:=#1;
  783. LinkPassSeparator_COMENT.NoList:=True;
  784. LinkPassSeparator_COMENT.EncodeTo(RawRecord);
  785. RawRecord.WriteTo(FWriter);
  786. LinkPassSeparator_COMENT.Free;
  787. { write section content, interleaved with fixups }
  788. WriteSections(Data);
  789. { write MODEND record }
  790. ModEnd:=TOmfRecord_MODEND.Create;
  791. ModEnd.EncodeTo(RawRecord);
  792. RawRecord.WriteTo(FWriter);
  793. ModEnd.Free;
  794. RawRecord.Free;
  795. result:=true;
  796. end;
  797. constructor TOmfObjOutput.create(AWriter:TObjectWriter);
  798. begin
  799. inherited create(AWriter);
  800. cobjdata:=TOmfObjData;
  801. FLNames:=TOmfOrderedNameCollection.Create;
  802. FSegments:=TFPHashObjectList.Create;
  803. FSegments.Add('',nil);
  804. FGroups:=TFPHashObjectList.Create;
  805. FGroups.Add('',nil);
  806. end;
  807. destructor TOmfObjOutput.Destroy;
  808. begin
  809. FGroups.Free;
  810. FSegments.Free;
  811. FLNames.Free;
  812. inherited Destroy;
  813. end;
  814. {****************************************************************************
  815. TOmfObjInput
  816. ****************************************************************************}
  817. function TOmfObjInput.ReadLNames(RawRec: TOmfRawRecord): Boolean;
  818. var
  819. LNamesRec: TOmfRecord_LNAMES;
  820. begin
  821. Result:=False;
  822. LNamesRec:=TOmfRecord_LNAMES.Create;
  823. LNamesRec.Names:=LNames;
  824. LNamesRec.DecodeFrom(RawRec);
  825. LNamesRec.Free;
  826. Result:=True;
  827. end;
  828. constructor TOmfObjInput.create;
  829. begin
  830. inherited create;
  831. cobjdata:=TOmfObjData;
  832. FLNames:=TOmfOrderedNameCollection.Create;
  833. FRawRecord:=TOmfRawRecord.Create;
  834. end;
  835. destructor TOmfObjInput.destroy;
  836. begin
  837. FRawRecord.Free;
  838. FLNames.Free;
  839. inherited destroy;
  840. end;
  841. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  842. var
  843. b: Byte;
  844. begin
  845. result:=false;
  846. if AReader.Read(b,sizeof(b)) then
  847. begin
  848. if b=RT_THEADR then
  849. { TODO: check additional fields }
  850. result:=true;
  851. end;
  852. AReader.Seek(0);
  853. end;
  854. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  855. begin
  856. FReader:=AReader;
  857. InputFileName:=AReader.FileName;
  858. objdata:=CObjData.Create(InputFileName);
  859. result:=false;
  860. LNames.Clear;
  861. FRawRecord.ReadFrom(FReader);
  862. if not FRawRecord.VerifyChecksumByte then
  863. begin
  864. InputError('Invalid checksum in OMF record');
  865. exit;
  866. end;
  867. if FRawRecord.RecordType<>RT_THEADR then
  868. begin
  869. InputError('Can''t read OMF header');
  870. exit;
  871. end;
  872. repeat
  873. FRawRecord.ReadFrom(FReader);
  874. if not FRawRecord.VerifyChecksumByte then
  875. begin
  876. InputError('Invalid checksum in OMF record');
  877. exit;
  878. end;
  879. case FRawRecord.RecordType of
  880. RT_LNAMES:
  881. if not ReadLNames(FRawRecord) then
  882. exit;
  883. RT_SEGDEF,RT_SEGDEF32:
  884. begin
  885. {todo}
  886. end;
  887. RT_GRPDEF:
  888. begin
  889. {todo}
  890. end;
  891. RT_COMENT:
  892. begin
  893. {todo}
  894. end;
  895. RT_EXTDEF:
  896. begin
  897. {todo}
  898. end;
  899. RT_PUBDEF,RT_PUBDEF32:
  900. begin
  901. {todo}
  902. end;
  903. RT_LEDATA,RT_LEDATA32:
  904. begin
  905. {todo}
  906. end;
  907. RT_FIXUPP,RT_FIXUPP32:
  908. begin
  909. {todo}
  910. end;
  911. RT_MODEND,RT_MODEND32:
  912. begin
  913. {todo}
  914. end;
  915. else
  916. begin
  917. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  918. exit;
  919. end;
  920. end;
  921. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  922. end;
  923. {****************************************************************************
  924. TMZExeOutput
  925. ****************************************************************************}
  926. constructor TMZExeOutput.create;
  927. begin
  928. inherited create;
  929. CObjData:=TOmfObjData;
  930. end;
  931. {****************************************************************************
  932. TOmfAssembler
  933. ****************************************************************************}
  934. constructor TOmfAssembler.Create(smart:boolean);
  935. begin
  936. inherited Create(smart);
  937. CObjOutput:=TOmfObjOutput;
  938. CInternalAr:=TOmfLibObjectWriter;
  939. end;
  940. {*****************************************************************************
  941. Initialize
  942. *****************************************************************************}
  943. {$ifdef i8086}
  944. const
  945. as_i8086_omf_info : tasminfo =
  946. (
  947. id : as_i8086_omf;
  948. idtxt : 'OMF';
  949. asmbin : '';
  950. asmcmd : '';
  951. supported_targets : [system_i8086_msdos];
  952. flags : [af_outputbinary,af_no_debug];
  953. labelprefix : '..@';
  954. comment : '; ';
  955. dollarsign: '$';
  956. );
  957. {$endif i8086}
  958. initialization
  959. {$ifdef i8086}
  960. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  961. {$endif i8086}
  962. end.