ogomf.pas 39 KB

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