ogomf.pas 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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. if SegDefRec.SegmentLength>High(objsec.Size) then
  898. begin
  899. InputError('Segment too large');
  900. SegDefRec.Free;
  901. exit;
  902. end;
  903. objsec.Size:=SegDefRec.SegmentLength;
  904. SegDefRec.Free;
  905. Result:=True;
  906. end;
  907. function TOmfObjInput.ReadGrpDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  908. var
  909. GrpDefRec: TOmfRecord_GRPDEF;
  910. GroupName: string;
  911. SecGroup: TObjSectionGroup;
  912. i,SegIndex: Integer;
  913. begin
  914. Result:=False;
  915. GrpDefRec:=TOmfRecord_GRPDEF.Create;
  916. GrpDefRec.DecodeFrom(RawRec);
  917. if (GrpDefRec.GroupNameIndex<1) or (GrpDefRec.GroupNameIndex>LNames.Count) then
  918. begin
  919. InputError('Group name index out of range');
  920. GrpDefRec.Free;
  921. exit;
  922. end;
  923. GroupName:=LNames[GrpDefRec.GroupNameIndex];
  924. SecGroup:=objdata.createsectiongroup(GroupName);
  925. SetLength(SecGroup.members,Length(GrpDefRec.SegmentList));
  926. for i:=0 to Length(GrpDefRec.SegmentList)-1 do
  927. begin
  928. SegIndex:=GrpDefRec.SegmentList[i];
  929. if (SegIndex<1) or (SegIndex>objdata.ObjSectionList.Count) then
  930. begin
  931. InputError('Segment name index out of range in group definition');
  932. GrpDefRec.Free;
  933. exit;
  934. end;
  935. SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
  936. end;
  937. GrpDefRec.Free;
  938. Result:=True;
  939. end;
  940. constructor TOmfObjInput.create;
  941. begin
  942. inherited create;
  943. cobjdata:=TOmfObjData;
  944. FLNames:=TOmfOrderedNameCollection.Create;
  945. FRawRecord:=TOmfRawRecord.Create;
  946. end;
  947. destructor TOmfObjInput.destroy;
  948. begin
  949. FRawRecord.Free;
  950. FLNames.Free;
  951. inherited destroy;
  952. end;
  953. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  954. var
  955. b: Byte;
  956. begin
  957. result:=false;
  958. if AReader.Read(b,sizeof(b)) then
  959. begin
  960. if b=RT_THEADR then
  961. { TODO: check additional fields }
  962. result:=true;
  963. end;
  964. AReader.Seek(0);
  965. end;
  966. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  967. begin
  968. FReader:=AReader;
  969. InputFileName:=AReader.FileName;
  970. objdata:=CObjData.Create(InputFileName);
  971. result:=false;
  972. LNames.Clear;
  973. FRawRecord.ReadFrom(FReader);
  974. if not FRawRecord.VerifyChecksumByte then
  975. begin
  976. InputError('Invalid checksum in OMF record');
  977. exit;
  978. end;
  979. if FRawRecord.RecordType<>RT_THEADR then
  980. begin
  981. InputError('Can''t read OMF header');
  982. exit;
  983. end;
  984. repeat
  985. FRawRecord.ReadFrom(FReader);
  986. if not FRawRecord.VerifyChecksumByte then
  987. begin
  988. InputError('Invalid checksum in OMF record');
  989. exit;
  990. end;
  991. case FRawRecord.RecordType of
  992. RT_LNAMES:
  993. if not ReadLNames(FRawRecord) then
  994. exit;
  995. RT_SEGDEF,RT_SEGDEF32:
  996. if not ReadSegDef(FRawRecord,objdata) then
  997. exit;
  998. RT_GRPDEF:
  999. if not ReadGrpDef(FRawRecord,objdata) then
  1000. exit;
  1001. RT_COMENT:
  1002. begin
  1003. {todo}
  1004. end;
  1005. RT_EXTDEF:
  1006. begin
  1007. {todo}
  1008. end;
  1009. RT_PUBDEF,RT_PUBDEF32:
  1010. begin
  1011. {todo}
  1012. end;
  1013. RT_LEDATA,RT_LEDATA32:
  1014. begin
  1015. {todo}
  1016. end;
  1017. RT_FIXUPP,RT_FIXUPP32:
  1018. begin
  1019. {todo}
  1020. end;
  1021. RT_MODEND,RT_MODEND32:
  1022. begin
  1023. {todo}
  1024. end;
  1025. else
  1026. begin
  1027. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  1028. exit;
  1029. end;
  1030. end;
  1031. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  1032. end;
  1033. {****************************************************************************
  1034. TMZExeOutput
  1035. ****************************************************************************}
  1036. constructor TMZExeOutput.create;
  1037. begin
  1038. inherited create;
  1039. CObjData:=TOmfObjData;
  1040. end;
  1041. {****************************************************************************
  1042. TOmfAssembler
  1043. ****************************************************************************}
  1044. constructor TOmfAssembler.Create(smart:boolean);
  1045. begin
  1046. inherited Create(smart);
  1047. CObjOutput:=TOmfObjOutput;
  1048. CInternalAr:=TOmfLibObjectWriter;
  1049. end;
  1050. {*****************************************************************************
  1051. Initialize
  1052. *****************************************************************************}
  1053. {$ifdef i8086}
  1054. const
  1055. as_i8086_omf_info : tasminfo =
  1056. (
  1057. id : as_i8086_omf;
  1058. idtxt : 'OMF';
  1059. asmbin : '';
  1060. asmcmd : '';
  1061. supported_targets : [system_i8086_msdos];
  1062. flags : [af_outputbinary,af_no_debug];
  1063. labelprefix : '..@';
  1064. comment : '; ';
  1065. dollarsign: '$';
  1066. );
  1067. {$endif i8086}
  1068. initialization
  1069. {$ifdef i8086}
  1070. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  1071. {$endif i8086}
  1072. end.