ogmacho.pas 38 KB

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