ogmacho.pas 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. {
  2. Copyright (c) 2009-2010 by Dmitry Boyarintsev
  3. Contains the binary mach-o writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit ogmacho;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. cclasses,
  22. globals, globtype, verbose,
  23. owbase, ogbase,
  24. aasmbase, assemble,
  25. macho, machoutils,
  26. systems,
  27. { assembler }
  28. cpuinfo,cpubase,aasmtai,aasmdata; {for system constants}
  29. type
  30. { TMachoRawWriter }
  31. TMachoRawWriter=class(TRawWriter)
  32. private
  33. fwriter : tobjectwriter;
  34. public
  35. constructor Create(awriter: tobjectwriter);
  36. procedure WriteRaw(const data; datasize: Integer); override;
  37. end;
  38. { TmachoObjSection }
  39. TMachoSectionType=(mst_Normal, mst_ObjC, mst_Stabs, mst_Dwarf);
  40. TmachoObjSection=class(tObjSection)
  41. public
  42. nmsegment : string; {mach-o segment name}
  43. nmsection : string; {mach-o section name}
  44. inSegIdx : Integer; {section index inside segment. one-based number}
  45. RelocOfs : aword; {file offset to the first relocation symbol}
  46. IndIndex : Integer; {index in indirect table (see DysymTableCommand) for lazy and non-lazy symbol pointers}
  47. machoSec : TMachoSectionType;
  48. function GetRelocCount: Integer;
  49. function FileSize: Integer;
  50. constructor create(AList:TFPHashObjectList; const Aname:string; Aalign:shortint; Aoptions:TObjSectionOptions);override;
  51. end;
  52. { TmachoObjData }
  53. TmachoObjData=class(TObjData)
  54. public
  55. debugcount: Integer;
  56. constructor create(const n:string); override;
  57. procedure CreateDebugSections; override;
  58. function sectionname(atype:TAsmSectiontype; const aname:string; aorder:TAsmSectionOrder):string;override;
  59. function sectiontype2align(atype:TAsmSectiontype):shortint;override;
  60. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;override;
  61. procedure writereloc(data:aint; len:aword; p:TObjSymbol; reltype:TObjRelocationType);override;
  62. public
  63. end;
  64. { TMachoObjectOutput }
  65. TMachoSymbolLocation=(loc_Notused, loc_Local, loc_External, loc_Undef);
  66. TMachoObjectOutput=class(TObjOutput)
  67. private
  68. machoData : TMachoObjData;
  69. mfile : TMachOWriter;
  70. cputarget : cpu_type_t;
  71. stabsec : TmachoObjSection;
  72. strsec : TmachoObjSection;
  73. sectionscnt : integer;
  74. memofs : aword;
  75. fileofs : aword;
  76. symstrofs : aword;
  77. symlen : aword;
  78. symCount : aint;
  79. iLocal : Integer;
  80. iExtern : Integer;
  81. iUndef : Integer;
  82. iIndir : Integer;
  83. symList : TFPObjectList;
  84. IndirIndex : tdynamicarray;
  85. relcount : integer;
  86. protected
  87. procedure TrailZeros;
  88. {sections}
  89. procedure FixSectionRelocs(s: TMachoObjSection);
  90. procedure section_count_sections(p:TObject;arg:pointer);
  91. procedure section_set_datamempos(p:TObject;arg:pointer);
  92. procedure section_set_relocpos(p:TObject;arg:pointer);
  93. procedure section_write_data(p:TObject;arg:pointer);
  94. procedure section_write_relocdata(p:TObject;arg:pointer);
  95. procedure section_prepare_indirect(s: TObjSection);
  96. {symbols}
  97. procedure symbol_write_nlist(sym:TObjSymbol; symstr: tdynamicarray);
  98. function dysymbol_location(sym: TObjSymbol): TMachoSymbolLocation;
  99. function symWriteName(s: TObjSymbol): string;
  100. procedure InitSymbolIndexes(var sCount: aint; var symStrLen: aword);
  101. {mach-o file related}
  102. procedure writeSectionsHeader(s: TMachoObjSection);
  103. procedure writeSymTabCommand;
  104. procedure writeSymbols(symstr: tdynamicarray);
  105. procedure writeDySymTabCommand(IndOffset: aword; IndCount: Integer);
  106. procedure writeDysymbols;
  107. function writedata(data:TObjData):boolean;override;
  108. public
  109. constructor Create(AWriter:TObjectWriter);override;
  110. end;
  111. { TMachoAssembler }
  112. TMachoAssembler=class(TInternalAssembler)
  113. public
  114. constructor create(info: pasminfo; smart:boolean);override;
  115. end;
  116. implementation
  117. uses
  118. owar;
  119. { TmachoObjData }
  120. constructor TmachoObjData.create(const n: string);
  121. begin
  122. inherited create(n);
  123. CObjSection:=TmachoObjSection;
  124. end;
  125. { TmachoObjData.CreateDebugSections. }
  126. { note: mach-o file has specific symbol table command (not sections) to keep symbols and symbol string }
  127. procedure TmachoObjData.CreateDebugSections;
  128. begin
  129. inherited CreateDebugSections;
  130. if target_dbg.id=dbg_stabs then
  131. begin
  132. stabssec:=createsection(sec_stab);
  133. stabstrsec:=createsection(sec_stabstr);
  134. end;
  135. end;
  136. function TmachoObjData.sectionname(atype: TAsmSectiontype; const aname: string; aorder: TAsmSectionOrder): string;
  137. const
  138. DwarfSect : array [sec_debug_frame..sec_debug_abbrev] of string
  139. = ('sec_debug_frame','__debug_info','__debug_line','__debug_abbrev');
  140. begin
  141. case atype of
  142. sec_user: Result:=aname;
  143. sec_bss: Result:=MakeSectionName(seg_DATA, '__common');
  144. sec_stab: Result:='.stabs';
  145. sec_stabstr: Result:='.stabsstr';
  146. sec_fpc: Result:=MakeSectionName(seg_TEXT, '.fpc');
  147. sec_stub: Result:=MakeSectionName(seg_IMPORT, '__jump_table');
  148. sec_code:
  149. if (aname='fpc_geteipasebx') or
  150. (aname='fpc_geteipasecx') then
  151. Result:=MakeSectionName(seg_TEXT, '__textcoal_nt')
  152. else
  153. Result:=MakeSectionName(seg_TEXT, '__text');
  154. sec_rodata_norel: Result:=MakeSectionName(seg_TEXT, '__const'); {.const}
  155. sec_rodata: Result:=MakeSectionName(seg_DATA, '__const');
  156. sec_data: Result:=MakeSectionName(seg_DATA, '__data');
  157. sec_data_nonlazy: Result:=MakeSectionName(seg_DATA, '__nl_symbol_ptr');
  158. sec_data_lazy: Result:=MakeSectionName(seg_DATA, '__la_symbol_ptr');
  159. sec_init_func: Result:=MakeSectionName(seg_DATA, '__mod_init_func');
  160. sec_term_func: Result:=MakeSectionName(seg_DATA, '__mod_term_func');
  161. sec_objc_class: Result:='__OBJC __class';
  162. sec_objc_meta_class: Result:='__OBJC __meta_class';
  163. sec_objc_cat_cls_meth: Result:='__OBJC __cat_cls_meth';
  164. sec_objc_cat_inst_meth: Result:='__OBJC __cat_inst_meth';
  165. sec_objc_protocol: Result:='__OBJC __protocol';
  166. sec_objc_string_object: Result:='__OBJC __cstring';
  167. sec_objc_cls_meth: Result:='__OBJC __cls_meth';
  168. sec_objc_inst_meth: Result:='__OBJC __inst_meth';
  169. sec_objc_cls_refs: Result:='__OBJC __cls_refs';
  170. sec_objc_message_refs: Result:='__OBJC __message_refs';
  171. sec_objc_symbols: Result:='__OBJC __symbols';
  172. sec_objc_category: Result:='__OBJC __categories';
  173. sec_objc_class_vars: Result:='__OBJC __cls_vars';
  174. sec_objc_instance_vars: Result:='__OBJC __inst_vars';
  175. sec_objc_module_info: Result := '__OBJC __module_info';
  176. sec_objc_class_names: Result:='__TEXT __cstring';
  177. sec_objc_meth_var_types: Result:='__OBJC __var_types';
  178. sec_objc_meth_var_names: Result:='__TEXT __cstring';
  179. sec_objc_selector_strs: Result:='__TEXT __cstring';
  180. sec_objc_protocol_ext: Result:='__OBJC __protocol_ext';
  181. sec_objc_class_ext: Result:='__OBJC __class_ext';
  182. sec_objc_property: Result:='__OBJC __property';
  183. sec_objc_image_info: Result:='__OBJC __image_info';
  184. sec_objc_cstring_object: Result:='__OBJC __cstring_object';
  185. sec_objc_sel_fixup: Result:='__OBJC __sel_fixup';
  186. { Objective-C non-fragile ABI }
  187. sec_objc_data: Result:='__OBJC __data';
  188. sec_objc_const: Result:='__OBJC __const';
  189. sec_objc_sup_refs: Result:='__OBJC __supc_refs';
  190. sec_objc_classlist: Result:='__OBJC __classlist';
  191. sec_objc_nlclasslist: Result:='__OBJC __nlclasslist';
  192. sec_objc_catlist: Result:='__OBJC __catlist';
  193. sec_objc_nlcatlist: Result:='__OBJC __nlcatlist';
  194. sec_objc_protolist: Result:='__OBJC __protolist';
  195. sec_debug_frame,
  196. sec_debug_info,
  197. sec_debug_line,
  198. sec_debug_abbrev:
  199. Result:=MakeSectionName(seg_DWARF, DwarfSect[atype])
  200. else
  201. Result:=MakeSectionName(seg_DATA, '__data');
  202. end;
  203. end;
  204. procedure TmachoObjData.writereloc(data: aint; len: aword; p: TObjSymbol; reltype: TObjRelocationType);
  205. var
  206. symaddr : longint;
  207. begin
  208. {stabs relocation}
  209. case TMachoObjSection(CurrObjSec).machoSec of
  210. mst_Stabs:
  211. begin
  212. if Assigned(p) then
  213. begin
  214. data:=p.address;
  215. CurrObjSec.addsymreloc(CurrObjSec.Size,p,reltype);
  216. end;
  217. CurrObjSec.write(data, len);
  218. end;
  219. mst_Dwarf:
  220. begin
  221. if Assigned(p) then
  222. begin
  223. CurrObjSec.addsectionReloc(CurrObjSec.Size,p.objsection,reltype);
  224. data:=p.address;
  225. end;
  226. CurrObjSec.write(data, len);
  227. end;
  228. else
  229. if assigned(p) then
  230. begin
  231. { real address of the symbol }
  232. symaddr:=p.address;
  233. { Local ObjSymbols can be resolved already or need a section reloc }
  234. if (p.bind=AB_LOCAL) and
  235. (reltype in [RELOC_RELATIVE,RELOC_ABSOLUTE{$ifdef x86_64},RELOC_ABSOLUTE32{$endif x86_64}]) then
  236. begin
  237. { For a reltype relocation in the same section the value can be calculated }
  238. if (p.objsection=CurrObjSec) and
  239. (reltype=RELOC_RELATIVE) then
  240. inc(data,symaddr-len-CurrObjSec.Size)
  241. else
  242. begin
  243. if (p.typ=AT_NONE) then
  244. begin
  245. {undefined symbol, using section}
  246. CurrObjSec.addsectionreloc(CurrObjSec.Size,p.objsection,reltype);
  247. data:=symaddr-len-CurrObjSec.Size;
  248. end
  249. else
  250. begin
  251. CurrObjSec.addsymreloc(CurrObjSec.Size,p,reltype);
  252. if Assigned(p.objsection) and
  253. (p.objsection.Name='__TEXT __textcoal_nt') then
  254. data:=symaddr-len-CurrObjSec.Size
  255. else
  256. data:=p.objsection.Size;
  257. end;
  258. end;
  259. end
  260. else if (p.bind=AB_GLOBAL) and
  261. not Assigned(p.indsymbol) and
  262. (reltype<>RELOC_PIC_PAIR) then
  263. begin
  264. CurrObjSec.addsectionreloc(CurrObjSec.Size,p.objsection,reltype);
  265. data:=p.address;
  266. end
  267. else
  268. CurrObjSec.addsymreloc(CurrObjSec.Size,p,reltype);
  269. end; {if assigned(p) }
  270. CurrObjSec.write(data, len);
  271. end;
  272. end;
  273. function TmachoObjData.sectiontype2align(atype: TAsmSectiontype): shortint;
  274. begin
  275. case atype of
  276. sec_bss:
  277. Result:=4;
  278. sec_stabstr, sec_stab:
  279. Result:=1;
  280. sec_stub, sec_data_lazy, sec_data_nonlazy:
  281. Result:=4;
  282. else
  283. Result:=inherited sectiontype2align(atype);
  284. end;
  285. end;
  286. function TmachoObjData.sectiontype2options(atype: TAsmSectiontype): TObjSectionOptions;
  287. begin
  288. case atype of
  289. sec_objc_meth_var_names,
  290. sec_objc_class_names: Result:=[oso_data, oso_load];
  291. else
  292. Result:=inherited sectiontype2options(atype);
  293. end
  294. end;
  295. { TMachoAssembler }
  296. constructor TMachoAssembler.create(info: pasminfo; smart: boolean);
  297. begin
  298. inherited;
  299. CObjOutput:=TMachoObjectOutput;
  300. CInternalAr:=tarobjectwriter;
  301. end;
  302. { TMachoObjectOutput }
  303. procedure TMachoObjectOutput.FixSectionRelocs(s: TMachoObjSection);
  304. var
  305. i : integer;
  306. ro : TObjRelocation;
  307. dw : aword;
  308. begin
  309. {todo: is it I386 only core}
  310. if not Assigned(s.Data) then
  311. Exit;
  312. for i:=0 to s.ObjRelocations.Count-1 do
  313. begin
  314. ro:=TObjRelocation(s.ObjRelocations[i]);
  315. if (Assigned(ro.objsection)) and
  316. (ro.objsection.Name='__TEXT __textcoal_nt') then
  317. Continue;
  318. if Assigned(ro.objsection) then
  319. begin
  320. s.Data.seek(ro.DataOffset);
  321. s.Data.read(dw, sizeof(aword));
  322. dw:=dw+ro.objsection.MemPos;
  323. s.Data.seek(ro.DataOffset);
  324. s.Data.write(dw, sizeof(aword));
  325. end
  326. else
  327. begin
  328. if ro.symbol.Name='fpc_geteipasebx' then
  329. Continue;
  330. if Assigned(ro.symbol.indsymbol) or
  331. (ro.typ=RELOC_PIC_PAIR) then
  332. begin
  333. s.Data.seek(ro.DataOffset);
  334. s.Data.read(dw, sizeof(aword));
  335. dw:=ro.symbol.address-dw;
  336. s.Data.seek(ro.DataOffset);
  337. s.Data.write(dw, sizeof(aword));
  338. end
  339. else if (ro.symbol.bind=AB_LOCAL) then
  340. begin
  341. dw:=ro.symbol.address;
  342. s.Data.seek(ro.DataOffset);
  343. s.Data.write(dw, sizeof(aword));
  344. end;
  345. end;
  346. end;
  347. s.Data.seek(s.Data.Size);
  348. end;
  349. procedure TMachoObjectOutput.section_count_sections(p: TObject; arg: pointer);
  350. var
  351. s : TMachoObjSection;
  352. begin
  353. s:=TMachoObjSection(p);
  354. if s.machoSec=mst_Stabs then
  355. Exit;
  356. inc(sectionscnt);
  357. s.inSegIdx:=sectionscnt;
  358. end;
  359. procedure TMachoObjectOutput.section_set_datamempos(p: TObject; arg: pointer);
  360. var
  361. s : TMachoObjSection;
  362. begin
  363. s:=TMachoObjSection(p);
  364. if s.machoSec=mst_Stabs then
  365. Exit;
  366. s.setDataPos(fileofs);
  367. s.setMemPos(memofs);
  368. memofs:=Align(memofs+s.Size, s.SecAlign);
  369. fileofs:=AlignAddr(cputarget, fileofs);
  370. end;
  371. procedure TMachoObjectOutput.section_set_relocpos(p:TObject;arg:pointer);
  372. var
  373. s : TMachoObjSection;
  374. sz : Integer;
  375. begin
  376. s:=TMachoObjSection(p);
  377. if s.machoSec=mst_Stabs then
  378. Exit;
  379. sz:=s.GetRelocCount * sizeof(relocation_info);
  380. if sz > 0 then
  381. begin
  382. s.relocofs:=fileofs;
  383. inc(fileofs, sz);
  384. fileofs:=AlignAddr(cputarget, fileofs);
  385. end;
  386. end;
  387. procedure TMachoObjectOutput.section_write_data(p: TObject; arg: pointer);
  388. var
  389. s : TMachoObjSection;
  390. begin
  391. s:=TMachoObjSection(p);
  392. if s.machoSec=mst_Stabs then
  393. Exit;
  394. Writer.writezeros(s.DataAlignBytes);
  395. FixSectionRelocs(s);
  396. if s.Datapos<>FWriter.ObjSize then
  397. InternalError(200903101);
  398. if Assigned(s.data) then
  399. Writer.writearray(s.data);
  400. TrailZeros;
  401. end;
  402. procedure TMachoObjectOutput.section_write_relocdata(p: TObject; arg: pointer);
  403. var
  404. s : TMachoObjSection;
  405. symsec : TMachoObjSection;
  406. i : Integer;
  407. dw : aword;
  408. r : relocation_info;
  409. sr : scattered_relocation_info;
  410. ro : TObjRelocation;
  411. symnum : Integer;
  412. relpc : Boolean;
  413. relextern : Boolean;
  414. reltype : Integer;
  415. begin
  416. s:=TMachoObjSection(p);
  417. {stabs relocation should not present in relocation table}
  418. if s.machoSec=mst_Stabs then
  419. Exit;
  420. {no relocation for the section}
  421. if s.relocofs=0 then
  422. Exit;
  423. {check file alignment}
  424. if s.relocofs<>FWriter.ObjSize then
  425. InternalError(200903102); {file misalignment}
  426. relcount:=s.ObjRelocations.Count;
  427. {the reversed order, is only to be alike Apple linker}
  428. for i:=s.ObjRelocations.Count-1 downto 0 do
  429. begin
  430. ro:=TObjRelocation(s.ObjRelocations[i]);
  431. {in-section relocation}
  432. if ro.symbol=nil then
  433. begin
  434. relextern:=false;
  435. relpc:=false;
  436. symnum:=TmachoObjSection(ro.objsection).inSegIdx;
  437. case ro.typ of
  438. RELOC_ABSOLUTE:
  439. begin
  440. RelocInfo(ro.DataOffset, symnum, GENERIC_RELOC_VANILLA, ril_long, relpc, relextern, r);
  441. mfile.WriteRelocation(r);
  442. end;
  443. else
  444. relpc:=ro.typ=RELOC_RELATIVE;
  445. RelocInfo(ro.DataOffset, symnum, GENERIC_RELOC_VANILLA, ril_long, relpc, relextern, r);
  446. mfile.WriteRelocation(r);
  447. end;
  448. end
  449. else
  450. begin
  451. symsec:=TMachoObjSection(ro.symbol.objsection);
  452. if Assigned(symsec) and
  453. (symsec.Name='__TEXT __textcoal_nt') then
  454. begin
  455. relextern:=true;
  456. symnum:=ro.symbol.symidx;
  457. end
  458. else if ro.symbol.bind=AB_EXTERNAL then
  459. begin
  460. relextern:=true;
  461. symnum:=ro.symbol.symidx;
  462. end
  463. else if Assigned(ro.symbol.objsection) and
  464. (ro.symbol.bind=AB_LOCAL) and
  465. (ro.symbol.typ=AT_DATA) then
  466. begin
  467. relextern:=false;
  468. symnum:=TMachoObjSection(ro.symbol.objsection).inSegIdx;
  469. end
  470. else if (ro.symbol.bind=AB_LOCAL) or
  471. (ro.symbol.typ=AT_NONE) then
  472. begin
  473. relextern:=false;
  474. symnum:=s.inSegIdx
  475. end
  476. else
  477. begin
  478. relextern:=true;
  479. symnum:=ro.symbol.symidx;
  480. end;
  481. relpc:=false;
  482. relpc:=(ro.typ=RELOC_RELATIVE);
  483. if (ro.typ=RELOC_PIC_PAIR) then
  484. begin
  485. if ro.symbol.bind=AB_LOCAL then
  486. reltype:=GENERIC_RELOC_LOCAL_SECTDIFF
  487. else
  488. reltype:=GENERIC_RELOC_SECTDIFF;
  489. ScatterRelocInfo(ro.symbol.address, ro.DataOffset, reltype, ril_long, false, sr);
  490. mfile.WriteScatterReloc(sr);
  491. { the section data is already fixed to: ro.SymbolOffset - Label.Offset }
  492. s.Data.seek(ro.DataOffset);
  493. s.Data.read(dw, sizeof(aword));
  494. dw:=ro.symbol.address-dw;
  495. ScatterRelocInfo(dw, 0, GENERIC_RELOC_PAIR, ril_long, false, sr);
  496. mfile.WriteScatterReloc(sr);
  497. end
  498. else
  499. begin
  500. RelocInfo(ro.DataOffset, symnum, GENERIC_RELOC_VANILLA, ril_long, relpc, relextern, r);
  501. mfile.WriteRelocation(r);
  502. end
  503. end;
  504. if Assigned(s.Data) then
  505. s.Data.seek(s.Data.size);
  506. end;
  507. TrailZeros;
  508. end;
  509. procedure TMachoObjectOutput.section_prepare_indirect(s: TObjSection);
  510. var
  511. t : TObjSymbol;
  512. i : Integer;
  513. anysym : Boolean;
  514. begin
  515. if TmachoObjSection(s).machoSec=mst_Stabs then
  516. Exit;
  517. anysym:=false;
  518. for i:=0 to machoData.ObjSymbolList.Count-1 do
  519. begin
  520. t:=TObjSymbol(machoData.ObjSymbolList[i]);
  521. if (t.objsection=s) and Assigned(t.indsymbol) then
  522. begin
  523. if not anysym then
  524. begin
  525. {remember the index of the first indirect symbol. Will be used later at section header writting}
  526. TmachoObjSection(s).indIndex:=IndirIndex.size div SizeOf(Integer);
  527. anysym:=true;
  528. end;
  529. IndirIndex.write(t.symidx, sizeof(Integer));
  530. end;
  531. end;
  532. end;
  533. procedure TMachoObjectOutput.symbol_write_nlist(sym:TObjSymbol; symstr: tdynamicarray);
  534. var
  535. n : nlist_64;
  536. sec : TmachoObjSection;
  537. begin
  538. sec:=TMachoObjSection(sym.objsection);
  539. FillChar(n, sizeof(n), 0);
  540. n.n_un.n_strx:=symstr.size;
  541. symstr.writestr(sym.Name+#0);
  542. if assigned(sec) and
  543. (sec.machoSec=mst_ObjC) and
  544. (sec.nmsection='__module_info') then
  545. begin
  546. n.n_type:=N_ABS or N_EXT;
  547. mfile.WriteNList(n);
  548. Exit;
  549. end;
  550. if (sym.typ=AT_NONE) then
  551. begin
  552. n.n_value:=0;
  553. if sym.bind<>AB_EXTERNAL then
  554. n.n_desc:=n.n_desc or REFERENCE_FLAG_UNDEFINED_LAZY;
  555. n.n_type:=n.n_type or N_EXT;
  556. end
  557. else if sym.bind=AB_LAZY then
  558. begin
  559. n.n_value:=0;
  560. n.n_type:=N_ABS or N_EXT;
  561. n.n_sect:=NO_SECT;
  562. end
  563. else
  564. begin
  565. n.n_value:=sym.address;
  566. if Assigned(sec) then
  567. begin
  568. n.n_sect:=sec.inSegIdx;
  569. n.n_type:=n.n_type or N_SECT;
  570. if (sym.typ=AT_FUNCTION) and
  571. (sym.bind=AB_LOCAL) then
  572. begin
  573. n.n_type:=N_PEXT or N_EXT or N_SECT;
  574. n.n_desc:=n.n_desc or N_WEAK_DEF;
  575. end;
  576. end;
  577. end;
  578. if (sym.bind=AB_GLOBAL) and
  579. (n.n_type and N_PEXT=0) then
  580. n.n_type:=n.n_type or N_EXT;
  581. if (sym.typ=AT_FUNCTION) and
  582. (sym.bind=AB_GLOBAL) then
  583. n.n_desc:=n.n_desc or N_NO_DEAD_STRIP;
  584. if Assigned(sec) then
  585. begin
  586. if (sec.nmsection='__nl_symbol_ptr') then
  587. n.n_desc:=n.n_desc or REFERENCE_FLAG_UNDEFINED_NON_LAZY;
  588. if (sec.nmsegment=seg_Data) and (sec.nmsection='__const') then
  589. n.n_desc:=n.n_desc or N_NO_DEAD_STRIP;
  590. end;
  591. mfile.WriteNList(n);
  592. end;
  593. function TMachoObjectOutput.dysymbol_location(sym: TObjSymbol): TMachoSymbolLocation;
  594. begin
  595. if Assigned(sym.objsection) and
  596. (TMachoObjSection(sym.objsection).machoSec=mst_Stabs) then
  597. Result:=loc_Local
  598. else
  599. case sym.typ of
  600. AT_NONE: Result:=loc_Undef;
  601. AT_LABEL: Result:=loc_Notused;
  602. else
  603. Result:=loc_External;
  604. end;
  605. end;
  606. procedure TMachoObjectOutput.writeSectionsHeader(s: TMachoObjSection);
  607. var
  608. sc : TMachoSection;
  609. begin
  610. section_prepare_indirect(s);
  611. fillChar(sc, sizeof(sc), 0);
  612. sc.segname:=s.nmsegment;
  613. sc.sectname:=s.nmsection;
  614. sc.size:=s.Size;
  615. if s.FileSize>0 then
  616. sc.offset:=s.DataPos
  617. else
  618. sc.offset:=0;
  619. sc.addr:=s.MemPos;
  620. sc.nreloc:=s.GetRelocCount;
  621. sc.reloff:=s.relocofs;
  622. sc.flags:=GetSectionFlags(s.nmsegment, s.nmsection);
  623. sc.align:=MachoAlign(s.SecAlign);
  624. sc.indirectIndex:=s.indIndex;
  625. if (sc.flags and SECTION_TYPE)=S_SYMBOL_STUBS then
  626. sc.stubSize:=GetStubSize(cputarget, false);
  627. mfile.WriteSection(sc);
  628. end;
  629. procedure TMachoObjectOutput.writeSymTabCommand;
  630. begin
  631. mfile.WriteLoadCommand(LC_SYMTAB, sizeof(symtab_command));
  632. mfile.WriteUint32(fileofs); {symoff}
  633. mfile.WriteUint32(symCount); {nsyms}
  634. inc(fileofs, symCount*sizeNList(cputarget));
  635. fileofs:=AlignAddr(cputarget, fileofs);
  636. symstrofs:=fileofs;
  637. mfile.WriteUint32(fileofs); {stroff}
  638. mfile.WriteUint32(symlen); {strsize}
  639. inc(fileofs, symlen);
  640. fileofs:=AlignAddr(cputarget, fileofs);
  641. end;
  642. function TMachoObjectOutput.symWriteName(s: TObjSymbol): string;
  643. begin
  644. if not Assigned(s.indsymbol) then
  645. Result:=s.Name
  646. else
  647. Result:=s.indsymbol.Name;
  648. end;
  649. { function getSymWriteNameLength(s: TObjSymbol): Integer; inline;
  650. begin
  651. Result:=length(symWriteName(s))+1;
  652. end;}
  653. procedure TMachoObjectOutput.InitSymbolIndexes(var sCount: aint; var symStrLen: aword);
  654. var
  655. i : integer;
  656. s : TObjSymbol;
  657. stabcount : Integer;
  658. begin
  659. sCount:=0;
  660. symStrLen:=0;
  661. iIndir:=0;
  662. for i:=0 to machoData.ObjSymbolList.Count-1 do
  663. begin
  664. s:=TObjSymbol(machoData.ObjSymbolList[i]);
  665. if (s.typ=AT_LABEL) then
  666. Continue;
  667. if Assigned(s.indsymbol) then
  668. inc(iIndir);
  669. end;
  670. iLocal:=0;
  671. iExtern:=0;
  672. iUndef:=0;
  673. for i:=0 to machoData.ObjSymbolList.Count-1 do
  674. begin
  675. s:=TObjSymbol(machoData.ObjSymbolList[i]);
  676. if (s.typ=AT_LABEL) or
  677. Assigned(s.indsymbol) then
  678. Continue;
  679. if (s.bind=AB_LOCAL) and
  680. (s.Name <> 'fpc_geteipasebx') then
  681. Continue;
  682. case dysymbol_location(s) of
  683. loc_Local:
  684. begin
  685. symList.Insert(iLocal, s);
  686. inc(iLocal); inc(iExtern); inc(iUndef);
  687. end;
  688. loc_External:
  689. begin
  690. symList.Insert(iExtern, s);
  691. inc(iExtern); inc(iUndef);
  692. end;
  693. loc_Undef:
  694. begin
  695. symList.Insert(iUndef, s);
  696. inc(iUndef);
  697. end;
  698. end;
  699. inc(symStrLen, length(s.Name)+1 );
  700. end;
  701. if Assigned(stabsec) then
  702. {skipping hdrsym! (added by ogbase) }
  703. stabcount:=stabsec.Size div sizeof(TObjStabEntry) - 1
  704. else
  705. stabcount:=0;
  706. for i:=0 to symList.Count-1 do
  707. TObjSymbol(symList[i]).symidx:=i+stabcount;
  708. sCount:=symList.Count+stabcount;
  709. for i:=0 to machoData.ObjSymbolList.Count-1 do
  710. with TObjSymbol(machoData.ObjSymbolList[i]) do
  711. if Assigned(indsymbol) then
  712. symidx:=indsymbol.symidx;
  713. if Assigned(strsec) then
  714. // 1 byte of zero name (that stands in the end of table, not at zero pos)
  715. inc(symlen, strsec.Size + 1)
  716. else
  717. inc(symlen); {the first zero byte}
  718. dec(iUndef, iExtern); { iUndef is count of undefined symbols (for dysymtable command) }
  719. dec(iExtern, iLocal); { iExtern is count of external symbols (for dysymtable command) }
  720. inc(iLocal, stabcount);
  721. end;
  722. procedure TMachoObjectOutput.writeSymbols(symstr: tdynamicarray);
  723. var
  724. i : integer;
  725. s : TObjSymbol;
  726. b : byte;
  727. stab : TObjStabEntry;
  728. ro : TObjRelocation;
  729. sym : TObjSymbol;
  730. addr : aword;
  731. text : TmachoObjSection;
  732. funofs : AWord;
  733. begin
  734. if Assigned(stabsec) then
  735. begin
  736. for i:=0 to stabsec.ObjRelocations.Count - 1 do
  737. begin
  738. ro:=TObjRelocation(stabsec.ObjRelocations[i]);
  739. sym:=ro.symbol;
  740. addr:=sym.address;
  741. if Assigned(sym.objsection) then
  742. begin
  743. stabsec.Data.seek(ro.DataOffset-3);
  744. b:=TmachoObjSection(sym.objsection).inSegIdx;
  745. stabsec.Data.write(b, sizeof(b));
  746. end;
  747. stabsec.Data.seek(ro.DataOffset);
  748. stabsec.Data.write(addr, sizeof(addr));
  749. end;
  750. stabsec.Data.seek(sizeof(TObjStabEntry));
  751. funofs:=0;
  752. text:=TmachoObjSection(machoData.ObjSectionList.Find(MakeSectionName(seg_TEXT, '__text')));
  753. for i:=1 to stabsec.Data.size div SizeOf(TObjStabEntry) - 1 do
  754. begin
  755. stabsec.Data.read(stab, sizeof(stab));
  756. case stab.ntype of
  757. N_FUN:
  758. begin
  759. if stab.strpos=0 then
  760. funofs:=0
  761. else
  762. funofs:=stab.nvalue;
  763. end;
  764. N_SLINE,N_RBRAC,N_LBRAC:
  765. begin
  766. if Assigned(text) then
  767. begin
  768. { SLINE are expected to be in __TEXT __text only }
  769. stab.nother:=text.inSegIdx;
  770. inc(stab.nvalue, funofs);
  771. end;
  772. end;
  773. N_OSO:
  774. begin
  775. { null-terminated string is the first in the list }
  776. { apple-gdb doesn't recognize it as zero-string for N_OSO }
  777. { another zero-string should be added to the list }
  778. if stab.strpos=0 then
  779. stab.strpos:=symstr.Size;
  780. end;
  781. end;
  782. FWriter.write(stab, sizeof(stab));
  783. end;
  784. end;
  785. symstr.Seek(symStr.size);
  786. b:=0;
  787. symstr.Write(b,1);
  788. for i:=0 to symList.Count-1 do
  789. begin
  790. s:=TObjSymbol(symList[i]);
  791. symbol_write_nlist(s, symstr);
  792. end;
  793. end;
  794. procedure TMachoObjectOutput.writeDySymTabCommand(IndOffset: aword; IndCount: Integer);
  795. begin
  796. mfile.WriteLoadCommand(LC_DYSYMTAB, sizeof(dysymtab_command));
  797. mfile.WriteUint32(0); {ilocalsym}
  798. mfile.WriteUint32(iLocal); {nlocalsym}
  799. mfile.WriteUint32(iLocal); {iextdefsym}
  800. mfile.WriteUint32(iExtern); {nextdefsym}
  801. mfile.WriteUint32(iLocal + iExtern); {iundefsym}
  802. mfile.WriteUint32(iUndef); {nundefsym}
  803. mfile.WriteUint32(0); {tocoff}
  804. mfile.WriteUint32(0); {ntoc}
  805. mfile.WriteUint32(0); {modtaboff}
  806. mfile.WriteUint32(0); {nmodtab}
  807. mfile.WriteUint32(0); {extrefsymoff}
  808. mfile.WriteUint32(0); {nextrefsyms}
  809. mfile.WriteUint32(IndOffset); {indirectsymoff}
  810. mfile.WriteUint32(IndCount); {nindirectsyms}
  811. mfile.WriteUint32(0); {extreloff}
  812. mfile.WriteUint32(0); {nextrel}
  813. mfile.WriteUint32(0); {locreloff}
  814. mfile.WriteUint32(0); {nlocrel}
  815. end;
  816. procedure TMachoObjectOutput.writeDysymbols;
  817. var
  818. i : integer;
  819. idx : LongWord;
  820. begin
  821. IndirIndex.seek(0);
  822. for i:=0 to (IndirIndex.size div sizeof(Integer))-1 do
  823. begin
  824. IndirIndex.read(idx, sizeof(idx));
  825. mfile.WriteUint32(idx);
  826. end;
  827. end;
  828. function AddSectionToSegment(var segment: TMachoSegment; section : TMachoObjSection): boolean;
  829. begin
  830. { sections must be attached one-by-one to the segment }
  831. if segment.fileoff=0 then
  832. segment.fileoff:=section.DataPos;
  833. if (segment.fileoff+segment.filesize)<(section.FileSize+section.DataPos) then
  834. segment.filesize:=section.FileSize+section.DataPos;
  835. inc(segment.nsects);
  836. inc(segment.vmsize, section.size);
  837. Result:=true;
  838. end;
  839. procedure TMachoObjectOutput.TrailZeros;
  840. var
  841. sz : LongWord;
  842. begin
  843. sz:=AlignAddr(cputarget, FWriter.Size);
  844. if sz - FWriter.Size>0 then
  845. FWriter.WriteZeros(sz-FWriter.Size);
  846. end;
  847. function TMachoObjectOutput.writedata(data: TObjData): boolean;
  848. var
  849. header : TMachHeader;
  850. seg : TMachoSegment;
  851. secobj : TMachoObjSection;
  852. i : Integer;
  853. symstr : tdynamicarray;
  854. segSize : integer; {size of a segment command - platform dependant}
  855. sctSize : integer; {size of a single section header - platform dependant}
  856. indOfs: aword; {indirect symbol offset}
  857. begin
  858. symList:=TFPObjectList.Create(false);
  859. IndirIndex:=tdynamicarray.Create(1024);
  860. result:=false;
  861. machoData:=TMachoObjData(data);
  862. cputarget:=CPU_TYPE_i386;
  863. segSize:=sizeSegment(cputarget);
  864. sctSize:=sizeSection(cputarget);
  865. sectionscnt:=0;
  866. stabsec:=TMachoObjSection(machoData.ObjSectionList.Find('.stabs'));
  867. strsec:=TMachoObjSection(machoData.ObjSectionList.Find('.stabsstr'));
  868. {count number of sections}
  869. machoData.ObjSectionList.ForEachCall(@section_count_sections, nil);
  870. {sections data is written after machheader,load-commands. }
  871. { basic loadcommands for MH_OBJECT are }
  872. { single LC_SEGMENT, containing all sections headers }
  873. { symbol linking information at LC_SYMTAB and LC_DYSYMTAB }
  874. header.cputype:=cputarget;
  875. header.cpusubtype:=CPU_SUBTYPE_i386_ALL;
  876. header.filetype:=MH_OBJECT;
  877. header.ncmds:=3;
  878. header.sizeofcmds:=segSize+sctSize*sectionscnt+sizeof(symtab_command)+sizeof(dysymtab_command);
  879. header.flags:=0;
  880. {setting sections data and memory pos}
  881. fileofs:=sizeMachHeader(cputarget)+header.sizeofcmds;
  882. fileofs:=AlignAddr(cputarget, fileofs);
  883. memofs:=0;
  884. machoData.ObjSectionList.ForEachCall(@section_set_datamempos, nil);
  885. fileofs:=AlignAddr(cputarget, fileofs);
  886. {setting sections relocation offsets}
  887. machoData.ObjSectionList.ForEachCall(@section_set_relocpos, nil);
  888. fileofs:=AlignAddr(cputarget, fileofs);
  889. {creating actual mach-o file writer}
  890. mfile:=AllocMachoWriter(CPU_TYPE_I386, TMachoRawWriter.Create(writer), true);
  891. {writing macho-o header}
  892. mfile.WriteHeader(header);
  893. {starting the first segment command}
  894. InitSegment(seg);
  895. {initialze symbols. some sections (non_lazy, lazy pointers) are effected}
  896. InitSymbolIndexes(symCount, symlen);
  897. for i:=0 to machoData.ObjSectionList.Count-1 do
  898. begin
  899. secobj:=TmachoObjSection(machoData.ObjSectionList[i]);
  900. if secobj.machoSec=mst_Stabs then
  901. Continue;
  902. AddSectionToSegment(seg, secobj);
  903. end;
  904. {writting segment command}
  905. {for MH_OBJECT, all sections are stored in the single segment}
  906. mfile.WriteSegmentCmd(seg, segSize+(seg.nsects)*sctSize);
  907. {section headers are written inside segment command}
  908. for i:=0 to machoData.ObjSectionlist.Count - 1 do
  909. begin
  910. secobj:=TmachoObjSection(machoData.ObjSectionList[i]);
  911. if secobj.machoSec=mst_Stabs then
  912. Continue;
  913. writeSectionsHeader(secobj);
  914. end;
  915. TrailZeros;
  916. if IndirIndex.size div sizeof(Integer)<>iIndir then
  917. InternalError(2009121001);
  918. if iIndir>0 then
  919. indOfs:=fileOfs
  920. else
  921. indOfs:=0;
  922. inc(fileofs, IndirIndex.size);
  923. {write symtab command}
  924. {initilize symbos order. local first, extern second, undef last}
  925. writeSymTabCommand;
  926. TrailZeros;
  927. {write dysymtab command}
  928. writeDySymTabCommand(indofs, iIndir);
  929. TrailZeros;
  930. {writting sections data, to precalculated offsets}
  931. {if precalculated offsets, doesn't match actual written offsets, internal error is risen}
  932. machoData.ObjSectionList.ForEachCall(@section_write_data, nil);
  933. {writting relocation offsets}
  934. machoData.ObjSectionList.ForEachCall(@section_write_relocdata, nil);
  935. {writting dyn symbol tables (indirect symbols arrays)}
  936. writeDysymbols;
  937. {writting symbol table}
  938. if Assigned(strsec) then
  939. symstr:=strsec.Data
  940. else
  941. symstr:=tdynamicarray.create(1024);
  942. writeSymbols(symstr);
  943. TrailZeros;
  944. {writting symbol table strings}
  945. FWriter.writearray(symstr);
  946. // terminating null name
  947. TrailZeros;
  948. if not Assigned(strsec) then
  949. symstr.Free;
  950. TrailZeros;
  951. mfile.Free;
  952. symList.Free;
  953. IndirIndex.Free;
  954. end;
  955. constructor TMachoObjectOutput.Create(AWriter: TObjectWriter);
  956. begin
  957. inherited Create(AWriter);
  958. CObjData:=TMachoObjData;
  959. end;
  960. { TMachoRawWriter }
  961. constructor TMachoRawWriter.Create(awriter: tobjectwriter);
  962. begin
  963. inherited Create;
  964. fwriter:=awriter;
  965. end;
  966. procedure TMachoRawWriter.WriteRaw(const data; datasize: Integer);
  967. begin
  968. fwriter.Write(data, datasize);
  969. end;
  970. { TmachoObjSection }
  971. function TmachoObjSection.GetRelocCount: Integer;
  972. var
  973. i: integer;
  974. r: TObjRelocation;
  975. begin
  976. Result:=ObjRelocations.Count;
  977. for i:=0 to ObjRelocations.Count-1 do
  978. begin
  979. r:=TObjRelocation(ObjRelocations[i]);
  980. if (r.typ=RELOC_PIC_PAIR) then
  981. inc(Result);
  982. end;
  983. end;
  984. function TmachoObjSection.FileSize: Integer;
  985. begin
  986. if Assigned(data) then
  987. Result:=data.size
  988. else
  989. Result:=0;
  990. end;
  991. constructor TmachoObjSection.create(AList: TFPHashObjectList;
  992. const Aname: string; Aalign: shortint; Aoptions: TObjSectionOptions);
  993. begin
  994. if Aname = '__TEXT __textcoal_nt' then
  995. Aalign:=4;
  996. inherited create(AList, Aname, Aalign, Aoptions);
  997. GetSegmentSectionName(aName, nmsegment, nmsection);
  998. if (aname='.stabs') or
  999. (aname='.stabsstr') then
  1000. machoSec:=mst_Stabs
  1001. else if nmsegment=seg_DWARF then
  1002. machoSec:=mst_Dwarf
  1003. else if nmsegment=seg_OBJC then
  1004. machoSec:=mst_ObjC
  1005. else
  1006. machoSec:=mst_Normal;
  1007. end;
  1008. const
  1009. as_i386_darwin_info : tasminfo =
  1010. (
  1011. id : as_i386_macho;
  1012. idtxt : 'MACHO';
  1013. asmbin : '';
  1014. asmcmd : '';
  1015. supported_targets : [system_i386_darwin,system_i386_iphonesim];
  1016. flags : [af_outputbinary,af_smartlink_sections,af_supports_dwarf{, af_stabs_use_function_absolute_addresses}];
  1017. labelprefix : '.L';
  1018. comment : '#';
  1019. dollarsign: '$';
  1020. );
  1021. initialization
  1022. RegisterAssembler(as_i386_darwin_info,TMachoAssembler);
  1023. end.