ogmacho.pas 38 KB

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