ogmacho.pas 38 KB

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