ogmacho.pas 38 KB

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