deal with endian-ness in mach-o non-scattered relocs.
[external/binutils.git] / bfd / mach-o.c
1 /* Mach-O support for BFD.
2    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3    2009, 2010, 2011, 2012
4    Free Software Foundation, Inc.
5
6    This file is part of BFD, the Binary File Descriptor library.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22
23 #include "sysdep.h"
24 #include "mach-o.h"
25 #include "bfd.h"
26 #include "libbfd.h"
27 #include "libiberty.h"
28 #include "aout/stab_gnu.h"
29 #include "mach-o/reloc.h"
30 #include "mach-o/external.h"
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #define bfd_mach_o_object_p bfd_mach_o_gen_object_p
36 #define bfd_mach_o_core_p bfd_mach_o_gen_core_p
37 #define bfd_mach_o_mkobject bfd_mach_o_gen_mkobject
38
39 #define FILE_ALIGN(off, algn) \
40   (((off) + ((file_ptr) 1 << (algn)) - 1) & ((file_ptr) -1 << (algn)))
41
42 unsigned int
43 bfd_mach_o_version (bfd *abfd)
44 {
45   bfd_mach_o_data_struct *mdata = NULL;
46
47   BFD_ASSERT (bfd_mach_o_valid (abfd));
48   mdata = bfd_mach_o_get_data (abfd);
49
50   return mdata->header.version;
51 }
52
53 bfd_boolean
54 bfd_mach_o_valid (bfd *abfd)
55 {
56   if (abfd == NULL || abfd->xvec == NULL)
57     return FALSE;
58
59   if (abfd->xvec->flavour != bfd_target_mach_o_flavour)
60     return FALSE;
61
62   if (bfd_mach_o_get_data (abfd) == NULL)
63     return FALSE;
64   return TRUE;
65 }
66
67 static INLINE bfd_boolean
68 mach_o_wide_p (bfd_mach_o_header *header)
69 {
70   switch (header->version)
71     {
72     case 1:
73       return FALSE;
74     case 2:
75       return TRUE;
76     default:
77       BFD_FAIL ();
78       return FALSE;
79     }
80 }
81
82 static INLINE bfd_boolean
83 bfd_mach_o_wide_p (bfd *abfd)
84 {
85   return mach_o_wide_p (&bfd_mach_o_get_data (abfd)->header);
86 }
87       
88 /* Tables to translate well known Mach-O segment/section names to bfd
89    names.  Use of canonical names (such as .text or .debug_frame) is required
90    by gdb.  */
91
92 /* __TEXT Segment.  */
93 static const mach_o_section_name_xlat text_section_names_xlat[] =
94   {
95     {   ".text",                                "__text",       
96         SEC_CODE | SEC_LOAD,                    BFD_MACH_O_S_REGULAR,
97         BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS,    0},
98     {   ".const",                               "__const",
99         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_REGULAR,
100         BFD_MACH_O_S_ATTR_NONE,                 0},
101     {   ".static_const",                        "__static_const",
102         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_REGULAR,
103         BFD_MACH_O_S_ATTR_NONE,                 0},
104     {   ".cstring",                             "__cstring",
105         SEC_READONLY | SEC_DATA | SEC_LOAD | SEC_MERGE | SEC_STRINGS,
106                                                 BFD_MACH_O_S_CSTRING_LITERALS,
107         BFD_MACH_O_S_ATTR_NONE,                 0},
108     {   ".literal4",                            "__literal4",
109         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_4BYTE_LITERALS,
110         BFD_MACH_O_S_ATTR_NONE,                 2},
111     {   ".literal8",                            "__literal8",
112         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_8BYTE_LITERALS,
113         BFD_MACH_O_S_ATTR_NONE,                 3},
114     {   ".literal16",                           "__literal16",
115         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_16BYTE_LITERALS,
116         BFD_MACH_O_S_ATTR_NONE,                 4},
117     {   ".constructor",                         "__constructor",
118         SEC_CODE | SEC_LOAD,                    BFD_MACH_O_S_REGULAR,
119         BFD_MACH_O_S_ATTR_NONE,                 0},
120     {   ".destructor",                          "__destructor",
121         SEC_CODE | SEC_LOAD,                    BFD_MACH_O_S_REGULAR,
122         BFD_MACH_O_S_ATTR_NONE,                 0},
123     {   ".eh_frame",                            "__eh_frame",
124         SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_COALESCED,
125         BFD_MACH_O_S_ATTR_LIVE_SUPPORT
126         | BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS
127         | BFD_MACH_O_S_ATTR_NO_TOC,             2},
128     { NULL, NULL, 0, 0, 0, 0}
129   };
130
131 /* __DATA Segment.  */
132 static const mach_o_section_name_xlat data_section_names_xlat[] =
133   {
134     {   ".data",                        "__data",
135         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
136         BFD_MACH_O_S_ATTR_NONE,         0},
137     {   ".bss",                         "__bss",
138         SEC_NO_FLAGS,                   BFD_MACH_O_S_ZEROFILL,
139         BFD_MACH_O_S_ATTR_NONE,         0},
140     {   ".const_data",                  "__const",
141         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
142         BFD_MACH_O_S_ATTR_NONE,         0},
143     {   ".static_data",                 "__static_data",
144         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
145         BFD_MACH_O_S_ATTR_NONE,         0},
146     {   ".mod_init_func",               "__mod_init_func",
147         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_MOD_INIT_FUNC_POINTERS,
148         BFD_MACH_O_S_ATTR_NONE,         2},
149     {   ".mod_term_func",               "__mod_term_func",
150         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_MOD_FINI_FUNC_POINTERS,
151         BFD_MACH_O_S_ATTR_NONE,         2},
152     {   ".dyld",                        "__dyld",
153         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
154         BFD_MACH_O_S_ATTR_NONE,         0},
155     {   ".cfstring",                    "__cfstring",
156         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
157         BFD_MACH_O_S_ATTR_NONE,         2},
158     { NULL, NULL, 0, 0, 0, 0}
159   };
160
161 /* __DWARF Segment.  */
162 static const mach_o_section_name_xlat dwarf_section_names_xlat[] =
163   {
164     {   ".debug_frame",                 "__debug_frame",
165         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
166         BFD_MACH_O_S_ATTR_DEBUG,        0},
167     {   ".debug_info",                  "__debug_info",
168         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
169         BFD_MACH_O_S_ATTR_DEBUG,        0},
170     {   ".debug_abbrev",                "__debug_abbrev",
171         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
172         BFD_MACH_O_S_ATTR_DEBUG,        0},
173     {   ".debug_aranges",               "__debug_aranges",
174         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
175         BFD_MACH_O_S_ATTR_DEBUG,        0},
176     {   ".debug_macinfo",               "__debug_macinfo",
177         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
178         BFD_MACH_O_S_ATTR_DEBUG,        0},
179     {   ".debug_line",                  "__debug_line",
180         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
181         BFD_MACH_O_S_ATTR_DEBUG,        0},
182     {   ".debug_loc",                   "__debug_loc",
183         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
184         BFD_MACH_O_S_ATTR_DEBUG,        0},
185     {   ".debug_pubnames",              "__debug_pubnames",
186         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
187         BFD_MACH_O_S_ATTR_DEBUG,        0},
188     {   ".debug_pubtypes",              "__debug_pubtypes",
189         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
190         BFD_MACH_O_S_ATTR_DEBUG,        0},
191     {   ".debug_str",                   "__debug_str",
192         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
193         BFD_MACH_O_S_ATTR_DEBUG,        0},
194     {   ".debug_ranges",                "__debug_ranges",
195         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
196         BFD_MACH_O_S_ATTR_DEBUG,        0},
197     {   ".debug_macro",                 "__debug_macro",
198         SEC_DEBUGGING,                  BFD_MACH_O_S_REGULAR,
199         BFD_MACH_O_S_ATTR_DEBUG,        0},
200     { NULL, NULL, 0, 0, 0, 0}
201   };
202
203 /* __OBJC Segment.  */
204 static const mach_o_section_name_xlat objc_section_names_xlat[] =
205   {
206     {   ".objc_class",                  "__class",
207         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
208         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
209     {   ".objc_meta_class",             "__meta_class",
210         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
211         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
212     {   ".objc_cat_cls_meth",           "__cat_cls_meth",
213         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
214         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
215     {   ".objc_cat_inst_meth",          "__cat_inst_meth",
216         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
217         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
218     {   ".objc_protocol",               "__protocol",
219         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
220         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
221     {   ".objc_string_object",          "__string_object",
222         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
223         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
224     {   ".objc_cls_meth",               "__cls_meth",
225         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
226         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
227     {   ".objc_inst_meth",              "__inst_meth",
228         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
229         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
230     {   ".objc_cls_refs",               "__cls_refs",
231         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_LITERAL_POINTERS,
232         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
233     {   ".objc_message_refs",           "__message_refs",
234         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_LITERAL_POINTERS,
235         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
236     {   ".objc_symbols",                "__symbols",
237         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
238         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
239     {   ".objc_category",               "__category",
240         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
241         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
242     {   ".objc_class_vars",             "__class_vars",
243         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
244         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
245     {   ".objc_instance_vars",          "__instance_vars",
246         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
247         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
248     {   ".objc_module_info",            "__module_info",
249         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
250         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
251     {   ".objc_selector_strs",          "__selector_strs",
252         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_CSTRING_LITERALS,
253         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
254     {   ".objc_image_info",             "__image_info",
255         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
256         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
257     {   ".objc_selector_fixup",         "__sel_fixup",
258         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
259         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
260     /* Objc V1 */
261     {   ".objc1_class_ext",             "__class_ext",
262         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
263         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
264     {   ".objc1_property_list",         "__property",
265         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
266         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
267     {   ".objc1_protocol_ext",          "__protocol_ext",
268         SEC_DATA | SEC_LOAD,            BFD_MACH_O_S_REGULAR,
269         BFD_MACH_O_S_ATTR_NO_DEAD_STRIP, 0},
270     { NULL, NULL, 0, 0, 0, 0}
271   };
272
273 static const mach_o_segment_name_xlat segsec_names_xlat[] =
274   {
275     { "__TEXT", text_section_names_xlat },
276     { "__DATA", data_section_names_xlat },
277     { "__DWARF", dwarf_section_names_xlat },
278     { "__OBJC", objc_section_names_xlat },
279     { NULL, NULL }
280   };
281
282 static const char dsym_subdir[] = ".dSYM/Contents/Resources/DWARF";
283
284 /* For both cases bfd-name => mach-o name and vice versa, the specific target
285    is checked before the generic.  This allows a target (e.g. ppc for cstring)
286    to override the generic definition with a more specific one.  */
287
288 /* Fetch the translation from a Mach-O section designation (segment, section)
289    as a bfd short name, if one exists.  Otherwise return NULL.
290    
291    Allow the segment and section names to be unterminated 16 byte arrays.  */
292
293 const mach_o_section_name_xlat *
294 bfd_mach_o_section_data_for_mach_sect (bfd *abfd, const char *segname,
295                                        const char *sectname)
296 {
297   const struct mach_o_segment_name_xlat *seg;
298   const mach_o_section_name_xlat *sec;
299   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
300
301   /* First try any target-specific translations defined...  */
302   if (bed->segsec_names_xlat)
303     for (seg = bed->segsec_names_xlat; seg->segname; seg++)
304       if (strncmp (seg->segname, segname, BFD_MACH_O_SEGNAME_SIZE) == 0)
305         for (sec = seg->sections; sec->mach_o_name; sec++)
306           if (strncmp (sec->mach_o_name, sectname,
307                        BFD_MACH_O_SECTNAME_SIZE) == 0)
308             return sec;
309
310   /* ... and then the Mach-O generic ones.  */
311   for (seg = segsec_names_xlat; seg->segname; seg++)
312     if (strncmp (seg->segname, segname, BFD_MACH_O_SEGNAME_SIZE) == 0)
313       for (sec = seg->sections; sec->mach_o_name; sec++)
314         if (strncmp (sec->mach_o_name, sectname,
315                      BFD_MACH_O_SECTNAME_SIZE) == 0)
316           return sec;
317
318   return NULL;  
319 }
320
321 /* If the bfd_name for this section is a 'canonical' form for which we
322    know the Mach-O data, return the segment name and the data for the 
323    Mach-O equivalent.  Otherwise return NULL.  */
324
325 const mach_o_section_name_xlat *
326 bfd_mach_o_section_data_for_bfd_name (bfd *abfd, const char *bfd_name,
327                                       const char **segname)
328 {
329   const struct mach_o_segment_name_xlat *seg;
330   const mach_o_section_name_xlat *sec;
331   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
332   *segname = NULL;
333
334   if (bfd_name[0] != '.')
335     return NULL;
336
337   /* First try any target-specific translations defined...  */
338   if (bed->segsec_names_xlat)
339     for (seg = bed->segsec_names_xlat; seg->segname; seg++)
340       for (sec = seg->sections; sec->bfd_name; sec++)
341         if (strcmp (bfd_name, sec->bfd_name) == 0)
342           {
343             *segname = seg->segname;
344             return sec;
345           }
346
347   /* ... and then the Mach-O generic ones.  */
348   for (seg = segsec_names_xlat; seg->segname; seg++)
349     for (sec = seg->sections; sec->bfd_name; sec++)
350       if (strcmp (bfd_name, sec->bfd_name) == 0)
351         {
352           *segname = seg->segname;
353           return sec;
354         }
355
356   return NULL;  
357 }
358
359 /* Convert Mach-O section name to BFD.
360
361    Try to use standard/canonical names, for which we have tables including 
362    default flag settings - which are returned.  Otherwise forge a new name
363    in the form "<segmentname>.<sectionname>" this will be prefixed with
364    LC_SEGMENT. if the segment name does not begin with an underscore.
365
366    SEGNAME and SECTNAME are 16 byte arrays (they do not need to be NUL-
367    terminated if the name length is exactly 16 bytes - but must be if the name
368    length is less than 16 characters).  */
369
370 void
371 bfd_mach_o_convert_section_name_to_bfd (bfd *abfd, const char *segname,
372                                         const char *secname, const char **name,
373                                         flagword *flags)
374 {
375   const mach_o_section_name_xlat *xlat;
376   char *res;
377   unsigned int len;
378   const char *pfx = "";
379
380   *name = NULL;
381   *flags = SEC_NO_FLAGS;
382
383   /* First search for a canonical name...  
384      xlat will be non-null if there is an entry for segname, secname.  */
385   xlat = bfd_mach_o_section_data_for_mach_sect (abfd, segname, secname);
386   if (xlat)
387     {
388       len = strlen (xlat->bfd_name);
389       res = bfd_alloc (abfd, len+1);
390       if (res == NULL)
391         return;
392       memcpy (res, xlat->bfd_name, len+1);
393       *name = res;
394       *flags = xlat->bfd_flags;
395       return;
396     }
397
398   /* ... else we make up a bfd name from the segment concatenated with the
399      section.  */
400
401   len = 16 + 1 + 16 + 1;
402
403   /* Put "LC_SEGMENT." prefix if the segment name is weird (ie doesn't start
404      with an underscore.  */
405   if (segname[0] != '_')
406     {
407       static const char seg_pfx[] = "LC_SEGMENT.";
408
409       pfx = seg_pfx;
410       len += sizeof (seg_pfx) - 1;
411     }
412
413   res = bfd_alloc (abfd, len);
414   if (res == NULL)
415     return;
416   snprintf (res, len, "%s%.16s.%.16s", pfx, segname, secname);
417   *name = res;
418 }
419
420 /* Convert a bfd section name to a Mach-O segment + section name.
421
422    If the name is a canonical one for which we have a Darwin match
423    return the translation table - which contains defaults for flags,
424    type, attribute and default alignment data.
425
426    Otherwise, expand the bfd_name (assumed to be in the form 
427    "[LC_SEGMENT.]<segmentname>.<sectionname>") and return NULL.  */
428
429 static const mach_o_section_name_xlat *
430 bfd_mach_o_convert_section_name_to_mach_o (bfd *abfd ATTRIBUTE_UNUSED,
431                                            asection *sect,
432                                            bfd_mach_o_section *section)
433 {
434   const mach_o_section_name_xlat *xlat;
435   const char *name = bfd_get_section_name (abfd, sect);
436   const char *segname;
437   const char *dot;
438   unsigned int len;
439   unsigned int seglen;
440   unsigned int seclen;
441
442   memset (section->segname, 0, BFD_MACH_O_SEGNAME_SIZE + 1);
443   memset (section->sectname, 0, BFD_MACH_O_SECTNAME_SIZE + 1);
444
445   /* See if is a canonical name ... */
446   xlat = bfd_mach_o_section_data_for_bfd_name (abfd, name, &segname);
447   if (xlat)
448     {
449       strcpy (section->segname, segname);
450       strcpy (section->sectname, xlat->mach_o_name);
451       return xlat;
452     }
453
454   /* .. else we convert our constructed one back to Mach-O.
455      Strip LC_SEGMENT. prefix, if present.  */
456   if (strncmp (name, "LC_SEGMENT.", 11) == 0)
457     name += 11;
458
459   /* Find a dot.  */
460   dot = strchr (name, '.');
461   len = strlen (name);
462
463   /* Try to split name into segment and section names.  */
464   if (dot && dot != name)
465     {
466       seglen = dot - name;
467       seclen = len - (dot + 1 - name);
468
469       if (seglen < 16 && seclen < 16)
470         {
471           memcpy (section->segname, name, seglen);
472           section->segname[seglen] = 0;
473           memcpy (section->sectname, dot + 1, seclen);
474           section->sectname[seclen] = 0;
475           return NULL;
476         }
477     }
478
479   /* The segment and section names are both missing - don't make them
480      into dots.  */
481   if (dot && dot == name)
482     return NULL;
483
484   /* Just duplicate the name into both segment and section.  */
485   if (len > 16)
486     len = 16;
487   memcpy (section->segname, name, len);
488   section->segname[len] = 0;
489   memcpy (section->sectname, name, len);
490   section->sectname[len] = 0;
491   return NULL;
492 }
493
494 /* Return the size of an entry for section SEC.
495    Must be called only for symbol pointer section and symbol stubs
496    sections.  */
497
498 unsigned int
499 bfd_mach_o_section_get_entry_size (bfd *abfd, bfd_mach_o_section *sec)
500 {
501   switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
502     {
503     case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
504     case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
505       return bfd_mach_o_wide_p (abfd) ? 8 : 4;
506     case BFD_MACH_O_S_SYMBOL_STUBS:
507       return sec->reserved2;
508     default:
509       BFD_FAIL ();
510       return 0;
511     }
512 }
513
514 /* Return the number of indirect symbols for a section.
515    Must be called only for symbol pointer section and symbol stubs
516    sections.  */
517
518 unsigned int
519 bfd_mach_o_section_get_nbr_indirect (bfd *abfd, bfd_mach_o_section *sec)
520 {
521   unsigned int elsz;
522
523   elsz = bfd_mach_o_section_get_entry_size (abfd, sec);
524   if (elsz == 0)
525     return 0;
526   else
527     return sec->size / elsz;
528 }
529
530
531 /* Copy any private info we understand from the input symbol
532    to the output symbol.  */
533
534 bfd_boolean
535 bfd_mach_o_bfd_copy_private_symbol_data (bfd *ibfd ATTRIBUTE_UNUSED,
536                                          asymbol *isymbol,
537                                          bfd *obfd ATTRIBUTE_UNUSED,
538                                          asymbol *osymbol)
539 {
540   bfd_mach_o_asymbol *os, *is;
541   os = (bfd_mach_o_asymbol *)osymbol;
542   is = (bfd_mach_o_asymbol *)isymbol;
543   os->n_type = is->n_type;
544   os->n_sect = is->n_sect;
545   os->n_desc = is->n_desc;
546   os->symbol.udata.i = is->symbol.udata.i;
547   return TRUE;
548 }
549
550 /* Copy any private info we understand from the input section
551    to the output section.  */
552
553 bfd_boolean
554 bfd_mach_o_bfd_copy_private_section_data (bfd *ibfd ATTRIBUTE_UNUSED,
555                                           asection *isection,
556                                           bfd *obfd ATTRIBUTE_UNUSED,
557                                           asection *osection)
558 {
559   if (osection->used_by_bfd == NULL)
560     osection->used_by_bfd = isection->used_by_bfd;
561   else 
562     if (isection->used_by_bfd != NULL)
563       memcpy (osection->used_by_bfd, isection->used_by_bfd, 
564               sizeof (bfd_mach_o_section));
565  
566   if (osection->used_by_bfd != NULL)
567     ((bfd_mach_o_section *)osection->used_by_bfd)->bfdsection = osection;
568
569   return TRUE;
570 }
571
572 /* Copy any private info we understand from the input bfd
573    to the output bfd.  */
574
575 bfd_boolean
576 bfd_mach_o_bfd_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
577 {
578   if (bfd_get_flavour (ibfd) != bfd_target_mach_o_flavour
579       || bfd_get_flavour (obfd) != bfd_target_mach_o_flavour)
580     return TRUE;
581
582   BFD_ASSERT (bfd_mach_o_valid (ibfd));
583   BFD_ASSERT (bfd_mach_o_valid (obfd));
584
585   /* FIXME: copy commands.  */
586
587   return TRUE;
588 }
589
590 /* This allows us to set up to 32 bits of flags (unless we invent some
591    fiendish scheme to subdivide).  For now, we'll just set the file flags
592    without error checking - just overwrite.  */
593    
594 bfd_boolean
595 bfd_mach_o_bfd_set_private_flags (bfd *abfd, flagword flags)
596 {
597   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
598
599   if (!mdata)
600     return FALSE;
601
602   mdata->header.flags = flags;
603   return TRUE;
604 }
605
606 /* Count the total number of symbols.  */
607
608 static long
609 bfd_mach_o_count_symbols (bfd *abfd)
610 {
611   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
612
613   if (mdata->symtab == NULL)
614     return 0;
615   return mdata->symtab->nsyms;
616 }
617
618 long
619 bfd_mach_o_get_symtab_upper_bound (bfd *abfd)
620 {
621   long nsyms = bfd_mach_o_count_symbols (abfd);
622
623   return ((nsyms + 1) * sizeof (asymbol *));
624 }
625
626 long
627 bfd_mach_o_canonicalize_symtab (bfd *abfd, asymbol **alocation)
628 {
629   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
630   long nsyms = bfd_mach_o_count_symbols (abfd);
631   bfd_mach_o_symtab_command *sym = mdata->symtab;
632   unsigned long j;
633
634   if (nsyms < 0)
635     return nsyms;
636
637   if (nsyms == 0)
638     {
639       /* Do not try to read symbols if there are none.  */
640       alocation[0] = NULL;
641       return 0;
642     }
643
644   if (!bfd_mach_o_read_symtab_symbols (abfd))
645     {
646       (*_bfd_error_handler)
647         (_("bfd_mach_o_canonicalize_symtab: unable to load symbols"));
648       return 0;
649     }
650
651   BFD_ASSERT (sym->symbols != NULL);
652
653   for (j = 0; j < sym->nsyms; j++)
654     alocation[j] = &sym->symbols[j].symbol;
655
656   alocation[j] = NULL;
657
658   return nsyms;
659 }
660
661 /* Create synthetic symbols for indirect symbols.  */
662
663 long
664 bfd_mach_o_get_synthetic_symtab (bfd *abfd,
665                                  long symcount ATTRIBUTE_UNUSED,
666                                  asymbol **syms ATTRIBUTE_UNUSED,
667                                  long dynsymcount ATTRIBUTE_UNUSED,
668                                  asymbol **dynsyms ATTRIBUTE_UNUSED,
669                                  asymbol **ret)
670 {
671   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
672   bfd_mach_o_dysymtab_command *dysymtab = mdata->dysymtab;
673   bfd_mach_o_symtab_command *symtab = mdata->symtab;
674   asymbol *s;
675   unsigned long count, i, j, n;
676   size_t size;
677   char *names;
678   char *nul_name;
679
680   *ret = NULL;
681
682   /* Stop now if no symbols or no indirect symbols.  */
683   if (dysymtab == NULL || symtab == NULL || symtab->symbols == NULL)
684     return 0;
685
686   if (dysymtab->nindirectsyms == 0)
687     return 0;
688
689   /* We need to allocate a bfd symbol for every indirect symbol and to
690      allocate the memory for its name.  */
691   count = dysymtab->nindirectsyms;
692   size = count * sizeof (asymbol) + 1;
693
694   for (j = 0; j < count; j++)
695     {
696       unsigned int isym = dysymtab->indirect_syms[j];
697
698       /* Some indirect symbols are anonymous.  */
699       if (isym < symtab->nsyms && symtab->symbols[isym].symbol.name)
700         size += strlen (symtab->symbols[isym].symbol.name) + sizeof ("$stub");
701     }
702
703   s = *ret = (asymbol *) bfd_malloc (size);
704   if (s == NULL)
705     return -1;
706   names = (char *) (s + count);
707   nul_name = names;
708   *names++ = 0;
709   
710   n = 0;
711   for (i = 0; i < mdata->nsects; i++)
712     {
713       bfd_mach_o_section *sec = mdata->sections[i];
714       unsigned int first, last;
715       bfd_vma addr;
716       bfd_vma entry_size;
717       
718       switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
719         {
720         case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
721         case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
722         case BFD_MACH_O_S_SYMBOL_STUBS:
723           /* Only these sections have indirect symbols.  */
724           first = sec->reserved1;
725           last = first + bfd_mach_o_section_get_nbr_indirect (abfd, sec);
726           addr = sec->addr;
727           entry_size = bfd_mach_o_section_get_entry_size (abfd, sec);
728           for (j = first; j < last; j++)
729             {
730               unsigned int isym = dysymtab->indirect_syms[j];
731
732               s->flags = BSF_GLOBAL | BSF_SYNTHETIC;
733               s->section = sec->bfdsection;
734               s->value = addr - sec->addr;
735               s->udata.p = NULL;
736               
737               if (isym < symtab->nsyms
738                   && symtab->symbols[isym].symbol.name)
739                 {
740                   const char *sym = symtab->symbols[isym].symbol.name;
741                   size_t len;
742
743                   s->name = names;
744                   len = strlen (sym);
745                   memcpy (names, sym, len);
746                   names += len;
747                   memcpy (names, "$stub", sizeof ("$stub"));
748                   names += sizeof ("$stub");
749                 }
750               else
751                 s->name = nul_name;
752
753               addr += entry_size;
754               s++;
755               n++;
756             }
757           break;
758         default:
759           break;
760         }
761     }
762
763   return n;
764 }
765
766 void
767 bfd_mach_o_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
768                             asymbol *symbol,
769                             symbol_info *ret)
770 {
771   bfd_symbol_info (symbol, ret);
772 }
773
774 void
775 bfd_mach_o_print_symbol (bfd *abfd,
776                          void * afile,
777                          asymbol *symbol,
778                          bfd_print_symbol_type how)
779 {
780   FILE *file = (FILE *) afile;
781   const char *name;
782   bfd_mach_o_asymbol *asym = (bfd_mach_o_asymbol *)symbol;
783
784   switch (how)
785     {
786     case bfd_print_symbol_name:
787       fprintf (file, "%s", symbol->name);
788       break;
789     default:
790       bfd_print_symbol_vandf (abfd, (void *) file, symbol);
791       if (asym->n_type & BFD_MACH_O_N_STAB)
792         name = bfd_get_stab_name (asym->n_type);
793       else
794         switch (asym->n_type & BFD_MACH_O_N_TYPE)
795           {
796           case BFD_MACH_O_N_UNDF:
797             if (symbol->value == 0)
798               name = "UND";
799             else
800               name = "COM";
801             break;
802           case BFD_MACH_O_N_ABS:
803             name = "ABS";
804             break;
805           case BFD_MACH_O_N_INDR:
806             name = "INDR";
807             break;
808           case BFD_MACH_O_N_PBUD:
809             name = "PBUD";
810             break;
811           case BFD_MACH_O_N_SECT:
812             name = "SECT";
813             break;
814           default:
815             name = "???";
816             break;
817           }
818       if (name == NULL)
819         name = "";
820       fprintf (file, " %02x %-6s %02x %04x",
821                asym->n_type, name, asym->n_sect, asym->n_desc);
822       if ((asym->n_type & BFD_MACH_O_N_STAB) == 0
823           && (asym->n_type & BFD_MACH_O_N_TYPE) == BFD_MACH_O_N_SECT)
824         fprintf (file, " [%s]", symbol->section->name);
825       fprintf (file, " %s", symbol->name);
826     }
827 }
828
829 static void
830 bfd_mach_o_convert_architecture (bfd_mach_o_cpu_type mtype,
831                                  bfd_mach_o_cpu_subtype msubtype,
832                                  enum bfd_architecture *type,
833                                  unsigned long *subtype)
834 {
835   *subtype = bfd_arch_unknown;
836
837   switch (mtype)
838     {
839     case BFD_MACH_O_CPU_TYPE_VAX:
840       *type = bfd_arch_vax;
841       break;
842     case BFD_MACH_O_CPU_TYPE_MC680x0:
843       *type = bfd_arch_m68k;
844       break;
845     case BFD_MACH_O_CPU_TYPE_I386:
846       *type = bfd_arch_i386;
847       *subtype = bfd_mach_i386_i386;
848       break;
849     case BFD_MACH_O_CPU_TYPE_X86_64:
850       *type = bfd_arch_i386;
851       *subtype = bfd_mach_x86_64;
852       break;
853     case BFD_MACH_O_CPU_TYPE_MIPS:
854       *type = bfd_arch_mips;
855       break;
856     case BFD_MACH_O_CPU_TYPE_MC98000:
857       *type = bfd_arch_m98k;
858       break;
859     case BFD_MACH_O_CPU_TYPE_HPPA:
860       *type = bfd_arch_hppa;
861       break;
862     case BFD_MACH_O_CPU_TYPE_ARM:
863       *type = bfd_arch_arm;
864       switch (msubtype)
865         {
866         case BFD_MACH_O_CPU_SUBTYPE_ARM_V4T:
867           *subtype = bfd_mach_arm_4T;
868           break;
869         case BFD_MACH_O_CPU_SUBTYPE_ARM_V6:
870           *subtype = bfd_mach_arm_4T;   /* Best fit ?  */
871           break;
872         case BFD_MACH_O_CPU_SUBTYPE_ARM_V5TEJ:
873           *subtype = bfd_mach_arm_5TE;
874           break;
875         case BFD_MACH_O_CPU_SUBTYPE_ARM_XSCALE:
876           *subtype = bfd_mach_arm_XScale;
877           break;
878         case BFD_MACH_O_CPU_SUBTYPE_ARM_V7:
879           *subtype = bfd_mach_arm_5TE;  /* Best fit ?  */
880           break;
881         case BFD_MACH_O_CPU_SUBTYPE_ARM_ALL:
882         default:
883           break;
884         }
885       break;
886     case BFD_MACH_O_CPU_TYPE_MC88000:
887       *type = bfd_arch_m88k;
888       break;
889     case BFD_MACH_O_CPU_TYPE_SPARC:
890       *type = bfd_arch_sparc;
891       *subtype = bfd_mach_sparc;
892       break;
893     case BFD_MACH_O_CPU_TYPE_I860:
894       *type = bfd_arch_i860;
895       break;
896     case BFD_MACH_O_CPU_TYPE_ALPHA:
897       *type = bfd_arch_alpha;
898       break;
899     case BFD_MACH_O_CPU_TYPE_POWERPC:
900       *type = bfd_arch_powerpc;
901       *subtype = bfd_mach_ppc;
902       break;
903     case BFD_MACH_O_CPU_TYPE_POWERPC_64:
904       *type = bfd_arch_powerpc;
905       *subtype = bfd_mach_ppc64;
906       break;
907     default:
908       *type = bfd_arch_unknown;
909       break;
910     }
911 }
912
913 static bfd_boolean
914 bfd_mach_o_write_header (bfd *abfd, bfd_mach_o_header *header)
915 {
916   struct mach_o_header_external raw;
917   unsigned int size;
918
919   size = mach_o_wide_p (header) ?
920     BFD_MACH_O_HEADER_64_SIZE : BFD_MACH_O_HEADER_SIZE;
921
922   bfd_h_put_32 (abfd, header->magic, raw.magic);
923   bfd_h_put_32 (abfd, header->cputype, raw.cputype);
924   bfd_h_put_32 (abfd, header->cpusubtype, raw.cpusubtype);
925   bfd_h_put_32 (abfd, header->filetype, raw.filetype);
926   bfd_h_put_32 (abfd, header->ncmds, raw.ncmds);
927   bfd_h_put_32 (abfd, header->sizeofcmds, raw.sizeofcmds);
928   bfd_h_put_32 (abfd, header->flags, raw.flags);
929
930   if (mach_o_wide_p (header))
931     bfd_h_put_32 (abfd, header->reserved, raw.reserved);
932
933   if (bfd_seek (abfd, 0, SEEK_SET) != 0
934       || bfd_bwrite (&raw, size, abfd) != size)
935     return FALSE;
936
937   return TRUE;
938 }
939
940 static int
941 bfd_mach_o_write_thread (bfd *abfd, bfd_mach_o_load_command *command)
942 {
943   bfd_mach_o_thread_command *cmd = &command->command.thread;
944   unsigned int i;
945   struct mach_o_thread_command_external raw;
946   unsigned int offset;
947
948   BFD_ASSERT ((command->type == BFD_MACH_O_LC_THREAD)
949               || (command->type == BFD_MACH_O_LC_UNIXTHREAD));
950
951   offset = 8;
952   for (i = 0; i < cmd->nflavours; i++)
953     {
954       BFD_ASSERT ((cmd->flavours[i].size % 4) == 0);
955       BFD_ASSERT (cmd->flavours[i].offset ==
956                   (command->offset + offset + BFD_MACH_O_LC_SIZE));
957
958       bfd_h_put_32 (abfd, cmd->flavours[i].flavour, raw.flavour);
959       bfd_h_put_32 (abfd, (cmd->flavours[i].size / 4), raw.count);
960
961       if (bfd_seek (abfd, command->offset + offset, SEEK_SET) != 0
962           || bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
963         return -1;
964
965       offset += cmd->flavours[i].size + sizeof (raw);
966     }
967
968   return 0;
969 }
970
971 long
972 bfd_mach_o_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
973                                   asection *asect)
974 {
975   return (asect->reloc_count + 1) * sizeof (arelent *);
976 }
977
978 /* In addition to the need to byte-swap the symbol number, the bit positions
979    of the fields in the relocation information vary per target endian-ness.  */
980
981 static void
982 bfd_mach_o_swap_in_non_scattered_reloc (bfd *abfd, bfd_mach_o_reloc_info *rel,
983                                        unsigned char *fields)
984 {
985   unsigned char info = fields[3];
986
987   if (bfd_big_endian (abfd))
988     {
989       rel->r_value = (fields[0] << 16) | (fields[1] << 8) | fields[2];
990       rel->r_type = (info >> BFD_MACH_O_BE_TYPE_SHIFT) & BFD_MACH_O_TYPE_MASK;
991       rel->r_pcrel = (info & BFD_MACH_O_BE_PCREL) ? 1 : 0;
992       rel->r_length = (info >> BFD_MACH_O_BE_LENGTH_SHIFT) 
993                       & BFD_MACH_O_LENGTH_MASK;
994       rel->r_extern = (info & BFD_MACH_O_BE_EXTERN) ? 1 : 0;
995     }
996   else
997     {
998       rel->r_value = (fields[2] << 16) | (fields[1] << 8) | fields[0];
999       rel->r_type = (info >> BFD_MACH_O_LE_TYPE_SHIFT) & BFD_MACH_O_TYPE_MASK;
1000       rel->r_pcrel = (info & BFD_MACH_O_LE_PCREL) ? 1 : 0;
1001       rel->r_length = (info >> BFD_MACH_O_LE_LENGTH_SHIFT) 
1002                       & BFD_MACH_O_LENGTH_MASK;
1003       rel->r_extern = (info & BFD_MACH_O_LE_EXTERN) ? 1 : 0;
1004     }
1005 }
1006
1007 static int
1008 bfd_mach_o_canonicalize_one_reloc (bfd *abfd,
1009                                    struct mach_o_reloc_info_external *raw,
1010                                    arelent *res, asymbol **syms)
1011 {
1012   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
1013   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
1014   bfd_mach_o_reloc_info reloc;
1015   bfd_vma addr;
1016   asymbol **sym;
1017
1018   addr = bfd_get_32 (abfd, raw->r_address);
1019   res->sym_ptr_ptr = NULL;
1020   res->addend = 0;
1021   
1022   if (addr & BFD_MACH_O_SR_SCATTERED)
1023     {
1024       unsigned int j;
1025       bfd_vma symnum = bfd_get_32 (abfd, raw->r_symbolnum);
1026
1027       /* Scattered relocation, can't be extern. */
1028       reloc.r_scattered = 1;
1029       reloc.r_extern = 0;
1030
1031       /*   Extract section and offset from r_value (symnum).  */
1032       reloc.r_value = symnum;
1033       /* FIXME: This breaks when a symbol in a reloc exactly follows the
1034          end of the data for the section (e.g. in a calculation of section
1035          data length).  At present, the symbol will end up associated with
1036          the following section or, if it falls within alignment padding, as
1037          null - which will assert later.  */
1038       for (j = 0; j < mdata->nsects; j++)
1039         {
1040           bfd_mach_o_section *sect = mdata->sections[j];
1041           if (symnum >= sect->addr && symnum < sect->addr + sect->size)
1042             {
1043               res->sym_ptr_ptr = sect->bfdsection->symbol_ptr_ptr;
1044               res->addend = symnum - sect->addr;
1045               break;
1046             }
1047         }
1048
1049       /* Extract the info and address fields from r_address.  */
1050       reloc.r_type = BFD_MACH_O_GET_SR_TYPE (addr);
1051       reloc.r_length = BFD_MACH_O_GET_SR_LENGTH (addr);
1052       reloc.r_pcrel = addr & BFD_MACH_O_SR_PCREL;
1053       reloc.r_address = BFD_MACH_O_GET_SR_TYPE (addr);
1054       res->address = BFD_MACH_O_GET_SR_ADDRESS (addr);
1055     }
1056   else
1057     {
1058       unsigned int num;
1059       
1060       /* Non-scattered relocation.  */
1061       reloc.r_scattered = 0;
1062       
1063       /* The value and info fields have to be extracted dependent on target
1064          endian-ness.  */
1065       bfd_mach_o_swap_in_non_scattered_reloc (abfd, &reloc, raw->r_symbolnum);
1066       num = reloc.r_value;
1067
1068       if (reloc.r_extern)
1069           sym = syms + num;
1070       else if (reloc.r_scattered
1071                || (reloc.r_type != BFD_MACH_O_GENERIC_RELOC_PAIR))
1072         {
1073           BFD_ASSERT (num != 0);
1074           BFD_ASSERT (num <= mdata->nsects);
1075           sym = mdata->sections[num - 1]->bfdsection->symbol_ptr_ptr;
1076           /* For a symbol defined in section S, the addend (stored in the
1077              binary) contains the address of the section.  To comply with
1078              bfd convention, subtract the section address.
1079              Use the address from the header, so that the user can modify
1080              the vma of the section.  */
1081           res->addend = -mdata->sections[num - 1]->addr;
1082         }
1083       else /* ... The 'symnum' in a non-scattered PAIR will be 0x00ffffff.  */
1084         {
1085           /* Pairs for PPC LO/HI/HA are not scattered, but contain the offset
1086              in the lower 16bits of the address value.  So we have to find the
1087              'symbol' from the preceding reloc.  We do this even thoough the
1088              section symbol is probably not needed here, because NULL symbol
1089              values cause an assert in generic BFD code.  */
1090           sym = (res - 1)->sym_ptr_ptr;
1091         }
1092       res->sym_ptr_ptr = sym;
1093       
1094       /* The 'address' is just r_address.
1095          ??? maybe this should be masked with  0xffffff for safety.  */
1096       res->address = addr;
1097       reloc.r_address = addr;
1098     }
1099   
1100   /* We have set up a reloc with all the information present, so the swapper can
1101      modify address, value and addend fields, if necessary, to convey information
1102      in the generic BFD reloc that is mach-o specific.  */
1103
1104   if (!(*bed->_bfd_mach_o_swap_reloc_in)(res, &reloc))
1105     return -1;
1106   return 0;
1107 }
1108
1109 static int
1110 bfd_mach_o_canonicalize_relocs (bfd *abfd, unsigned long filepos,
1111                                 unsigned long count,
1112                                 arelent *res, asymbol **syms)
1113 {
1114   unsigned long i;
1115   struct mach_o_reloc_info_external *native_relocs;
1116   bfd_size_type native_size;
1117
1118   /* Allocate and read relocs.  */
1119   native_size = count * BFD_MACH_O_RELENT_SIZE;
1120   native_relocs =
1121     (struct mach_o_reloc_info_external *) bfd_malloc (native_size);
1122   if (native_relocs == NULL)
1123     return -1;
1124
1125   if (bfd_seek (abfd, filepos, SEEK_SET) != 0
1126       || bfd_bread (native_relocs, native_size, abfd) != native_size)
1127     goto err;
1128
1129   for (i = 0; i < count; i++)
1130     {
1131       if (bfd_mach_o_canonicalize_one_reloc (abfd, &native_relocs[i],
1132                                              &res[i], syms) < 0)
1133         goto err;
1134     }
1135   free (native_relocs);
1136   return i;
1137  err:
1138   free (native_relocs);
1139   return -1;
1140 }
1141
1142 long
1143 bfd_mach_o_canonicalize_reloc (bfd *abfd, asection *asect,
1144                                arelent **rels, asymbol **syms)
1145 {
1146   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
1147   unsigned long i;
1148   arelent *res;
1149
1150   if (asect->reloc_count == 0)
1151     return 0;
1152
1153   /* No need to go further if we don't know how to read relocs.  */
1154   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
1155     return 0;
1156
1157   if (asect->relocation == NULL)
1158     {
1159       res = bfd_malloc (asect->reloc_count * sizeof (arelent));
1160       if (res == NULL)
1161         return -1;
1162
1163       if (bfd_mach_o_canonicalize_relocs (abfd, asect->rel_filepos,
1164                                           asect->reloc_count, res, syms) < 0)
1165         {
1166           free (res);
1167           return -1;
1168         }
1169       asect->relocation = res;
1170     }
1171
1172   res = asect->relocation;
1173   for (i = 0; i < asect->reloc_count; i++)
1174     rels[i] = &res[i];
1175   rels[i] = NULL;
1176
1177   return i;
1178 }
1179
1180 long
1181 bfd_mach_o_get_dynamic_reloc_upper_bound (bfd *abfd)
1182 {
1183   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
1184
1185   if (mdata->dysymtab == NULL)
1186     return 1;
1187   return (mdata->dysymtab->nextrel + mdata->dysymtab->nlocrel + 1)
1188     * sizeof (arelent *);
1189 }
1190
1191 long
1192 bfd_mach_o_canonicalize_dynamic_reloc (bfd *abfd, arelent **rels,
1193                                        struct bfd_symbol **syms)
1194 {
1195   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
1196   bfd_mach_o_dysymtab_command *dysymtab = mdata->dysymtab;
1197   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
1198   unsigned long i;
1199   arelent *res;
1200
1201   if (dysymtab == NULL)
1202     return 0;
1203   if (dysymtab->nextrel == 0 && dysymtab->nlocrel == 0)
1204     return 0;
1205
1206   /* No need to go further if we don't know how to read relocs.  */
1207   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
1208     return 0;
1209
1210   if (mdata->dyn_reloc_cache == NULL)
1211     {
1212       res = bfd_malloc ((dysymtab->nextrel + dysymtab->nlocrel)
1213                         * sizeof (arelent));
1214       if (res == NULL)
1215         return -1;
1216
1217       if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->extreloff,
1218                                           dysymtab->nextrel, res, syms) < 0)
1219         {
1220           free (res);
1221           return -1;
1222         }
1223
1224       if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->locreloff,
1225                                           dysymtab->nlocrel,
1226                                           res + dysymtab->nextrel, syms) < 0)
1227         {
1228           free (res);
1229           return -1;
1230         }
1231
1232       mdata->dyn_reloc_cache = res;
1233     }
1234
1235   res = mdata->dyn_reloc_cache;
1236   for (i = 0; i < dysymtab->nextrel + dysymtab->nlocrel; i++)
1237     rels[i] = &res[i];
1238   rels[i] = NULL;
1239   return i;
1240 }
1241
1242 /* In addition to the need to byte-swap the symbol number, the bit positions
1243    of the fields in the relocation information vary per target endian-ness.  */
1244
1245 static void
1246 bfd_mach_o_swap_out_non_scattered_reloc (bfd *abfd, unsigned char *fields,
1247                                        bfd_mach_o_reloc_info *rel)
1248 {
1249   unsigned char info = 0;
1250
1251   BFD_ASSERT (rel->r_type <= 15);
1252   BFD_ASSERT (rel->r_length <= 3);
1253
1254   if (bfd_big_endian (abfd))
1255     {
1256       fields[0] = (rel->r_value >> 16) & 0xff;
1257       fields[1] = (rel->r_value >> 8) & 0xff;
1258       fields[2] = rel->r_value & 0xff;
1259       info |= rel->r_type << BFD_MACH_O_BE_TYPE_SHIFT;
1260       info |= rel->r_pcrel ? BFD_MACH_O_BE_PCREL : 0;
1261       info |= rel->r_length << BFD_MACH_O_BE_LENGTH_SHIFT;
1262       info |= rel->r_extern ? BFD_MACH_O_BE_EXTERN : 0;
1263     }
1264   else
1265     {
1266       fields[2] = (rel->r_value >> 16) & 0xff;
1267       fields[1] = (rel->r_value >> 8) & 0xff;
1268       fields[0] = rel->r_value & 0xff;
1269       info |= rel->r_type << BFD_MACH_O_LE_TYPE_SHIFT;
1270       info |= rel->r_pcrel ? BFD_MACH_O_LE_PCREL : 0;
1271       info |= rel->r_length << BFD_MACH_O_LE_LENGTH_SHIFT;
1272       info |= rel->r_extern ? BFD_MACH_O_LE_EXTERN : 0;
1273     }
1274   fields[3] = info;
1275 }
1276
1277 static bfd_boolean
1278 bfd_mach_o_write_relocs (bfd *abfd, bfd_mach_o_section *section)
1279 {
1280   unsigned int i;
1281   arelent **entries;
1282   asection *sec;
1283   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
1284
1285   sec = section->bfdsection;
1286   if (sec->reloc_count == 0)
1287     return TRUE;
1288
1289   if (bed->_bfd_mach_o_swap_reloc_out == NULL)
1290     return TRUE;
1291
1292   if (bfd_seek (abfd, section->reloff, SEEK_SET) != 0)
1293     return FALSE;
1294
1295   /* Convert and write.  */
1296   entries = section->bfdsection->orelocation;
1297   for (i = 0; i < section->nreloc; i++)
1298     {
1299       arelent *rel = entries[i];
1300       struct mach_o_reloc_info_external raw;
1301       bfd_mach_o_reloc_info info, *pinfo = &info;
1302
1303       /* Convert relocation to an intermediate representation.  */
1304       if (!(*bed->_bfd_mach_o_swap_reloc_out) (rel, pinfo))
1305         return FALSE;
1306
1307       /* Lower the relocation info.  */
1308       if (pinfo->r_scattered)
1309         {
1310           unsigned long v;
1311
1312           v = BFD_MACH_O_SR_SCATTERED
1313             | (pinfo->r_pcrel ? BFD_MACH_O_SR_PCREL : 0)
1314             | BFD_MACH_O_SET_SR_LENGTH(pinfo->r_length)
1315             | BFD_MACH_O_SET_SR_TYPE(pinfo->r_type)
1316             | BFD_MACH_O_SET_SR_ADDRESS(pinfo->r_address);
1317           /* Note: scattered relocs have field in reverse order...  */
1318           bfd_put_32 (abfd, v, raw.r_address);
1319           bfd_put_32 (abfd, pinfo->r_value, raw.r_symbolnum);
1320         }
1321       else
1322         {
1323           bfd_put_32 (abfd, pinfo->r_address, raw.r_address);
1324           bfd_mach_o_swap_out_non_scattered_reloc (abfd, raw.r_symbolnum,
1325                                                    pinfo);
1326         }
1327
1328       if (bfd_bwrite (&raw, BFD_MACH_O_RELENT_SIZE, abfd)
1329           != BFD_MACH_O_RELENT_SIZE)
1330         return FALSE;
1331     }
1332   return TRUE;
1333 }
1334
1335 static int
1336 bfd_mach_o_write_section_32 (bfd *abfd, bfd_mach_o_section *section)
1337 {
1338   struct mach_o_section_32_external raw;
1339
1340   memcpy (raw.sectname, section->sectname, 16);
1341   memcpy (raw.segname, section->segname, 16);
1342   bfd_h_put_32 (abfd, section->addr, raw.addr);
1343   bfd_h_put_32 (abfd, section->size, raw.size);
1344   bfd_h_put_32 (abfd, section->offset, raw.offset);
1345   bfd_h_put_32 (abfd, section->align, raw.align);
1346   bfd_h_put_32 (abfd, section->reloff, raw.reloff);
1347   bfd_h_put_32 (abfd, section->nreloc, raw.nreloc);
1348   bfd_h_put_32 (abfd, section->flags, raw.flags);
1349   bfd_h_put_32 (abfd, section->reserved1, raw.reserved1);
1350   bfd_h_put_32 (abfd, section->reserved2, raw.reserved2);
1351
1352   if (bfd_bwrite (&raw, BFD_MACH_O_SECTION_SIZE, abfd)
1353       != BFD_MACH_O_SECTION_SIZE)
1354     return -1;
1355
1356   return 0;
1357 }
1358
1359 static int
1360 bfd_mach_o_write_section_64 (bfd *abfd, bfd_mach_o_section *section)
1361 {
1362   struct mach_o_section_64_external raw;
1363
1364   memcpy (raw.sectname, section->sectname, 16);
1365   memcpy (raw.segname, section->segname, 16);
1366   bfd_h_put_64 (abfd, section->addr, raw.addr);
1367   bfd_h_put_64 (abfd, section->size, raw.size);
1368   bfd_h_put_32 (abfd, section->offset, raw.offset);
1369   bfd_h_put_32 (abfd, section->align, raw.align);
1370   bfd_h_put_32 (abfd, section->reloff, raw.reloff);
1371   bfd_h_put_32 (abfd, section->nreloc, raw.nreloc);
1372   bfd_h_put_32 (abfd, section->flags, raw.flags);
1373   bfd_h_put_32 (abfd, section->reserved1, raw.reserved1);
1374   bfd_h_put_32 (abfd, section->reserved2, raw.reserved2);
1375   bfd_h_put_32 (abfd, section->reserved3, raw.reserved3);
1376
1377   if (bfd_bwrite (&raw, BFD_MACH_O_SECTION_64_SIZE, abfd)
1378       != BFD_MACH_O_SECTION_64_SIZE)
1379     return -1;
1380
1381   return 0;
1382 }
1383
1384 static int
1385 bfd_mach_o_write_segment_32 (bfd *abfd, bfd_mach_o_load_command *command)
1386 {
1387   struct mach_o_segment_command_32_external raw;
1388   bfd_mach_o_segment_command *seg = &command->command.segment;
1389   bfd_mach_o_section *sec;
1390
1391   BFD_ASSERT (command->type == BFD_MACH_O_LC_SEGMENT);
1392
1393   for (sec = seg->sect_head; sec != NULL; sec = sec->next)
1394     if (!bfd_mach_o_write_relocs (abfd, sec))
1395       return -1;
1396
1397   memcpy (raw.segname, seg->segname, 16);
1398   bfd_h_put_32 (abfd, seg->vmaddr, raw.vmaddr);
1399   bfd_h_put_32 (abfd, seg->vmsize, raw.vmsize);
1400   bfd_h_put_32 (abfd, seg->fileoff, raw.fileoff);
1401   bfd_h_put_32 (abfd, seg->filesize, raw.filesize);
1402   bfd_h_put_32 (abfd, seg->maxprot, raw.maxprot);
1403   bfd_h_put_32 (abfd, seg->initprot, raw.initprot);
1404   bfd_h_put_32 (abfd, seg->nsects, raw.nsects);
1405   bfd_h_put_32 (abfd, seg->flags, raw.flags);
1406   
1407   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
1408       || bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1409     return -1;
1410
1411   for (sec = seg->sect_head; sec != NULL; sec = sec->next)
1412     if (bfd_mach_o_write_section_32 (abfd, sec))
1413       return -1;
1414
1415   return 0;
1416 }
1417
1418 static int
1419 bfd_mach_o_write_segment_64 (bfd *abfd, bfd_mach_o_load_command *command)
1420 {
1421   struct mach_o_segment_command_64_external raw;
1422   bfd_mach_o_segment_command *seg = &command->command.segment;
1423   bfd_mach_o_section *sec;
1424
1425   BFD_ASSERT (command->type == BFD_MACH_O_LC_SEGMENT_64);
1426
1427   for (sec = seg->sect_head; sec != NULL; sec = sec->next)
1428     if (!bfd_mach_o_write_relocs (abfd, sec))
1429       return -1;
1430
1431   memcpy (raw.segname, seg->segname, 16);
1432   bfd_h_put_64 (abfd, seg->vmaddr, raw.vmaddr);
1433   bfd_h_put_64 (abfd, seg->vmsize, raw.vmsize);
1434   bfd_h_put_64 (abfd, seg->fileoff, raw.fileoff);
1435   bfd_h_put_64 (abfd, seg->filesize, raw.filesize);
1436   bfd_h_put_32 (abfd, seg->maxprot, raw.maxprot);
1437   bfd_h_put_32 (abfd, seg->initprot, raw.initprot);
1438   bfd_h_put_32 (abfd, seg->nsects, raw.nsects);
1439   bfd_h_put_32 (abfd, seg->flags, raw.flags);
1440
1441   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
1442       || bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1443     return -1;
1444
1445   for (sec = seg->sect_head; sec != NULL; sec = sec->next)
1446     if (bfd_mach_o_write_section_64 (abfd, sec))
1447       return -1;
1448
1449   return 0;
1450 }
1451
1452 static bfd_boolean
1453 bfd_mach_o_write_symtab (bfd *abfd, bfd_mach_o_load_command *command)
1454 {
1455   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
1456   bfd_mach_o_symtab_command *sym = &command->command.symtab;
1457   unsigned long i;
1458   unsigned int wide = bfd_mach_o_wide_p (abfd);
1459   unsigned int symlen = wide ? BFD_MACH_O_NLIST_64_SIZE : BFD_MACH_O_NLIST_SIZE;
1460   struct bfd_strtab_hash *strtab;
1461   asymbol **symbols = bfd_get_outsymbols (abfd);
1462
1463   BFD_ASSERT (command->type == BFD_MACH_O_LC_SYMTAB);
1464
1465   /* Write the symbols first.  */
1466   mdata->filelen = FILE_ALIGN(mdata->filelen, wide ? 3 : 2);
1467   sym->symoff = mdata->filelen;
1468   if (bfd_seek (abfd, sym->symoff, SEEK_SET) != 0)
1469     return FALSE;
1470
1471   sym->nsyms = bfd_get_symcount (abfd);
1472   mdata->filelen += sym->nsyms * symlen;
1473
1474   strtab = _bfd_stringtab_init ();
1475   if (strtab == NULL)
1476     return FALSE;
1477
1478   if (sym->nsyms > 0)
1479     /* Although we don't strictly need to do this, for compatibility with
1480        Darwin system tools, actually output an empty string for the index
1481        0 entry.  */
1482     _bfd_stringtab_add (strtab, "", TRUE, FALSE);
1483
1484   for (i = 0; i < sym->nsyms; i++)
1485     {
1486       bfd_size_type str_index;
1487       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
1488      
1489       if (s->symbol.name == 0 || s->symbol.name[0] == '\0')
1490         /* An index of 0 always means the empty string.  */
1491         str_index = 0;
1492       else
1493         {
1494           str_index = _bfd_stringtab_add (strtab, s->symbol.name, TRUE, FALSE);
1495
1496           if (str_index == (bfd_size_type) -1)
1497             goto err;
1498         }
1499
1500       if (wide)
1501         {
1502           struct mach_o_nlist_64_external raw;
1503
1504           bfd_h_put_32 (abfd, str_index, raw.n_strx);
1505           bfd_h_put_8 (abfd, s->n_type, raw.n_type);
1506           bfd_h_put_8 (abfd, s->n_sect, raw.n_sect);
1507           bfd_h_put_16 (abfd, s->n_desc, raw.n_desc);
1508           bfd_h_put_64 (abfd, s->symbol.section->vma + s->symbol.value,
1509                         raw.n_value);
1510
1511           if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1512             goto err;
1513         }
1514       else
1515         {
1516           struct mach_o_nlist_external raw;
1517
1518           bfd_h_put_32 (abfd, str_index, raw.n_strx);
1519           bfd_h_put_8 (abfd, s->n_type, raw.n_type);
1520           bfd_h_put_8 (abfd, s->n_sect, raw.n_sect);
1521           bfd_h_put_16 (abfd, s->n_desc, raw.n_desc);
1522           bfd_h_put_32 (abfd, s->symbol.section->vma + s->symbol.value,
1523                         raw.n_value);
1524
1525           if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1526             goto err;
1527         }
1528     }
1529   sym->strsize = _bfd_stringtab_size (strtab);
1530   sym->stroff = mdata->filelen;
1531   mdata->filelen += sym->strsize;
1532
1533   if (_bfd_stringtab_emit (abfd, strtab) != TRUE)
1534     goto err;
1535   _bfd_stringtab_free (strtab);
1536
1537   /* The command.  */
1538   {
1539     struct mach_o_symtab_command_external raw;
1540
1541     bfd_h_put_32 (abfd, sym->symoff, raw.symoff);
1542     bfd_h_put_32 (abfd, sym->nsyms, raw.nsyms);
1543     bfd_h_put_32 (abfd, sym->stroff, raw.stroff);
1544     bfd_h_put_32 (abfd, sym->strsize, raw.strsize);
1545
1546     if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
1547         || bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1548       return FALSE;
1549   }
1550
1551   return TRUE;
1552
1553  err:
1554   _bfd_stringtab_free (strtab);
1555   return FALSE;
1556 }
1557
1558 /* Write a dysymtab command.
1559    TODO: Possibly coalesce writes of smaller objects.  */
1560
1561 static bfd_boolean
1562 bfd_mach_o_write_dysymtab (bfd *abfd, bfd_mach_o_load_command *command)
1563 {
1564   bfd_mach_o_dysymtab_command *cmd = &command->command.dysymtab;
1565
1566   BFD_ASSERT (command->type == BFD_MACH_O_LC_DYSYMTAB);
1567
1568   if (cmd->nmodtab != 0)
1569     {
1570       unsigned int i;
1571
1572       if (bfd_seek (abfd, cmd->modtaboff, SEEK_SET) != 0)
1573         return FALSE;
1574
1575       for (i = 0; i < cmd->nmodtab; i++)
1576         {
1577           bfd_mach_o_dylib_module *module = &cmd->dylib_module[i];
1578           unsigned int iinit;
1579           unsigned int ninit;
1580
1581           iinit = module->iinit & 0xffff;
1582           iinit |= ((module->iterm & 0xffff) << 16);
1583
1584           ninit = module->ninit & 0xffff;
1585           ninit |= ((module->nterm & 0xffff) << 16);
1586
1587           if (bfd_mach_o_wide_p (abfd))
1588             {
1589               struct mach_o_dylib_module_64_external w;
1590
1591               bfd_h_put_32 (abfd, module->module_name_idx, &w.module_name);
1592               bfd_h_put_32 (abfd, module->iextdefsym, &w.iextdefsym);
1593               bfd_h_put_32 (abfd, module->nextdefsym, &w.nextdefsym);
1594               bfd_h_put_32 (abfd, module->irefsym, &w.irefsym);
1595               bfd_h_put_32 (abfd, module->nrefsym, &w.nrefsym);
1596               bfd_h_put_32 (abfd, module->ilocalsym, &w.ilocalsym);
1597               bfd_h_put_32 (abfd, module->nlocalsym, &w.nlocalsym);
1598               bfd_h_put_32 (abfd, module->iextrel, &w.iextrel);
1599               bfd_h_put_32 (abfd, module->nextrel, &w.nextrel);
1600               bfd_h_put_32 (abfd, iinit, &w.iinit_iterm);
1601               bfd_h_put_32 (abfd, ninit, &w.ninit_nterm);
1602               bfd_h_put_64 (abfd, module->objc_module_info_addr,
1603                             &w.objc_module_info_addr);
1604               bfd_h_put_32 (abfd, module->objc_module_info_size,
1605                             &w.objc_module_info_size);
1606
1607               if (bfd_bwrite ((void *) &w, sizeof (w), abfd) != sizeof (w))
1608                 return FALSE;
1609             }
1610           else
1611             {
1612               struct mach_o_dylib_module_external n;
1613
1614               bfd_h_put_32 (abfd, module->module_name_idx, &n.module_name);
1615               bfd_h_put_32 (abfd, module->iextdefsym, &n.iextdefsym);
1616               bfd_h_put_32 (abfd, module->nextdefsym, &n.nextdefsym);
1617               bfd_h_put_32 (abfd, module->irefsym, &n.irefsym);
1618               bfd_h_put_32 (abfd, module->nrefsym, &n.nrefsym);
1619               bfd_h_put_32 (abfd, module->ilocalsym, &n.ilocalsym);
1620               bfd_h_put_32 (abfd, module->nlocalsym, &n.nlocalsym);
1621               bfd_h_put_32 (abfd, module->iextrel, &n.iextrel);
1622               bfd_h_put_32 (abfd, module->nextrel, &n.nextrel);
1623               bfd_h_put_32 (abfd, iinit, &n.iinit_iterm);
1624               bfd_h_put_32 (abfd, ninit, &n.ninit_nterm);
1625               bfd_h_put_32 (abfd, module->objc_module_info_addr,
1626                             &n.objc_module_info_addr);
1627               bfd_h_put_32 (abfd, module->objc_module_info_size,
1628                             &n.objc_module_info_size);
1629
1630               if (bfd_bwrite ((void *) &n, sizeof (n), abfd) != sizeof (n))
1631                 return FALSE;
1632             }
1633         }
1634     }
1635
1636   if (cmd->ntoc != 0)
1637     {
1638       unsigned int i;
1639
1640       if (bfd_seek (abfd, cmd->tocoff, SEEK_SET) != 0)
1641         return FALSE;
1642
1643       for (i = 0; i < cmd->ntoc; i++)
1644         {
1645           struct mach_o_dylib_table_of_contents_external raw;
1646           bfd_mach_o_dylib_table_of_content *toc = &cmd->dylib_toc[i];
1647
1648           bfd_h_put_32 (abfd, toc->symbol_index, &raw.symbol_index);
1649           bfd_h_put_32 (abfd, toc->module_index, &raw.module_index);
1650
1651           if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1652             return FALSE;
1653         }
1654     }
1655   
1656   if (cmd->nindirectsyms > 0)
1657     {
1658       unsigned int i;
1659
1660       if (bfd_seek (abfd, cmd->indirectsymoff, SEEK_SET) != 0)
1661         return FALSE;
1662
1663       for (i = 0; i < cmd->nindirectsyms; ++i)
1664         {
1665           unsigned char raw[4];
1666
1667           bfd_h_put_32 (abfd, cmd->indirect_syms[i], &raw);
1668           if (bfd_bwrite (raw, sizeof (raw), abfd) != sizeof (raw))
1669             return FALSE;
1670         }    
1671     }
1672
1673   if (cmd->nextrefsyms != 0)
1674     {
1675       unsigned int i;
1676
1677       if (bfd_seek (abfd, cmd->extrefsymoff, SEEK_SET) != 0)
1678         return FALSE;
1679
1680       for (i = 0; i < cmd->nextrefsyms; i++)
1681         {
1682           unsigned long v;
1683           unsigned char raw[4];
1684           bfd_mach_o_dylib_reference *ref = &cmd->ext_refs[i];
1685
1686           /* Fields isym and flags are written as bit-fields, thus we need
1687              a specific processing for endianness.  */
1688
1689           if (bfd_big_endian (abfd))
1690             {
1691               v = ((ref->isym & 0xffffff) << 8);
1692               v |= ref->flags & 0xff;
1693             }
1694           else
1695             {
1696               v = ref->isym  & 0xffffff;
1697               v |= ((ref->flags & 0xff) << 24);
1698             }
1699
1700           bfd_h_put_32 (abfd, v, raw);
1701           if (bfd_bwrite (raw, sizeof (raw), abfd) != sizeof (raw))
1702             return FALSE;
1703         }
1704     }
1705
1706   /* The command.  */
1707   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0)
1708     return FALSE;
1709   else
1710     {
1711       struct mach_o_dysymtab_command_external raw;
1712
1713       bfd_h_put_32 (abfd, cmd->ilocalsym, &raw.ilocalsym);
1714       bfd_h_put_32 (abfd, cmd->nlocalsym, &raw.nlocalsym);
1715       bfd_h_put_32 (abfd, cmd->iextdefsym, &raw.iextdefsym);
1716       bfd_h_put_32 (abfd, cmd->nextdefsym, &raw.nextdefsym);
1717       bfd_h_put_32 (abfd, cmd->iundefsym, &raw.iundefsym);
1718       bfd_h_put_32 (abfd, cmd->nundefsym, &raw.nundefsym);
1719       bfd_h_put_32 (abfd, cmd->tocoff, &raw.tocoff);
1720       bfd_h_put_32 (abfd, cmd->ntoc, &raw.ntoc);
1721       bfd_h_put_32 (abfd, cmd->modtaboff, &raw.modtaboff);
1722       bfd_h_put_32 (abfd, cmd->nmodtab, &raw.nmodtab);
1723       bfd_h_put_32 (abfd, cmd->extrefsymoff, &raw.extrefsymoff);
1724       bfd_h_put_32 (abfd, cmd->nextrefsyms, &raw.nextrefsyms);
1725       bfd_h_put_32 (abfd, cmd->indirectsymoff, &raw.indirectsymoff);
1726       bfd_h_put_32 (abfd, cmd->nindirectsyms, &raw.nindirectsyms);
1727       bfd_h_put_32 (abfd, cmd->extreloff, &raw.extreloff);
1728       bfd_h_put_32 (abfd, cmd->nextrel, &raw.nextrel);
1729       bfd_h_put_32 (abfd, cmd->locreloff, &raw.locreloff);
1730       bfd_h_put_32 (abfd, cmd->nlocrel, &raw.nlocrel);
1731
1732       if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
1733         return FALSE;
1734     }
1735
1736   return TRUE;
1737 }
1738
1739 static unsigned
1740 bfd_mach_o_primary_symbol_sort_key (bfd_mach_o_asymbol *s)
1741 {
1742   unsigned mtyp = s->n_type & BFD_MACH_O_N_TYPE;
1743
1744   /* Just leave debug symbols where they are (pretend they are local, and
1745      then they will just be sorted on position).  */
1746   if (s->n_type & BFD_MACH_O_N_STAB)
1747     return 0;
1748
1749   /* Local (we should never see an undefined local AFAICT).  */
1750   if (! (s->n_type & (BFD_MACH_O_N_EXT | BFD_MACH_O_N_PEXT)))
1751     return 0;
1752
1753   /* Common symbols look like undefined externs.  */
1754   if (mtyp == BFD_MACH_O_N_UNDF)
1755     return 2;
1756
1757   /* A defined non-local, non-debug symbol.  */
1758   return 1;
1759 }
1760
1761 static int
1762 bfd_mach_o_cf_symbols (const void *a, const void *b)
1763 {
1764   bfd_mach_o_asymbol *sa = *(bfd_mach_o_asymbol **) a;
1765   bfd_mach_o_asymbol *sb = *(bfd_mach_o_asymbol **) b;
1766   unsigned int soa, sob;
1767
1768   soa = bfd_mach_o_primary_symbol_sort_key (sa);
1769   sob = bfd_mach_o_primary_symbol_sort_key (sb);
1770   if (soa < sob)
1771     return -1;
1772
1773   if (soa > sob)
1774     return 1;
1775
1776   /* If it's local or stab, just preserve the input order.  */
1777   if (soa == 0)
1778     {
1779       if (sa->symbol.udata.i < sb->symbol.udata.i)
1780         return -1;
1781       if (sa->symbol.udata.i > sb->symbol.udata.i)
1782         return  1;
1783
1784       /* This is probably an error.  */
1785       return 0;
1786     }
1787
1788   /* The second sort key is name.  */
1789   return strcmp (sa->symbol.name, sb->symbol.name);
1790 }
1791
1792 /* Process the symbols.
1793
1794    This should be OK for single-module files - but it is not likely to work
1795    for multi-module shared libraries.
1796
1797    (a) If the application has not filled in the relevant mach-o fields, make
1798        an estimate.
1799
1800    (b) Order them, like this:
1801         (  i) local.
1802                 (unsorted)
1803         ( ii) external defined
1804                 (by name)
1805         (iii) external undefined/common
1806                 (by name)
1807         ( iv) common
1808                 (by name)
1809 */
1810
1811 static bfd_boolean
1812 bfd_mach_o_mangle_symbols (bfd *abfd)
1813 {
1814   unsigned long i;
1815   asymbol **symbols = bfd_get_outsymbols (abfd);
1816
1817   if (symbols == NULL || bfd_get_symcount (abfd) == 0)
1818     return TRUE;
1819
1820   for (i = 0; i < bfd_get_symcount (abfd); i++)
1821     {
1822       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
1823
1824       /* We use this value, which is out-of-range as a symbol index, to signal
1825          that the mach-o-specific data are not filled in and need to be created
1826          from the bfd values.  It is much preferable for the application to do
1827          this, since more meaningful diagnostics can be made that way.  */
1828
1829       if (s->symbol.udata.i == SYM_MACHO_FIELDS_UNSET)
1830         {
1831           /* No symbol information has been set - therefore determine
1832              it from the bfd symbol flags/info.  */
1833           if (s->symbol.section == bfd_abs_section_ptr)
1834             s->n_type = BFD_MACH_O_N_ABS;
1835           else if (s->symbol.section == bfd_und_section_ptr)
1836             {
1837               s->n_type = BFD_MACH_O_N_UNDF;
1838               if (s->symbol.flags & BSF_WEAK)
1839                 s->n_desc |= BFD_MACH_O_N_WEAK_REF;
1840               /* mach-o automatically makes undefined symbols extern.  */
1841               s->n_type |= BFD_MACH_O_N_EXT;
1842               s->symbol.flags |= BSF_GLOBAL;
1843             }
1844           else if (s->symbol.section == bfd_com_section_ptr)
1845             {
1846               s->n_type = BFD_MACH_O_N_UNDF | BFD_MACH_O_N_EXT;
1847               s->symbol.flags |= BSF_GLOBAL;
1848             }
1849           else
1850             s->n_type = BFD_MACH_O_N_SECT;
1851           
1852           if (s->symbol.flags & BSF_GLOBAL)
1853             s->n_type |= BFD_MACH_O_N_EXT;
1854         }
1855
1856       /* Put the section index in, where required.  */
1857       if ((s->symbol.section != bfd_abs_section_ptr
1858           && s->symbol.section != bfd_und_section_ptr
1859           && s->symbol.section != bfd_com_section_ptr)
1860           || ((s->n_type & BFD_MACH_O_N_STAB) != 0
1861                && s->symbol.name == NULL))
1862         s->n_sect = s->symbol.section->target_index;
1863
1864       /* Number to preserve order for local and debug syms.  */
1865       s->symbol.udata.i = i;
1866     }
1867
1868   /* Sort the symbols.  */
1869   qsort ((void *) symbols, (size_t) bfd_get_symcount (abfd),
1870          sizeof (asymbol *), bfd_mach_o_cf_symbols);
1871
1872   for (i = 0; i < bfd_get_symcount (abfd); ++i)
1873     {
1874       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
1875       s->symbol.udata.i = i;  /* renumber.  */
1876     }
1877
1878   return TRUE;
1879 }
1880
1881 /* We build a flat table of sections, which can be re-ordered if necessary.
1882    Fill in the section number and other mach-o-specific data.  */
1883
1884 static bfd_boolean
1885 bfd_mach_o_mangle_sections (bfd *abfd, bfd_mach_o_data_struct *mdata)
1886 {
1887   asection *sec;
1888   unsigned target_index;
1889   unsigned nsect;
1890
1891   nsect = bfd_count_sections (abfd);
1892   
1893   /* Don't do it if it's already set - assume the application knows what it's
1894      doing.  */
1895   if (mdata->nsects == nsect
1896       && (mdata->nsects == 0 || mdata->sections != NULL))
1897     return TRUE;
1898
1899   mdata->nsects = nsect;
1900   mdata->sections = bfd_alloc (abfd, 
1901                                mdata->nsects * sizeof (bfd_mach_o_section *));
1902   if (mdata->sections == NULL)
1903     return FALSE;
1904
1905   /* We need to check that this can be done...  */
1906   if (nsect > 255)
1907     (*_bfd_error_handler) (_("mach-o: there are too many sections (%d)"
1908                              " maximum is 255,\n"), nsect);
1909
1910   /* Create Mach-O sections.
1911      Section type, attribute and align should have been set when the 
1912      section was created - either read in or specified.  */
1913   target_index = 0;
1914   for (sec = abfd->sections; sec; sec = sec->next)
1915     {
1916       unsigned bfd_align = bfd_get_section_alignment (abfd, sec);
1917       bfd_mach_o_section *msect = bfd_mach_o_get_mach_o_section (sec);
1918
1919       mdata->sections[target_index] = msect;
1920
1921       msect->addr = bfd_get_section_vma (abfd, sec);
1922       msect->size = bfd_get_section_size (sec);
1923
1924       /* Use the largest alignment set, in case it was bumped after the 
1925          section was created.  */
1926       msect->align = msect->align > bfd_align ? msect->align : bfd_align;
1927
1928       msect->offset = 0;
1929       sec->target_index = ++target_index;
1930     }
1931
1932   return TRUE;
1933 }
1934
1935 bfd_boolean
1936 bfd_mach_o_write_contents (bfd *abfd)
1937 {
1938   unsigned int i;
1939   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
1940
1941   /* Make the commands, if not already present.  */
1942   if (mdata->header.ncmds == 0)
1943     if (!bfd_mach_o_build_commands (abfd))
1944       return FALSE;
1945
1946   if (!bfd_mach_o_write_header (abfd, &mdata->header))
1947     return FALSE;
1948
1949   for (i = 0; i < mdata->header.ncmds; i++)
1950     {
1951       struct mach_o_load_command_external raw;
1952       bfd_mach_o_load_command *cur = &mdata->commands[i];
1953       unsigned long typeflag;
1954
1955       typeflag = cur->type | (cur->type_required ? BFD_MACH_O_LC_REQ_DYLD : 0);
1956
1957       bfd_h_put_32 (abfd, typeflag, raw.cmd);
1958       bfd_h_put_32 (abfd, cur->len, raw.cmdsize);
1959
1960       if (bfd_seek (abfd, cur->offset, SEEK_SET) != 0
1961           || bfd_bwrite (&raw, BFD_MACH_O_LC_SIZE, abfd) != 8)
1962         return FALSE;
1963
1964       switch (cur->type)
1965         {
1966         case BFD_MACH_O_LC_SEGMENT:
1967           if (bfd_mach_o_write_segment_32 (abfd, cur) != 0)
1968             return FALSE;
1969           break;
1970         case BFD_MACH_O_LC_SEGMENT_64:
1971           if (bfd_mach_o_write_segment_64 (abfd, cur) != 0)
1972             return FALSE;
1973           break;
1974         case BFD_MACH_O_LC_SYMTAB:
1975           if (!bfd_mach_o_write_symtab (abfd, cur))
1976             return FALSE;
1977           break;
1978         case BFD_MACH_O_LC_DYSYMTAB:
1979           if (!bfd_mach_o_write_dysymtab (abfd, cur))
1980             return FALSE;
1981           break;
1982         case BFD_MACH_O_LC_SYMSEG:
1983           break;
1984         case BFD_MACH_O_LC_THREAD:
1985         case BFD_MACH_O_LC_UNIXTHREAD:
1986           if (bfd_mach_o_write_thread (abfd, cur) != 0)
1987             return FALSE;
1988           break;
1989         case BFD_MACH_O_LC_LOADFVMLIB:
1990         case BFD_MACH_O_LC_IDFVMLIB:
1991         case BFD_MACH_O_LC_IDENT:
1992         case BFD_MACH_O_LC_FVMFILE:
1993         case BFD_MACH_O_LC_PREPAGE:
1994         case BFD_MACH_O_LC_LOAD_DYLIB:
1995         case BFD_MACH_O_LC_LOAD_WEAK_DYLIB:
1996         case BFD_MACH_O_LC_ID_DYLIB:
1997         case BFD_MACH_O_LC_REEXPORT_DYLIB:
1998         case BFD_MACH_O_LC_LOAD_UPWARD_DYLIB:
1999         case BFD_MACH_O_LC_LOAD_DYLINKER:
2000         case BFD_MACH_O_LC_ID_DYLINKER:
2001         case BFD_MACH_O_LC_PREBOUND_DYLIB:
2002         case BFD_MACH_O_LC_ROUTINES:
2003         case BFD_MACH_O_LC_SUB_FRAMEWORK:
2004           break;
2005         default:
2006           (*_bfd_error_handler) (_("unable to write unknown load command 0x%lx"),
2007                                  (unsigned long) cur->type);
2008           return FALSE;
2009         }
2010     }
2011
2012   return TRUE;
2013 }
2014
2015 static void
2016 bfd_mach_o_append_section_to_segment (bfd_mach_o_segment_command *seg,
2017                                       asection *sec)
2018 {
2019   bfd_mach_o_section *s = (bfd_mach_o_section *)sec->used_by_bfd;
2020   if (seg->sect_head == NULL)
2021     seg->sect_head = s;
2022   else
2023     seg->sect_tail->next = s;
2024   seg->sect_tail = s;
2025 }
2026
2027 /* Create section Mach-O flags from BFD flags.  */
2028
2029 static void
2030 bfd_mach_o_set_section_flags_from_bfd (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
2031 {
2032   flagword bfd_flags;
2033   bfd_mach_o_section *s = bfd_mach_o_get_mach_o_section (sec);
2034
2035   /* Create default flags.  */
2036   bfd_flags = bfd_get_section_flags (abfd, sec);
2037   if ((bfd_flags & SEC_CODE) == SEC_CODE)
2038     s->flags = BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS
2039       | BFD_MACH_O_S_ATTR_SOME_INSTRUCTIONS
2040       | BFD_MACH_O_S_REGULAR;
2041   else if ((bfd_flags & (SEC_ALLOC | SEC_LOAD)) == SEC_ALLOC)
2042     s->flags = BFD_MACH_O_S_ZEROFILL;
2043   else if (bfd_flags & SEC_DEBUGGING)
2044     s->flags = BFD_MACH_O_S_REGULAR |  BFD_MACH_O_S_ATTR_DEBUG;
2045   else
2046     s->flags = BFD_MACH_O_S_REGULAR;
2047 }
2048
2049 /* Count the number of sections in the list for the segment named.
2050
2051    The special case of NULL or "" for the segment name is valid for
2052    an MH_OBJECT file and means 'all sections available'.  
2053    
2054    Requires that the sections table in mdata be filled in.  
2055
2056    Returns the number of sections (0 is valid).
2057    Any number > 255 signals an invalid section count, although we will,
2058    perhaps, allow the file to be written (in line with Darwin tools up
2059    to XCode 4). 
2060    
2061    A section count of (unsigned long) -1 signals a definite error.  */
2062
2063 static unsigned long
2064 bfd_mach_o_count_sections_for_seg (const char *segment,
2065                                    bfd_mach_o_data_struct *mdata)
2066 {
2067   unsigned i,j;
2068   if (mdata == NULL || mdata->sections == NULL)
2069     return (unsigned long) -1;
2070
2071   /* The MH_OBJECT case, all sections are considered; Although nsects is
2072      is an unsigned long, the maximum valid section count is 255 and this
2073      will have been checked already by mangle_sections.  */
2074   if (segment == NULL || segment[0] == '\0')
2075     return mdata->nsects;
2076
2077   /* Count the number of sections we see in this segment.  */
2078   j = 0;
2079   for (i = 0; i < mdata->nsects; ++i)
2080     {
2081       bfd_mach_o_section *s = mdata->sections[i];
2082       if (strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) == 0)
2083         j++;
2084     }
2085   return j;
2086 }
2087
2088 static bfd_boolean
2089 bfd_mach_o_build_seg_command (const char *segment,
2090                               bfd_mach_o_data_struct *mdata,
2091                               bfd_mach_o_segment_command *seg)
2092 {
2093   unsigned i;
2094   int is_mho = (segment == NULL || segment[0] == '\0');
2095
2096   /* Fill segment command.  */
2097   if (is_mho)
2098     memset (seg->segname, 0, sizeof (seg->segname));
2099   else
2100     strncpy (seg->segname, segment, sizeof (seg->segname));
2101
2102   /* TODO: fix this up for non-MH_OBJECT cases.  */
2103   seg->vmaddr = 0;
2104   seg->vmsize = 0;
2105
2106   seg->fileoff = mdata->filelen;
2107   seg->filesize = 0;
2108   seg->maxprot = BFD_MACH_O_PROT_READ | BFD_MACH_O_PROT_WRITE
2109                  | BFD_MACH_O_PROT_EXECUTE;
2110   seg->initprot = seg->maxprot;
2111   seg->flags = 0;
2112   seg->sect_head = NULL;
2113   seg->sect_tail = NULL;
2114
2115   /*  Append sections to the segment.  
2116
2117       This is a little tedious, we have to honor the need to account zerofill
2118       sections after all the rest.  This forces us to do the calculation of
2119       total vmsize in three passes so that any alignment increments are 
2120       properly accounted.  */
2121
2122   for (i = 0; i < mdata->nsects; ++i)
2123     {
2124       bfd_mach_o_section *s = mdata->sections[i];
2125       asection *sec = s->bfdsection;
2126
2127       /* If we're not making an MH_OBJECT, check whether this section is from
2128          our segment, and skip if not.  Otherwise, just add all sections.  */
2129       if (! is_mho 
2130           && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
2131         continue;
2132
2133       /* Although we account for zerofill section sizes in vm order, they are
2134          placed in the file in source sequence.  */
2135       bfd_mach_o_append_section_to_segment (seg, sec);
2136       s->offset = 0;
2137       
2138       /* Zerofill sections have zero file size & offset, 
2139          and are not written.  */
2140       if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) == BFD_MACH_O_S_ZEROFILL
2141           || (s->flags & BFD_MACH_O_SECTION_TYPE_MASK) 
2142               == BFD_MACH_O_S_GB_ZEROFILL)
2143         continue;
2144
2145       if (s->size > 0)
2146        {
2147           seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
2148           seg->vmsize += s->size;
2149
2150           seg->filesize = FILE_ALIGN (seg->filesize, s->align);
2151           seg->filesize += s->size;
2152
2153           mdata->filelen = FILE_ALIGN (mdata->filelen, s->align);
2154           s->offset = mdata->filelen;
2155         }
2156
2157       sec->filepos = s->offset;
2158       mdata->filelen += s->size;
2159     }
2160
2161   /* Now pass through again, for zerofill, only now we just update the vmsize.  */
2162   for (i = 0; i < mdata->nsects; ++i)
2163     {
2164       bfd_mach_o_section *s = mdata->sections[i];
2165
2166       if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) != BFD_MACH_O_S_ZEROFILL)
2167         continue;
2168
2169       if (! is_mho 
2170           && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
2171         continue;
2172
2173       if (s->size > 0)
2174         {
2175           seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
2176           seg->vmsize += s->size;
2177         }
2178     }
2179
2180   /* Now pass through again, for zerofill_GB.  */
2181   for (i = 0; i < mdata->nsects; ++i)
2182     {
2183       bfd_mach_o_section *s = mdata->sections[i];
2184  
2185       if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) != BFD_MACH_O_S_GB_ZEROFILL)
2186         continue;
2187
2188       if (! is_mho 
2189           && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
2190         continue;
2191
2192       if (s->size > 0)
2193         {
2194           seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
2195           seg->vmsize += s->size;
2196         }
2197     }
2198
2199   /* Allocate space for the relocations.  */
2200   mdata->filelen = FILE_ALIGN(mdata->filelen, 2);
2201
2202   for (i = 0; i < mdata->nsects; ++i)
2203     {
2204       bfd_mach_o_section *ms = mdata->sections[i];
2205       asection *sec = ms->bfdsection;
2206         
2207       if ((ms->nreloc = sec->reloc_count) == 0)
2208         {
2209           ms->reloff = 0;
2210           continue;
2211         }
2212       sec->rel_filepos = mdata->filelen;
2213       ms->reloff = sec->rel_filepos;
2214       mdata->filelen += sec->reloc_count * BFD_MACH_O_RELENT_SIZE;
2215     }
2216
2217   return TRUE;
2218 }
2219
2220 /* Count the number of indirect symbols in the image.
2221    Requires that the sections are in their final order.  */
2222
2223 static unsigned int
2224 bfd_mach_o_count_indirect_symbols (bfd *abfd, bfd_mach_o_data_struct *mdata)
2225 {
2226   unsigned int i;
2227   unsigned int nisyms = 0;
2228
2229   for (i = 0; i < mdata->nsects; ++i)
2230     {
2231       bfd_mach_o_section *sec = mdata->sections[i];
2232
2233       switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
2234         {
2235           case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
2236           case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
2237           case BFD_MACH_O_S_SYMBOL_STUBS:
2238             nisyms += bfd_mach_o_section_get_nbr_indirect (abfd, sec);
2239             break;
2240           default:
2241             break;
2242         }
2243     }
2244   return nisyms;
2245 }
2246
2247 static bfd_boolean
2248 bfd_mach_o_build_dysymtab_command (bfd *abfd,
2249                                    bfd_mach_o_data_struct *mdata,
2250                                    bfd_mach_o_load_command *cmd)
2251 {
2252   bfd_mach_o_dysymtab_command *dsym = &cmd->command.dysymtab;
2253
2254   /* TODO:
2255      We are not going to try and fill these in yet and, moreover, we are
2256      going to bail if they are already set.  */
2257   if (dsym->nmodtab != 0
2258       || dsym->ntoc != 0
2259       || dsym->nextrefsyms != 0)
2260     {
2261       (*_bfd_error_handler) (_("sorry: modtab, toc and extrefsyms are not yet"
2262                                 " implemented for dysymtab commands."));
2263       return FALSE;
2264     }
2265
2266   dsym->ilocalsym = 0;
2267
2268   if (bfd_get_symcount (abfd) > 0)
2269     {
2270       asymbol **symbols = bfd_get_outsymbols (abfd);
2271       unsigned long i;
2272
2273        /* Count the number of each kind of symbol.  */
2274       for (i = 0; i < bfd_get_symcount (abfd); ++i)
2275         {
2276           bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
2277           if (s->n_type & (BFD_MACH_O_N_EXT | BFD_MACH_O_N_PEXT))
2278             break;
2279         }
2280       dsym->nlocalsym = i;
2281       dsym->iextdefsym = i;
2282       for (; i < bfd_get_symcount (abfd); ++i)
2283         {
2284           bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
2285           if ((s->n_type & BFD_MACH_O_N_TYPE) == BFD_MACH_O_N_UNDF)
2286             break;
2287         }
2288       dsym->nextdefsym = i - dsym->nlocalsym;
2289       dsym->iundefsym = dsym->nextdefsym + dsym->iextdefsym;
2290       dsym->nundefsym = bfd_get_symcount (abfd) 
2291                         - dsym->nlocalsym 
2292                         - dsym->nextdefsym;
2293     }
2294   else
2295     {
2296       dsym->nlocalsym = 0;
2297       dsym->iextdefsym = 0;
2298       dsym->nextdefsym = 0;
2299       dsym->iundefsym = 0;
2300       dsym->nundefsym = 0;
2301     }
2302
2303   dsym->nindirectsyms = bfd_mach_o_count_indirect_symbols (abfd, mdata);
2304   if (dsym->nindirectsyms > 0)
2305     {
2306       unsigned i;
2307       unsigned n;
2308
2309       mdata->filelen = FILE_ALIGN (mdata->filelen, 2);
2310       dsym->indirectsymoff = mdata->filelen;
2311       mdata->filelen += dsym->nindirectsyms * 4;
2312       
2313       dsym->indirect_syms = bfd_zalloc (abfd, dsym->nindirectsyms * 4);
2314       if (dsym->indirect_syms == NULL)
2315         return FALSE;
2316                   
2317       n = 0;
2318       for (i = 0; i < mdata->nsects; ++i)
2319         {
2320           bfd_mach_o_section *sec = mdata->sections[i];
2321
2322           switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
2323             {
2324               case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
2325               case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
2326               case BFD_MACH_O_S_SYMBOL_STUBS:
2327                 {
2328                   unsigned j, num;
2329                   bfd_mach_o_asymbol **isyms = sec->indirect_syms;
2330                   
2331                   num = bfd_mach_o_section_get_nbr_indirect (abfd, sec);
2332                   if (isyms == NULL || num == 0)
2333                     break;
2334                   /* Record the starting index in the reserved1 field.  */
2335                   sec->reserved1 = n;
2336                   for (j = 0; j < num; j++, n++)
2337                     {
2338                       if (isyms[j] == NULL)
2339                         dsym->indirect_syms[n] = BFD_MACH_O_INDIRECT_SYM_LOCAL;
2340                       else if (isyms[j]->symbol.section == bfd_abs_section_ptr
2341                                && ! (isyms[j]->n_type & BFD_MACH_O_N_EXT))
2342                         dsym->indirect_syms[n] = BFD_MACH_O_INDIRECT_SYM_LOCAL
2343                                                  | BFD_MACH_O_INDIRECT_SYM_ABS;
2344                       else
2345                         dsym->indirect_syms[n] = isyms[j]->symbol.udata.i;
2346                     }
2347                 }
2348                 break;
2349               default:
2350                 break;
2351             }
2352         }
2353     }
2354
2355   return TRUE;
2356 }
2357
2358 /* Build Mach-O load commands (currently assuming an MH_OBJECT file).
2359    TODO: Other file formats, rebuilding symtab/dysymtab commands for strip
2360    and copy functionality.  */
2361
2362 bfd_boolean
2363 bfd_mach_o_build_commands (bfd *abfd)
2364 {
2365   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
2366   unsigned wide = mach_o_wide_p (&mdata->header);
2367   int segcmd_idx = -1;
2368   int symtab_idx = -1;
2369   int dysymtab_idx = -1;
2370   unsigned long base_offset = 0;
2371
2372   /* Return now if commands are already present.  */
2373   if (mdata->header.ncmds)
2374     return FALSE;
2375
2376   /* Fill in the file type, if not already set.  */
2377
2378   if (mdata->header.filetype == 0)
2379     {
2380       if (abfd->flags & EXEC_P)
2381         mdata->header.filetype = BFD_MACH_O_MH_EXECUTE;
2382       else if (abfd->flags & DYNAMIC)
2383         mdata->header.filetype = BFD_MACH_O_MH_DYLIB;
2384       else
2385         mdata->header.filetype = BFD_MACH_O_MH_OBJECT;
2386     }
2387
2388   /* If hasn't already been done, flatten sections list, and sort
2389      if/when required.  Must be done before the symbol table is adjusted,
2390      since that depends on properly numbered sections.  */
2391   if (mdata->nsects == 0 || mdata->sections == NULL)
2392     if (! bfd_mach_o_mangle_sections (abfd, mdata))
2393       return FALSE;
2394
2395   /* Order the symbol table, fill-in/check mach-o specific fields and
2396      partition out any indirect symbols.  */
2397   if (!bfd_mach_o_mangle_symbols (abfd))
2398     return FALSE;
2399
2400   /* Very simple command set (only really applicable to MH_OBJECTs):
2401      All the commands are optional - present only when there is suitable data.
2402      (i.e. it is valid to have an empty file)
2403
2404         a command (segment) to contain all the sections,
2405         command for the symbol table,
2406         a command for the dysymtab.  
2407
2408      ??? maybe we should assert that this is an MH_OBJECT?  */
2409
2410   if (mdata->nsects > 0)
2411     {
2412       segcmd_idx = 0;
2413       mdata->header.ncmds = 1;
2414     }
2415
2416   if (bfd_get_symcount (abfd) > 0)
2417     {
2418       mdata->header.ncmds++;
2419       symtab_idx = segcmd_idx + 1; /* 0 if the seg command is absent.  */
2420     }
2421
2422   /* FIXME:
2423      This is a rather crude test for whether we should build a dysymtab.  */
2424   if (bfd_mach_o_should_emit_dysymtab ()
2425       && bfd_get_symcount (abfd))
2426     {
2427       mdata->header.ncmds++;
2428       /* If there should be a case where a dysymtab could be emitted without
2429          a symtab (seems improbable), this would need amending.  */
2430       dysymtab_idx = symtab_idx + 1;
2431     }
2432
2433   if (wide)
2434     base_offset = BFD_MACH_O_HEADER_64_SIZE;
2435   else
2436     base_offset = BFD_MACH_O_HEADER_SIZE;
2437
2438   /* Well, we must have a header, at least.  */
2439   mdata->filelen = base_offset;
2440
2441   /* A bit unusual, but no content is valid;
2442      as -n empty.s -o empty.o  */
2443   if (mdata->header.ncmds == 0)
2444     return TRUE;
2445
2446   mdata->commands = bfd_zalloc (abfd, mdata->header.ncmds
2447                                 * sizeof (bfd_mach_o_load_command));
2448   if (mdata->commands == NULL)
2449     return FALSE;
2450
2451   if (segcmd_idx >= 0)
2452     {  
2453       bfd_mach_o_load_command *cmd = &mdata->commands[segcmd_idx];
2454       bfd_mach_o_segment_command *seg = &cmd->command.segment;
2455
2456       /* Count the segctions in the special blank segment used for MH_OBJECT.  */
2457       seg->nsects = bfd_mach_o_count_sections_for_seg (NULL, mdata);
2458       if (seg->nsects == (unsigned long) -1)
2459         return FALSE;
2460
2461       /* Init segment command.  */
2462       cmd->offset = base_offset;
2463       if (wide)
2464         {
2465           cmd->type = BFD_MACH_O_LC_SEGMENT_64;
2466           cmd->len = BFD_MACH_O_LC_SEGMENT_64_SIZE
2467                         + BFD_MACH_O_SECTION_64_SIZE * seg->nsects;
2468         }
2469       else
2470         {
2471           cmd->type = BFD_MACH_O_LC_SEGMENT;
2472           cmd->len = BFD_MACH_O_LC_SEGMENT_SIZE
2473                         + BFD_MACH_O_SECTION_SIZE * seg->nsects;
2474         }
2475
2476       cmd->type_required = FALSE;
2477       mdata->header.sizeofcmds = cmd->len;
2478       mdata->filelen += cmd->len;
2479     }
2480
2481   if (symtab_idx >= 0)
2482     {
2483       /* Init symtab command.  */
2484       bfd_mach_o_load_command *cmd = &mdata->commands[symtab_idx];
2485   
2486       cmd->type = BFD_MACH_O_LC_SYMTAB;
2487       cmd->offset = base_offset;
2488       if (segcmd_idx >= 0)
2489         cmd->offset += mdata->commands[segcmd_idx].len;
2490
2491       cmd->len = sizeof (struct mach_o_symtab_command_external)
2492                  + BFD_MACH_O_LC_SIZE;
2493       cmd->type_required = FALSE;
2494       mdata->header.sizeofcmds += cmd->len;
2495       mdata->filelen += cmd->len;
2496     }
2497
2498   /* If required, setup symtab command, see comment above about the quality
2499      of this test.  */
2500   if (dysymtab_idx >= 0)
2501     {
2502       bfd_mach_o_load_command *cmd = &mdata->commands[dysymtab_idx];
2503
2504       cmd->type = BFD_MACH_O_LC_DYSYMTAB;
2505       if (symtab_idx >= 0)
2506         cmd->offset = mdata->commands[symtab_idx].offset 
2507                     + mdata->commands[symtab_idx].len;
2508       else if (segcmd_idx >= 0)
2509         cmd->offset = mdata->commands[segcmd_idx].offset 
2510                     + mdata->commands[segcmd_idx].len;
2511       else
2512         cmd->offset = base_offset;
2513
2514       cmd->type_required = FALSE;
2515       cmd->len = sizeof (struct mach_o_dysymtab_command_external)
2516                  + BFD_MACH_O_LC_SIZE;
2517
2518       mdata->header.sizeofcmds += cmd->len;
2519       mdata->filelen += cmd->len;
2520     }
2521
2522   /* So, now we have sized the commands and the filelen set to that.
2523      Now we can build the segment command and set the section file offsets.  */
2524   if (segcmd_idx >= 0
2525       && ! bfd_mach_o_build_seg_command 
2526                 (NULL, mdata, &mdata->commands[segcmd_idx].command.segment))
2527     return FALSE;
2528
2529   /* If we're doing a dysymtab, cmd points to its load command.  */
2530   if (dysymtab_idx >= 0
2531       && ! bfd_mach_o_build_dysymtab_command (abfd, mdata, 
2532                                               &mdata->commands[dysymtab_idx]))
2533     return FALSE;
2534
2535   /* The symtab command is filled in when the symtab is written.  */
2536   return TRUE;
2537 }
2538
2539 /* Set the contents of a section.  */
2540
2541 bfd_boolean
2542 bfd_mach_o_set_section_contents (bfd *abfd,
2543                                  asection *section,
2544                                  const void * location,
2545                                  file_ptr offset,
2546                                  bfd_size_type count)
2547 {
2548   file_ptr pos;
2549
2550   /* Trying to write the first section contents will trigger the creation of
2551      the load commands if they are not already present.  */
2552   if (! abfd->output_has_begun && ! bfd_mach_o_build_commands (abfd))
2553     return FALSE;
2554
2555   if (count == 0)
2556     return TRUE;
2557
2558   pos = section->filepos + offset;
2559   if (bfd_seek (abfd, pos, SEEK_SET) != 0
2560       || bfd_bwrite (location, count, abfd) != count)
2561     return FALSE;
2562
2563   return TRUE;
2564 }
2565
2566 int
2567 bfd_mach_o_sizeof_headers (bfd *a ATTRIBUTE_UNUSED,
2568                            struct bfd_link_info *info ATTRIBUTE_UNUSED)
2569 {
2570   return 0;
2571 }
2572
2573 /* Make an empty symbol.  This is required only because
2574    bfd_make_section_anyway wants to create a symbol for the section.  */
2575
2576 asymbol *
2577 bfd_mach_o_make_empty_symbol (bfd *abfd)
2578 {
2579   asymbol *new_symbol;
2580
2581   new_symbol = bfd_zalloc (abfd, sizeof (bfd_mach_o_asymbol));
2582   if (new_symbol == NULL)
2583     return new_symbol;
2584   new_symbol->the_bfd = abfd;
2585   new_symbol->udata.i = SYM_MACHO_FIELDS_UNSET;
2586   return new_symbol;
2587 }
2588
2589 static bfd_boolean
2590 bfd_mach_o_read_header (bfd *abfd, bfd_mach_o_header *header)
2591 {
2592   struct mach_o_header_external raw;
2593   unsigned int size;
2594   bfd_vma (*get32) (const void *) = NULL;
2595
2596   /* Just read the magic number.  */
2597   if (bfd_seek (abfd, 0, SEEK_SET) != 0
2598       || bfd_bread (raw.magic, sizeof (raw.magic), abfd) != 4)
2599     return FALSE;
2600
2601   if (bfd_getb32 (raw.magic) == BFD_MACH_O_MH_MAGIC)
2602     {
2603       header->byteorder = BFD_ENDIAN_BIG;
2604       header->magic = BFD_MACH_O_MH_MAGIC;
2605       header->version = 1;
2606       get32 = bfd_getb32;
2607     }
2608   else if (bfd_getl32 (raw.magic) == BFD_MACH_O_MH_MAGIC)
2609     {
2610       header->byteorder = BFD_ENDIAN_LITTLE;
2611       header->magic = BFD_MACH_O_MH_MAGIC;
2612       header->version = 1;
2613       get32 = bfd_getl32;
2614     }
2615   else if (bfd_getb32 (raw.magic) == BFD_MACH_O_MH_MAGIC_64)
2616     {
2617       header->byteorder = BFD_ENDIAN_BIG;
2618       header->magic = BFD_MACH_O_MH_MAGIC_64;
2619       header->version = 2;
2620       get32 = bfd_getb32;
2621     }
2622   else if (bfd_getl32 (raw.magic) == BFD_MACH_O_MH_MAGIC_64)
2623     {
2624       header->byteorder = BFD_ENDIAN_LITTLE;
2625       header->magic = BFD_MACH_O_MH_MAGIC_64;
2626       header->version = 2;
2627       get32 = bfd_getl32;
2628     }
2629   else
2630     {
2631       header->byteorder = BFD_ENDIAN_UNKNOWN;
2632       return FALSE;
2633     }
2634
2635   /* Once the size of the header is known, read the full header.  */
2636   size = mach_o_wide_p (header) ?
2637     BFD_MACH_O_HEADER_64_SIZE : BFD_MACH_O_HEADER_SIZE;
2638
2639   if (bfd_seek (abfd, 0, SEEK_SET) != 0
2640       || bfd_bread (&raw, size, abfd) != size)
2641     return FALSE;
2642
2643   header->cputype = (*get32) (raw.cputype);
2644   header->cpusubtype = (*get32) (raw.cpusubtype);
2645   header->filetype = (*get32) (raw.filetype);
2646   header->ncmds = (*get32) (raw.ncmds);
2647   header->sizeofcmds = (*get32) (raw.sizeofcmds);
2648   header->flags = (*get32) (raw.flags);
2649
2650   if (mach_o_wide_p (header))
2651     header->reserved = (*get32) (raw.reserved);
2652   else
2653     header->reserved = 0;
2654
2655   return TRUE;
2656 }
2657
2658 bfd_boolean
2659 bfd_mach_o_new_section_hook (bfd *abfd, asection *sec)
2660 {
2661   bfd_mach_o_section *s;
2662   unsigned bfdalign = bfd_get_section_alignment (abfd, sec);
2663
2664   s = bfd_mach_o_get_mach_o_section (sec);
2665   if (s == NULL)
2666     {
2667       flagword bfd_flags;
2668       static const mach_o_section_name_xlat * xlat;
2669
2670       s = (bfd_mach_o_section *) bfd_zalloc (abfd, sizeof (*s));
2671       if (s == NULL)
2672         return FALSE;
2673       sec->used_by_bfd = s;
2674       s->bfdsection = sec;
2675
2676       /* Create the Darwin seg/sect name pair from the bfd name.
2677          If this is a canonical name for which a specific paiting exists
2678          there will also be defined flags, type, attribute and alignment
2679          values.  */
2680       xlat = bfd_mach_o_convert_section_name_to_mach_o (abfd, sec, s);
2681       if (xlat != NULL)
2682         {
2683           s->flags = xlat->macho_sectype | xlat->macho_secattr;
2684           s->align = xlat->sectalign > bfdalign ? xlat->sectalign 
2685                                                 : bfdalign;
2686           bfd_set_section_alignment (abfd, sec, s->align);
2687           bfd_flags = bfd_get_section_flags (abfd, sec);
2688           if (bfd_flags == SEC_NO_FLAGS)
2689             bfd_set_section_flags (abfd, sec, xlat->bfd_flags);
2690         }
2691       else
2692         /* Create default flags.  */
2693         bfd_mach_o_set_section_flags_from_bfd (abfd, sec);
2694     }
2695
2696   return _bfd_generic_new_section_hook (abfd, sec);
2697 }
2698
2699 static void
2700 bfd_mach_o_init_section_from_mach_o (bfd *abfd, asection *sec,
2701                                      unsigned long prot)
2702 {
2703   flagword flags;
2704   bfd_mach_o_section *section;
2705
2706   flags = bfd_get_section_flags (abfd, sec);
2707   section = bfd_mach_o_get_mach_o_section (sec);
2708
2709   /* TODO: see if we should use the xlat system for doing this by
2710      preference and fall back to this for unknown sections.  */
2711
2712   if (flags == SEC_NO_FLAGS)
2713     {
2714       /* Try to guess flags.  */
2715       if (section->flags & BFD_MACH_O_S_ATTR_DEBUG)
2716         flags = SEC_DEBUGGING;
2717       else
2718         {
2719           flags = SEC_ALLOC;
2720           if ((section->flags & BFD_MACH_O_SECTION_TYPE_MASK)
2721               != BFD_MACH_O_S_ZEROFILL)
2722             {
2723               flags |= SEC_LOAD;
2724               if (prot & BFD_MACH_O_PROT_EXECUTE)
2725                 flags |= SEC_CODE;
2726               if (prot & BFD_MACH_O_PROT_WRITE)
2727                 flags |= SEC_DATA;
2728               else if (prot & BFD_MACH_O_PROT_READ)
2729                 flags |= SEC_READONLY;
2730             }
2731         }
2732     }
2733   else
2734     {
2735       if ((flags & SEC_DEBUGGING) == 0)
2736         flags |= SEC_ALLOC;
2737     }
2738
2739   if (section->offset != 0)
2740     flags |= SEC_HAS_CONTENTS;
2741   if (section->nreloc != 0)
2742     flags |= SEC_RELOC;
2743
2744   bfd_set_section_flags (abfd, sec, flags);
2745
2746   sec->vma = section->addr;
2747   sec->lma = section->addr;
2748   sec->size = section->size;
2749   sec->filepos = section->offset;
2750   sec->alignment_power = section->align;
2751   sec->segment_mark = 0;
2752   sec->reloc_count = section->nreloc;
2753   sec->rel_filepos = section->reloff;
2754 }
2755
2756 static asection *
2757 bfd_mach_o_make_bfd_section (bfd *abfd,
2758                              const unsigned char *segname,
2759                              const unsigned char *sectname)
2760 {
2761   const char *sname;
2762   flagword flags;
2763
2764   bfd_mach_o_convert_section_name_to_bfd
2765     (abfd, (const char *)segname, (const char *)sectname, &sname, &flags);
2766   if (sname == NULL)
2767     return NULL;
2768
2769   return bfd_make_section_anyway_with_flags (abfd, sname, flags);
2770 }
2771
2772 static asection *
2773 bfd_mach_o_read_section_32 (bfd *abfd,
2774                             unsigned int offset,
2775                             unsigned long prot)
2776 {
2777   struct mach_o_section_32_external raw;
2778   asection *sec;
2779   bfd_mach_o_section *section;
2780
2781   if (bfd_seek (abfd, offset, SEEK_SET) != 0
2782       || (bfd_bread (&raw, BFD_MACH_O_SECTION_SIZE, abfd)
2783           != BFD_MACH_O_SECTION_SIZE))
2784     return NULL;
2785
2786   sec = bfd_mach_o_make_bfd_section (abfd, raw.segname, raw.sectname);
2787   if (sec == NULL)
2788     return NULL;
2789
2790   section = bfd_mach_o_get_mach_o_section (sec);
2791   memcpy (section->segname, raw.segname, sizeof (raw.segname));
2792   section->segname[BFD_MACH_O_SEGNAME_SIZE] = 0;
2793   memcpy (section->sectname, raw.sectname, sizeof (raw.sectname));
2794   section->sectname[BFD_MACH_O_SECTNAME_SIZE] = 0;
2795   section->addr = bfd_h_get_32 (abfd, raw.addr);
2796   section->size = bfd_h_get_32 (abfd, raw.size);
2797   section->offset = bfd_h_get_32 (abfd, raw.offset);
2798   section->align = bfd_h_get_32 (abfd, raw.align);
2799   section->reloff = bfd_h_get_32 (abfd, raw.reloff);
2800   section->nreloc = bfd_h_get_32 (abfd, raw.nreloc);
2801   section->flags = bfd_h_get_32 (abfd, raw.flags);
2802   section->reserved1 = bfd_h_get_32 (abfd, raw.reserved1);
2803   section->reserved2 = bfd_h_get_32 (abfd, raw.reserved2);
2804   section->reserved3 = 0;
2805
2806   bfd_mach_o_init_section_from_mach_o (abfd, sec, prot);
2807
2808   return sec;
2809 }
2810
2811 static asection *
2812 bfd_mach_o_read_section_64 (bfd *abfd,
2813                             unsigned int offset,
2814                             unsigned long prot)
2815 {
2816   struct mach_o_section_64_external raw;
2817   asection *sec;
2818   bfd_mach_o_section *section;
2819
2820   if (bfd_seek (abfd, offset, SEEK_SET) != 0
2821       || (bfd_bread (&raw, BFD_MACH_O_SECTION_64_SIZE, abfd)
2822           != BFD_MACH_O_SECTION_64_SIZE))
2823     return NULL;
2824
2825   sec = bfd_mach_o_make_bfd_section (abfd, raw.segname, raw.sectname);
2826   if (sec == NULL)
2827     return NULL;
2828
2829   section = bfd_mach_o_get_mach_o_section (sec);
2830   memcpy (section->segname, raw.segname, sizeof (raw.segname));
2831   section->segname[BFD_MACH_O_SEGNAME_SIZE] = 0;
2832   memcpy (section->sectname, raw.sectname, sizeof (raw.sectname));
2833   section->sectname[BFD_MACH_O_SECTNAME_SIZE] = 0;
2834   section->addr = bfd_h_get_64 (abfd, raw.addr);
2835   section->size = bfd_h_get_64 (abfd, raw.size);
2836   section->offset = bfd_h_get_32 (abfd, raw.offset);
2837   section->align = bfd_h_get_32 (abfd, raw.align);
2838   section->reloff = bfd_h_get_32 (abfd, raw.reloff);
2839   section->nreloc = bfd_h_get_32 (abfd, raw.nreloc);
2840   section->flags = bfd_h_get_32 (abfd, raw.flags);
2841   section->reserved1 = bfd_h_get_32 (abfd, raw.reserved1);
2842   section->reserved2 = bfd_h_get_32 (abfd, raw.reserved2);
2843   section->reserved3 = bfd_h_get_32 (abfd, raw.reserved3);
2844
2845   bfd_mach_o_init_section_from_mach_o (abfd, sec, prot);
2846
2847   return sec;
2848 }
2849
2850 static asection *
2851 bfd_mach_o_read_section (bfd *abfd,
2852                          unsigned int offset,
2853                          unsigned long prot,
2854                          unsigned int wide)
2855 {
2856   if (wide)
2857     return bfd_mach_o_read_section_64 (abfd, offset, prot);
2858   else
2859     return bfd_mach_o_read_section_32 (abfd, offset, prot);
2860 }
2861
2862 static bfd_boolean
2863 bfd_mach_o_read_symtab_symbol (bfd *abfd,
2864                                bfd_mach_o_symtab_command *sym,
2865                                bfd_mach_o_asymbol *s,
2866                                unsigned long i)
2867 {
2868   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
2869   unsigned int wide = mach_o_wide_p (&mdata->header);
2870   unsigned int symwidth =
2871     wide ? BFD_MACH_O_NLIST_64_SIZE : BFD_MACH_O_NLIST_SIZE;
2872   unsigned int symoff = sym->symoff + (i * symwidth);
2873   struct mach_o_nlist_64_external raw;
2874   unsigned char type = -1;
2875   unsigned char section = -1;
2876   short desc = -1;
2877   symvalue value = -1;
2878   unsigned long stroff = -1;
2879   unsigned int symtype = -1;
2880
2881   BFD_ASSERT (sym->strtab != NULL);
2882
2883   if (bfd_seek (abfd, symoff, SEEK_SET) != 0
2884       || bfd_bread (&raw, symwidth, abfd) != symwidth)
2885     {
2886       (*_bfd_error_handler)
2887         (_("bfd_mach_o_read_symtab_symbol: unable to read %d bytes at %lu"),
2888          symwidth, (unsigned long) symoff);
2889       return FALSE;
2890     }
2891
2892   stroff = bfd_h_get_32 (abfd, raw.n_strx);
2893   type = bfd_h_get_8 (abfd, raw.n_type);
2894   symtype = type & BFD_MACH_O_N_TYPE;
2895   section = bfd_h_get_8 (abfd, raw.n_sect);
2896   desc = bfd_h_get_16 (abfd, raw.n_desc);
2897   if (wide)
2898     value = bfd_h_get_64 (abfd, raw.n_value);
2899   else
2900     value = bfd_h_get_32 (abfd, raw.n_value);
2901
2902   if (stroff >= sym->strsize)
2903     {
2904       (*_bfd_error_handler)
2905         (_("bfd_mach_o_read_symtab_symbol: name out of range (%lu >= %lu)"),
2906          (unsigned long) stroff,
2907          (unsigned long) sym->strsize);
2908       return FALSE;
2909     }
2910
2911   s->symbol.the_bfd = abfd;
2912   s->symbol.name = sym->strtab + stroff;
2913   s->symbol.value = value;
2914   s->symbol.flags = 0x0;
2915   s->symbol.udata.i = i;
2916   s->n_type = type;
2917   s->n_sect = section;
2918   s->n_desc = desc;
2919
2920   if (type & BFD_MACH_O_N_STAB)
2921     {
2922       s->symbol.flags |= BSF_DEBUGGING;
2923       s->symbol.section = bfd_und_section_ptr;
2924       switch (type)
2925         {
2926         case N_FUN:
2927         case N_STSYM:
2928         case N_LCSYM:
2929         case N_BNSYM:
2930         case N_SLINE:
2931         case N_ENSYM:
2932         case N_ECOMM:
2933         case N_ECOML:
2934         case N_GSYM:
2935           if ((section > 0) && (section <= mdata->nsects))
2936             {
2937               s->symbol.section = mdata->sections[section - 1]->bfdsection;
2938               s->symbol.value =
2939                 s->symbol.value - mdata->sections[section - 1]->addr;
2940             }
2941           break;
2942         }
2943     }
2944   else
2945     {
2946       if (type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT))
2947         s->symbol.flags |= BSF_GLOBAL;
2948       else
2949         s->symbol.flags |= BSF_LOCAL;
2950
2951       switch (symtype)
2952         {
2953         case BFD_MACH_O_N_UNDF:
2954           if (type == (BFD_MACH_O_N_UNDF | BFD_MACH_O_N_EXT)
2955               && s->symbol.value != 0)
2956             {
2957               /* A common symbol.  */
2958               s->symbol.section = bfd_com_section_ptr;
2959               s->symbol.flags = BSF_NO_FLAGS;
2960             }
2961           else
2962             {
2963               s->symbol.section = bfd_und_section_ptr;
2964               if (s->n_desc & BFD_MACH_O_N_WEAK_REF)
2965                 s->symbol.flags |= BSF_WEAK;
2966             }
2967           break;
2968         case BFD_MACH_O_N_PBUD:
2969           s->symbol.section = bfd_und_section_ptr;
2970           break;
2971         case BFD_MACH_O_N_ABS:
2972           s->symbol.section = bfd_abs_section_ptr;
2973           break;
2974         case BFD_MACH_O_N_SECT:
2975           if ((section > 0) && (section <= mdata->nsects))
2976             {
2977               s->symbol.section = mdata->sections[section - 1]->bfdsection;
2978               s->symbol.value =
2979                 s->symbol.value - mdata->sections[section - 1]->addr;
2980             }
2981           else
2982             {
2983               /* Mach-O uses 0 to mean "no section"; not an error.  */
2984               if (section != 0)
2985                 {
2986                   (*_bfd_error_handler) (_("bfd_mach_o_read_symtab_symbol: "
2987                                            "symbol \"%s\" specified invalid section %d (max %lu): setting to undefined"),
2988                                          s->symbol.name, section, mdata->nsects);
2989                 }
2990               s->symbol.section = bfd_und_section_ptr;
2991             }
2992           break;
2993         case BFD_MACH_O_N_INDR:
2994           /* FIXME: we don't follow the BFD convention as this indirect symbol
2995              won't be followed by the referenced one.  This looks harmless
2996              unless we start using the linker.  */
2997           s->symbol.flags |= BSF_INDIRECT;
2998           s->symbol.section = bfd_ind_section_ptr;
2999           s->symbol.value = 0;
3000           break;
3001         default:
3002           (*_bfd_error_handler) (_("bfd_mach_o_read_symtab_symbol: "
3003                                    "symbol \"%s\" specified invalid type field 0x%x: setting to undefined"),
3004                                  s->symbol.name, symtype);
3005           s->symbol.section = bfd_und_section_ptr;
3006           break;
3007         }
3008     }
3009
3010   return TRUE;
3011 }
3012
3013 bfd_boolean
3014 bfd_mach_o_read_symtab_strtab (bfd *abfd)
3015 {
3016   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3017   bfd_mach_o_symtab_command *sym = mdata->symtab;
3018
3019   /* Fail if there is no symtab.  */
3020   if (sym == NULL)
3021     return FALSE;
3022
3023   /* Success if already loaded.  */
3024   if (sym->strtab)
3025     return TRUE;
3026
3027   if (abfd->flags & BFD_IN_MEMORY)
3028     {
3029       struct bfd_in_memory *b;
3030
3031       b = (struct bfd_in_memory *) abfd->iostream;
3032
3033       if ((sym->stroff + sym->strsize) > b->size)
3034         {
3035           bfd_set_error (bfd_error_file_truncated);
3036           return FALSE;
3037         }
3038       sym->strtab = (char *) b->buffer + sym->stroff;
3039     }
3040   else
3041     {
3042       sym->strtab = bfd_alloc (abfd, sym->strsize);
3043       if (sym->strtab == NULL)
3044         return FALSE;
3045
3046       if (bfd_seek (abfd, sym->stroff, SEEK_SET) != 0
3047           || bfd_bread (sym->strtab, sym->strsize, abfd) != sym->strsize)
3048         {
3049           bfd_set_error (bfd_error_file_truncated);
3050           return FALSE;
3051         }
3052     }
3053
3054   return TRUE;
3055 }
3056
3057 bfd_boolean
3058 bfd_mach_o_read_symtab_symbols (bfd *abfd)
3059 {
3060   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3061   bfd_mach_o_symtab_command *sym = mdata->symtab;
3062   unsigned long i;
3063
3064   if (sym == NULL || sym->symbols)
3065     {
3066       /* Return now if there are no symbols or if already loaded.  */
3067       return TRUE;
3068     }
3069
3070   sym->symbols = bfd_alloc (abfd, sym->nsyms * sizeof (bfd_mach_o_asymbol));
3071
3072   if (sym->symbols == NULL)
3073     {
3074       (*_bfd_error_handler) (_("bfd_mach_o_read_symtab_symbols: unable to allocate memory for symbols"));
3075       return FALSE;
3076     }
3077
3078   if (!bfd_mach_o_read_symtab_strtab (abfd))
3079     return FALSE;
3080
3081   for (i = 0; i < sym->nsyms; i++)
3082     {
3083       if (!bfd_mach_o_read_symtab_symbol (abfd, sym, &sym->symbols[i], i))
3084         return FALSE;
3085     }
3086
3087   return TRUE;
3088 }
3089
3090 static const char *
3091 bfd_mach_o_i386_flavour_string (unsigned int flavour)
3092 {
3093   switch ((int) flavour)
3094     {
3095     case BFD_MACH_O_x86_THREAD_STATE32:    return "x86_THREAD_STATE32";
3096     case BFD_MACH_O_x86_FLOAT_STATE32:     return "x86_FLOAT_STATE32";
3097     case BFD_MACH_O_x86_EXCEPTION_STATE32: return "x86_EXCEPTION_STATE32";
3098     case BFD_MACH_O_x86_THREAD_STATE64:    return "x86_THREAD_STATE64";
3099     case BFD_MACH_O_x86_FLOAT_STATE64:     return "x86_FLOAT_STATE64";
3100     case BFD_MACH_O_x86_EXCEPTION_STATE64: return "x86_EXCEPTION_STATE64";
3101     case BFD_MACH_O_x86_THREAD_STATE:      return "x86_THREAD_STATE";
3102     case BFD_MACH_O_x86_FLOAT_STATE:       return "x86_FLOAT_STATE";
3103     case BFD_MACH_O_x86_EXCEPTION_STATE:   return "x86_EXCEPTION_STATE";
3104     case BFD_MACH_O_x86_DEBUG_STATE32:     return "x86_DEBUG_STATE32";
3105     case BFD_MACH_O_x86_DEBUG_STATE64:     return "x86_DEBUG_STATE64";
3106     case BFD_MACH_O_x86_DEBUG_STATE:       return "x86_DEBUG_STATE";
3107     case BFD_MACH_O_x86_THREAD_STATE_NONE: return "x86_THREAD_STATE_NONE";
3108     default: return "UNKNOWN";
3109     }
3110 }
3111
3112 static const char *
3113 bfd_mach_o_ppc_flavour_string (unsigned int flavour)
3114 {
3115   switch ((int) flavour)
3116     {
3117     case BFD_MACH_O_PPC_THREAD_STATE:      return "PPC_THREAD_STATE";
3118     case BFD_MACH_O_PPC_FLOAT_STATE:       return "PPC_FLOAT_STATE";
3119     case BFD_MACH_O_PPC_EXCEPTION_STATE:   return "PPC_EXCEPTION_STATE";
3120     case BFD_MACH_O_PPC_VECTOR_STATE:      return "PPC_VECTOR_STATE";
3121     case BFD_MACH_O_PPC_THREAD_STATE64:    return "PPC_THREAD_STATE64";
3122     case BFD_MACH_O_PPC_EXCEPTION_STATE64: return "PPC_EXCEPTION_STATE64";
3123     default: return "UNKNOWN";
3124     }
3125 }
3126
3127 static int
3128 bfd_mach_o_read_dylinker (bfd *abfd, bfd_mach_o_load_command *command)
3129 {
3130   bfd_mach_o_dylinker_command *cmd = &command->command.dylinker;
3131   struct mach_o_str_command_external raw;
3132   unsigned int nameoff;
3133
3134   BFD_ASSERT ((command->type == BFD_MACH_O_LC_ID_DYLINKER)
3135               || (command->type == BFD_MACH_O_LC_LOAD_DYLINKER));
3136
3137   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3138       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3139     return -1;
3140
3141   nameoff = bfd_h_get_32 (abfd, raw.str);
3142
3143   cmd->name_offset = command->offset + nameoff;
3144   cmd->name_len = command->len - nameoff;
3145   cmd->name_str = bfd_alloc (abfd, cmd->name_len);
3146   if (cmd->name_str == NULL)
3147     return -1;
3148   if (bfd_seek (abfd, cmd->name_offset, SEEK_SET) != 0
3149       || bfd_bread (cmd->name_str, cmd->name_len, abfd) != cmd->name_len)
3150     return -1;
3151   return 0;
3152 }
3153
3154 static int
3155 bfd_mach_o_read_dylib (bfd *abfd, bfd_mach_o_load_command *command)
3156 {
3157   bfd_mach_o_dylib_command *cmd = &command->command.dylib;
3158   struct mach_o_dylib_command_external raw;
3159   unsigned int nameoff;
3160
3161   switch (command->type)
3162     {
3163     case BFD_MACH_O_LC_LOAD_DYLIB:
3164     case BFD_MACH_O_LC_LOAD_WEAK_DYLIB:
3165     case BFD_MACH_O_LC_ID_DYLIB:
3166     case BFD_MACH_O_LC_REEXPORT_DYLIB:
3167     case BFD_MACH_O_LC_LOAD_UPWARD_DYLIB:
3168       break;
3169     default:
3170       BFD_FAIL ();
3171       return -1;
3172     }
3173
3174   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3175       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3176     return -1;
3177
3178   nameoff = bfd_h_get_32 (abfd, raw.name);
3179   cmd->timestamp = bfd_h_get_32 (abfd, raw.timestamp);
3180   cmd->current_version = bfd_h_get_32 (abfd, raw.current_version);
3181   cmd->compatibility_version = bfd_h_get_32 (abfd, raw.compatibility_version);
3182
3183   cmd->name_offset = command->offset + nameoff;
3184   cmd->name_len = command->len - nameoff;
3185   cmd->name_str = bfd_alloc (abfd, cmd->name_len);
3186   if (cmd->name_str == NULL)
3187     return -1;
3188   if (bfd_seek (abfd, cmd->name_offset, SEEK_SET) != 0
3189       || bfd_bread (cmd->name_str, cmd->name_len, abfd) != cmd->name_len)
3190     return -1;
3191   return 0;
3192 }
3193
3194 static int
3195 bfd_mach_o_read_prebound_dylib (bfd *abfd ATTRIBUTE_UNUSED,
3196                                 bfd_mach_o_load_command *command ATTRIBUTE_UNUSED)
3197 {
3198   /* bfd_mach_o_prebound_dylib_command *cmd = &command->command.prebound_dylib; */
3199
3200   BFD_ASSERT (command->type == BFD_MACH_O_LC_PREBOUND_DYLIB);
3201   return 0;
3202 }
3203
3204 static int
3205 bfd_mach_o_read_fvmlib (bfd *abfd, bfd_mach_o_load_command *command)
3206 {
3207   bfd_mach_o_fvmlib_command *fvm = &command->command.fvmlib;
3208   struct mach_o_fvmlib_command_external raw;
3209   unsigned int nameoff;
3210
3211   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3212       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3213     return -1;
3214
3215   nameoff = bfd_h_get_32 (abfd, raw.name);
3216   fvm->minor_version = bfd_h_get_32 (abfd, raw.minor_version);
3217   fvm->header_addr = bfd_h_get_32 (abfd, raw.header_addr);
3218
3219   fvm->name_offset = command->offset + nameoff;
3220   fvm->name_len = command->len - nameoff;
3221   fvm->name_str = bfd_alloc (abfd, fvm->name_len);
3222   if (fvm->name_str == NULL)
3223     return -1;
3224   if (bfd_seek (abfd, fvm->name_offset, SEEK_SET) != 0
3225       || bfd_bread (fvm->name_str, fvm->name_len, abfd) != fvm->name_len)
3226     return -1;
3227   return 0;
3228 }
3229
3230 static int
3231 bfd_mach_o_read_thread (bfd *abfd, bfd_mach_o_load_command *command)
3232 {
3233   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3234   bfd_mach_o_thread_command *cmd = &command->command.thread;
3235   unsigned int offset;
3236   unsigned int nflavours;
3237   unsigned int i;
3238
3239   BFD_ASSERT ((command->type == BFD_MACH_O_LC_THREAD)
3240               || (command->type == BFD_MACH_O_LC_UNIXTHREAD));
3241
3242   /* Count the number of threads.  */
3243   offset = 8;
3244   nflavours = 0;
3245   while (offset != command->len)
3246     {
3247       struct mach_o_thread_command_external raw;
3248
3249       if (offset >= command->len)
3250         return -1;
3251
3252       if (bfd_seek (abfd, command->offset + offset, SEEK_SET) != 0
3253           || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3254         return -1;
3255
3256       offset += sizeof (raw) + bfd_h_get_32 (abfd, raw.count) * 4;
3257       nflavours++;
3258     }
3259
3260   /* Allocate threads.  */
3261   cmd->flavours = bfd_alloc
3262     (abfd, nflavours * sizeof (bfd_mach_o_thread_flavour));
3263   if (cmd->flavours == NULL)
3264     return -1;
3265   cmd->nflavours = nflavours;
3266
3267   offset = 8;
3268   nflavours = 0;
3269   while (offset != command->len)
3270     {
3271       struct mach_o_thread_command_external raw;
3272
3273       if (offset >= command->len)
3274         return -1;
3275
3276       if (nflavours >= cmd->nflavours)
3277         return -1;
3278
3279       if (bfd_seek (abfd, command->offset + offset, SEEK_SET) != 0
3280           || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3281         return -1;
3282
3283       cmd->flavours[nflavours].flavour = bfd_h_get_32 (abfd, raw.flavour);
3284       cmd->flavours[nflavours].offset = command->offset + offset + sizeof (raw);
3285       cmd->flavours[nflavours].size = bfd_h_get_32 (abfd, raw.count) * 4;
3286       offset += cmd->flavours[nflavours].size + sizeof (raw);
3287       nflavours++;
3288     }
3289
3290   for (i = 0; i < nflavours; i++)
3291     {
3292       asection *bfdsec;
3293       unsigned int snamelen;
3294       char *sname;
3295       const char *flavourstr;
3296       const char *prefix = "LC_THREAD";
3297       unsigned int j = 0;
3298
3299       switch (mdata->header.cputype)
3300         {
3301         case BFD_MACH_O_CPU_TYPE_POWERPC:
3302         case BFD_MACH_O_CPU_TYPE_POWERPC_64:
3303           flavourstr = bfd_mach_o_ppc_flavour_string (cmd->flavours[i].flavour);
3304           break;
3305         case BFD_MACH_O_CPU_TYPE_I386:
3306         case BFD_MACH_O_CPU_TYPE_X86_64:
3307           flavourstr = bfd_mach_o_i386_flavour_string (cmd->flavours[i].flavour);
3308           break;
3309         default:
3310           flavourstr = "UNKNOWN_ARCHITECTURE";
3311           break;
3312         }
3313
3314       snamelen = strlen (prefix) + 1 + 20 + 1 + strlen (flavourstr) + 1;
3315       sname = bfd_alloc (abfd, snamelen);
3316       if (sname == NULL)
3317         return -1;
3318
3319       for (;;)
3320         {
3321           sprintf (sname, "%s.%s.%u", prefix, flavourstr, j);
3322           if (bfd_get_section_by_name (abfd, sname) == NULL)
3323             break;
3324           j++;
3325         }
3326
3327       bfdsec = bfd_make_section_with_flags (abfd, sname, SEC_HAS_CONTENTS);
3328
3329       bfdsec->vma = 0;
3330       bfdsec->lma = 0;
3331       bfdsec->size = cmd->flavours[i].size;
3332       bfdsec->filepos = cmd->flavours[i].offset;
3333       bfdsec->alignment_power = 0x0;
3334
3335       cmd->section = bfdsec;
3336     }
3337
3338   return 0;
3339 }
3340
3341 static int
3342 bfd_mach_o_read_dysymtab (bfd *abfd, bfd_mach_o_load_command *command)
3343 {
3344   bfd_mach_o_dysymtab_command *cmd = &command->command.dysymtab;
3345   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3346
3347   BFD_ASSERT (command->type == BFD_MACH_O_LC_DYSYMTAB);
3348
3349   {
3350     struct mach_o_dysymtab_command_external raw;
3351
3352     if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3353         || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3354       return -1;
3355
3356     cmd->ilocalsym = bfd_h_get_32 (abfd, raw.ilocalsym);
3357     cmd->nlocalsym = bfd_h_get_32 (abfd, raw.nlocalsym);
3358     cmd->iextdefsym = bfd_h_get_32 (abfd, raw.iextdefsym);
3359     cmd->nextdefsym = bfd_h_get_32 (abfd, raw.nextdefsym);
3360     cmd->iundefsym = bfd_h_get_32 (abfd, raw.iundefsym);
3361     cmd->nundefsym = bfd_h_get_32 (abfd, raw.nundefsym);
3362     cmd->tocoff = bfd_h_get_32 (abfd, raw.tocoff);
3363     cmd->ntoc = bfd_h_get_32 (abfd, raw.ntoc);
3364     cmd->modtaboff = bfd_h_get_32 (abfd, raw.modtaboff);
3365     cmd->nmodtab = bfd_h_get_32 (abfd, raw.nmodtab);
3366     cmd->extrefsymoff = bfd_h_get_32 (abfd, raw.extrefsymoff);
3367     cmd->nextrefsyms = bfd_h_get_32 (abfd, raw.nextrefsyms);
3368     cmd->indirectsymoff = bfd_h_get_32 (abfd, raw.indirectsymoff);
3369     cmd->nindirectsyms = bfd_h_get_32 (abfd, raw.nindirectsyms);
3370     cmd->extreloff = bfd_h_get_32 (abfd, raw.extreloff);
3371     cmd->nextrel = bfd_h_get_32 (abfd, raw.nextrel);
3372     cmd->locreloff = bfd_h_get_32 (abfd, raw.locreloff);
3373     cmd->nlocrel = bfd_h_get_32 (abfd, raw.nlocrel);
3374   }
3375
3376   if (cmd->nmodtab != 0)
3377     {
3378       unsigned int i;
3379       int wide = bfd_mach_o_wide_p (abfd);
3380       unsigned int module_len = wide ? 56 : 52;
3381
3382       cmd->dylib_module =
3383         bfd_alloc (abfd, cmd->nmodtab * sizeof (bfd_mach_o_dylib_module));
3384       if (cmd->dylib_module == NULL)
3385         return -1;
3386
3387       if (bfd_seek (abfd, cmd->modtaboff, SEEK_SET) != 0)
3388         return -1;
3389
3390       for (i = 0; i < cmd->nmodtab; i++)
3391         {
3392           bfd_mach_o_dylib_module *module = &cmd->dylib_module[i];
3393           unsigned long v;
3394           unsigned char buf[56];
3395
3396           if (bfd_bread ((void *) buf, module_len, abfd) != module_len)
3397             return -1;
3398
3399           module->module_name_idx = bfd_h_get_32 (abfd, buf + 0);
3400           module->iextdefsym = bfd_h_get_32 (abfd, buf + 4);
3401           module->nextdefsym = bfd_h_get_32 (abfd, buf + 8);
3402           module->irefsym = bfd_h_get_32 (abfd, buf + 12);
3403           module->nrefsym = bfd_h_get_32 (abfd, buf + 16);
3404           module->ilocalsym = bfd_h_get_32 (abfd, buf + 20);
3405           module->nlocalsym = bfd_h_get_32 (abfd, buf + 24);
3406           module->iextrel = bfd_h_get_32 (abfd, buf + 28);
3407           module->nextrel = bfd_h_get_32 (abfd, buf + 32);
3408           v = bfd_h_get_32 (abfd, buf +36);
3409           module->iinit = v & 0xffff;
3410           module->iterm = (v >> 16) & 0xffff;
3411           v = bfd_h_get_32 (abfd, buf + 40);
3412           module->ninit = v & 0xffff;
3413           module->nterm = (v >> 16) & 0xffff;
3414           if (wide)
3415             {
3416               module->objc_module_info_size = bfd_h_get_32 (abfd, buf + 44);
3417               module->objc_module_info_addr = bfd_h_get_64 (abfd, buf + 48);
3418             }
3419           else
3420             {
3421               module->objc_module_info_addr = bfd_h_get_32 (abfd, buf + 44);
3422               module->objc_module_info_size = bfd_h_get_32 (abfd, buf + 48);
3423             }
3424         }
3425     }
3426
3427   if (cmd->ntoc != 0)
3428     {
3429       unsigned int i;
3430
3431       cmd->dylib_toc = bfd_alloc
3432         (abfd, cmd->ntoc * sizeof (bfd_mach_o_dylib_table_of_content));
3433       if (cmd->dylib_toc == NULL)
3434         return -1;
3435
3436       if (bfd_seek (abfd, cmd->tocoff, SEEK_SET) != 0)
3437         return -1;
3438
3439       for (i = 0; i < cmd->ntoc; i++)
3440         {
3441           struct mach_o_dylib_table_of_contents_external raw;
3442           bfd_mach_o_dylib_table_of_content *toc = &cmd->dylib_toc[i];
3443
3444           if (bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3445             return -1;
3446
3447           toc->symbol_index = bfd_h_get_32 (abfd, raw.symbol_index);
3448           toc->module_index = bfd_h_get_32 (abfd, raw.module_index);
3449         }
3450     }
3451
3452   if (cmd->nindirectsyms != 0)
3453     {
3454       unsigned int i;
3455
3456       cmd->indirect_syms = bfd_alloc
3457         (abfd, cmd->nindirectsyms * sizeof (unsigned int));
3458       if (cmd->indirect_syms == NULL)
3459         return -1;
3460
3461       if (bfd_seek (abfd, cmd->indirectsymoff, SEEK_SET) != 0)
3462         return -1;
3463
3464       for (i = 0; i < cmd->nindirectsyms; i++)
3465         {
3466           unsigned char raw[4];
3467           unsigned int *is = &cmd->indirect_syms[i];
3468
3469           if (bfd_bread (raw, sizeof (raw), abfd) != sizeof (raw))
3470             return -1;
3471
3472           *is = bfd_h_get_32 (abfd, raw);
3473         }
3474     }
3475
3476   if (cmd->nextrefsyms != 0)
3477     {
3478       unsigned long v;
3479       unsigned int i;
3480
3481       cmd->ext_refs = bfd_alloc
3482         (abfd, cmd->nextrefsyms * sizeof (bfd_mach_o_dylib_reference));
3483       if (cmd->ext_refs == NULL)
3484         return -1;
3485
3486       if (bfd_seek (abfd, cmd->extrefsymoff, SEEK_SET) != 0)
3487         return -1;
3488
3489       for (i = 0; i < cmd->nextrefsyms; i++)
3490         {
3491           unsigned char raw[4];
3492           bfd_mach_o_dylib_reference *ref = &cmd->ext_refs[i];
3493
3494           if (bfd_bread (raw, sizeof (raw), abfd) != sizeof (raw))
3495             return -1;
3496
3497           /* Fields isym and flags are written as bit-fields, thus we need
3498              a specific processing for endianness.  */
3499           v = bfd_h_get_32 (abfd, raw);
3500           if (bfd_big_endian (abfd))
3501             {
3502               ref->isym = (v >> 8) & 0xffffff;
3503               ref->flags = v & 0xff;
3504             }
3505           else
3506             {
3507               ref->isym = v & 0xffffff;
3508               ref->flags = (v >> 24) & 0xff;
3509             }
3510         }
3511     }
3512
3513   if (mdata->dysymtab)
3514     return -1;
3515   mdata->dysymtab = cmd;
3516
3517   return 0;
3518 }
3519
3520 static int
3521 bfd_mach_o_read_symtab (bfd *abfd, bfd_mach_o_load_command *command)
3522 {
3523   bfd_mach_o_symtab_command *symtab = &command->command.symtab;
3524   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3525   struct mach_o_symtab_command_external raw;
3526
3527   BFD_ASSERT (command->type == BFD_MACH_O_LC_SYMTAB);
3528
3529   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3530       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3531     return -1;
3532
3533   symtab->symoff = bfd_h_get_32 (abfd, raw.symoff);
3534   symtab->nsyms = bfd_h_get_32 (abfd, raw.nsyms);
3535   symtab->stroff = bfd_h_get_32 (abfd, raw.stroff);
3536   symtab->strsize = bfd_h_get_32 (abfd, raw.strsize);
3537   symtab->symbols = NULL;
3538   symtab->strtab = NULL;
3539
3540   if (symtab->nsyms != 0)
3541     abfd->flags |= HAS_SYMS;
3542
3543   if (mdata->symtab)
3544     return -1;
3545   mdata->symtab = symtab;
3546   return 0;
3547 }
3548
3549 static int
3550 bfd_mach_o_read_uuid (bfd *abfd, bfd_mach_o_load_command *command)
3551 {
3552   bfd_mach_o_uuid_command *cmd = &command->command.uuid;
3553
3554   BFD_ASSERT (command->type == BFD_MACH_O_LC_UUID);
3555
3556   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3557       || bfd_bread (cmd->uuid, 16, abfd) != 16)
3558     return -1;
3559
3560   return 0;
3561 }
3562
3563 static int
3564 bfd_mach_o_read_linkedit (bfd *abfd, bfd_mach_o_load_command *command)
3565 {
3566   bfd_mach_o_linkedit_command *cmd = &command->command.linkedit;
3567   struct mach_o_linkedit_data_command_external raw;
3568
3569   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3570       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3571     return -1;
3572
3573   cmd->dataoff = bfd_get_32 (abfd, raw.dataoff);
3574   cmd->datasize = bfd_get_32 (abfd, raw.datasize);
3575   return 0;
3576 }
3577
3578 static int
3579 bfd_mach_o_read_str (bfd *abfd, bfd_mach_o_load_command *command)
3580 {
3581   bfd_mach_o_str_command *cmd = &command->command.str;
3582   struct mach_o_str_command_external raw;
3583   unsigned long off;
3584
3585   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3586       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3587     return -1;
3588
3589   off = bfd_get_32 (abfd, raw.str);
3590   cmd->stroff = command->offset + off;
3591   cmd->str_len = command->len - off;
3592   cmd->str = bfd_alloc (abfd, cmd->str_len);
3593   if (cmd->str == NULL)
3594     return -1;
3595   if (bfd_seek (abfd, cmd->stroff, SEEK_SET) != 0
3596       || bfd_bread ((void *) cmd->str, cmd->str_len, abfd) != cmd->str_len)
3597     return -1;
3598   return 0;
3599 }
3600
3601 static int
3602 bfd_mach_o_read_dyld_info (bfd *abfd, bfd_mach_o_load_command *command)
3603 {
3604   bfd_mach_o_dyld_info_command *cmd = &command->command.dyld_info;
3605   struct mach_o_dyld_info_command_external raw;
3606
3607   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3608       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3609     return -1;
3610
3611   cmd->rebase_off = bfd_get_32 (abfd, raw.rebase_off);
3612   cmd->rebase_size = bfd_get_32 (abfd, raw.rebase_size);
3613   cmd->bind_off = bfd_get_32 (abfd, raw.bind_off);
3614   cmd->bind_size = bfd_get_32 (abfd, raw.bind_size);
3615   cmd->weak_bind_off = bfd_get_32 (abfd, raw.weak_bind_off);
3616   cmd->weak_bind_size = bfd_get_32 (abfd, raw.weak_bind_size);
3617   cmd->lazy_bind_off = bfd_get_32 (abfd, raw.lazy_bind_off);
3618   cmd->lazy_bind_size = bfd_get_32 (abfd, raw.lazy_bind_size);
3619   cmd->export_off = bfd_get_32 (abfd, raw.export_off);
3620   cmd->export_size = bfd_get_32 (abfd, raw.export_size);
3621   return 0;
3622 }
3623
3624 static bfd_boolean
3625 bfd_mach_o_read_version_min (bfd *abfd, bfd_mach_o_load_command *command)
3626 {
3627   bfd_mach_o_version_min_command *cmd = &command->command.version_min;
3628   struct mach_o_version_min_command_external raw;
3629   unsigned int ver;
3630
3631   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3632       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3633     return FALSE;
3634
3635   ver = bfd_get_32 (abfd, raw.version);
3636   cmd->rel = ver >> 16;
3637   cmd->maj = ver >> 8;
3638   cmd->min = ver;
3639   cmd->reserved = bfd_get_32 (abfd, raw.reserved);
3640   return TRUE;
3641 }
3642
3643 static bfd_boolean
3644 bfd_mach_o_read_encryption_info (bfd *abfd, bfd_mach_o_load_command *command)
3645 {
3646   bfd_mach_o_encryption_info_command *cmd = &command->command.encryption_info;
3647   struct mach_o_encryption_info_command_external raw;
3648
3649   if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3650       || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3651     return FALSE;
3652
3653   cmd->cryptoff = bfd_get_32 (abfd, raw.cryptoff);
3654   cmd->cryptsize = bfd_get_32 (abfd, raw.cryptsize);
3655   cmd->cryptid = bfd_get_32 (abfd, raw.cryptid);
3656   return TRUE;
3657 }
3658
3659 static int
3660 bfd_mach_o_read_segment (bfd *abfd,
3661                          bfd_mach_o_load_command *command,
3662                          unsigned int wide)
3663 {
3664   bfd_mach_o_segment_command *seg = &command->command.segment;
3665   unsigned long i;
3666
3667   if (wide)
3668     {
3669       struct mach_o_segment_command_64_external raw;
3670
3671       BFD_ASSERT (command->type == BFD_MACH_O_LC_SEGMENT_64);
3672
3673       if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3674           || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3675         return -1;
3676
3677       memcpy (seg->segname, raw.segname, 16);
3678       seg->segname[16] = '\0';
3679
3680       seg->vmaddr = bfd_h_get_64 (abfd, raw.vmaddr);
3681       seg->vmsize = bfd_h_get_64 (abfd, raw.vmsize);
3682       seg->fileoff = bfd_h_get_64 (abfd, raw.fileoff);
3683       seg->filesize = bfd_h_get_64 (abfd, raw.filesize);
3684       seg->maxprot = bfd_h_get_32 (abfd, raw.maxprot);
3685       seg->initprot = bfd_h_get_32 (abfd, raw.initprot);
3686       seg->nsects = bfd_h_get_32 (abfd, raw.nsects);
3687       seg->flags = bfd_h_get_32 (abfd, raw.flags);
3688     }
3689   else
3690     {
3691       struct mach_o_segment_command_32_external raw;
3692
3693       BFD_ASSERT (command->type == BFD_MACH_O_LC_SEGMENT);
3694
3695       if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
3696           || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
3697         return -1;
3698
3699       memcpy (seg->segname, raw.segname, 16);
3700       seg->segname[16] = '\0';
3701
3702       seg->vmaddr = bfd_h_get_32 (abfd, raw.vmaddr);
3703       seg->vmsize = bfd_h_get_32 (abfd, raw.vmsize);
3704       seg->fileoff = bfd_h_get_32 (abfd, raw.fileoff);
3705       seg->filesize = bfd_h_get_32 (abfd, raw.filesize);
3706       seg->maxprot = bfd_h_get_32 (abfd, raw.maxprot);
3707       seg->initprot = bfd_h_get_32 (abfd, raw.initprot);
3708       seg->nsects = bfd_h_get_32 (abfd, raw.nsects);
3709       seg->flags = bfd_h_get_32 (abfd, raw.flags);
3710     }
3711   seg->sect_head = NULL;
3712   seg->sect_tail = NULL;
3713
3714   for (i = 0; i < seg->nsects; i++)
3715     {
3716       bfd_vma segoff;
3717       asection *sec;
3718
3719       if (wide)
3720         segoff = command->offset + BFD_MACH_O_LC_SEGMENT_64_SIZE
3721           + (i * BFD_MACH_O_SECTION_64_SIZE);
3722       else
3723         segoff = command->offset + BFD_MACH_O_LC_SEGMENT_SIZE
3724           + (i * BFD_MACH_O_SECTION_SIZE);
3725
3726       sec = bfd_mach_o_read_section (abfd, segoff, seg->initprot, wide);
3727       if (sec == NULL)
3728         return -1;
3729
3730       bfd_mach_o_append_section_to_segment (seg, sec);
3731     }
3732
3733   return 0;
3734 }
3735
3736 static int
3737 bfd_mach_o_read_segment_32 (bfd *abfd, bfd_mach_o_load_command *command)
3738 {
3739   return bfd_mach_o_read_segment (abfd, command, 0);
3740 }
3741
3742 static int
3743 bfd_mach_o_read_segment_64 (bfd *abfd, bfd_mach_o_load_command *command)
3744 {
3745   return bfd_mach_o_read_segment (abfd, command, 1);
3746 }
3747
3748 static int
3749 bfd_mach_o_read_command (bfd *abfd, bfd_mach_o_load_command *command)
3750 {
3751   struct mach_o_load_command_external raw;
3752   unsigned int cmd;
3753
3754   /* Read command type and length.  */
3755   if (bfd_seek (abfd, command->offset, SEEK_SET) != 0
3756       || bfd_bread (&raw, BFD_MACH_O_LC_SIZE, abfd) != BFD_MACH_O_LC_SIZE)
3757     return -1;
3758
3759   cmd = bfd_h_get_32 (abfd, raw.cmd);
3760   command->type =  cmd & ~BFD_MACH_O_LC_REQ_DYLD;
3761   command->type_required = cmd & BFD_MACH_O_LC_REQ_DYLD ? TRUE : FALSE;
3762   command->len = bfd_h_get_32 (abfd, raw.cmdsize);
3763
3764   switch (command->type)
3765     {
3766     case BFD_MACH_O_LC_SEGMENT:
3767       if (bfd_mach_o_read_segment_32 (abfd, command) != 0)
3768         return -1;
3769       break;
3770     case BFD_MACH_O_LC_SEGMENT_64:
3771       if (bfd_mach_o_read_segment_64 (abfd, command) != 0)
3772         return -1;
3773       break;
3774     case BFD_MACH_O_LC_SYMTAB:
3775       if (bfd_mach_o_read_symtab (abfd, command) != 0)
3776         return -1;
3777       break;
3778     case BFD_MACH_O_LC_SYMSEG:
3779       break;
3780     case BFD_MACH_O_LC_THREAD:
3781     case BFD_MACH_O_LC_UNIXTHREAD:
3782       if (bfd_mach_o_read_thread (abfd, command) != 0)
3783         return -1;
3784       break;
3785     case BFD_MACH_O_LC_LOAD_DYLINKER:
3786     case BFD_MACH_O_LC_ID_DYLINKER:
3787       if (bfd_mach_o_read_dylinker (abfd, command) != 0)
3788         return -1;
3789       break;
3790     case BFD_MACH_O_LC_LOAD_DYLIB:
3791     case BFD_MACH_O_LC_ID_DYLIB:
3792     case BFD_MACH_O_LC_LOAD_WEAK_DYLIB:
3793     case BFD_MACH_O_LC_REEXPORT_DYLIB:
3794     case BFD_MACH_O_LC_LOAD_UPWARD_DYLIB:
3795       if (bfd_mach_o_read_dylib (abfd, command) != 0)
3796         return -1;
3797       break;
3798     case BFD_MACH_O_LC_PREBOUND_DYLIB:
3799       if (bfd_mach_o_read_prebound_dylib (abfd, command) != 0)
3800         return -1;
3801       break;
3802     case BFD_MACH_O_LC_LOADFVMLIB:
3803     case BFD_MACH_O_LC_IDFVMLIB:
3804       if (bfd_mach_o_read_fvmlib (abfd, command) != 0)
3805         return -1;
3806       break;
3807     case BFD_MACH_O_LC_IDENT:
3808     case BFD_MACH_O_LC_FVMFILE:
3809     case BFD_MACH_O_LC_PREPAGE:
3810     case BFD_MACH_O_LC_ROUTINES:
3811     case BFD_MACH_O_LC_ROUTINES_64:
3812       break;
3813     case BFD_MACH_O_LC_SUB_FRAMEWORK:
3814     case BFD_MACH_O_LC_SUB_UMBRELLA:
3815     case BFD_MACH_O_LC_SUB_LIBRARY:
3816     case BFD_MACH_O_LC_SUB_CLIENT:
3817     case BFD_MACH_O_LC_RPATH:
3818       if (bfd_mach_o_read_str (abfd, command) != 0)
3819         return -1;
3820       break;
3821     case BFD_MACH_O_LC_DYSYMTAB:
3822       if (bfd_mach_o_read_dysymtab (abfd, command) != 0)
3823         return -1;
3824       break;
3825     case BFD_MACH_O_LC_TWOLEVEL_HINTS:
3826     case BFD_MACH_O_LC_PREBIND_CKSUM:
3827       break;
3828     case BFD_MACH_O_LC_UUID:
3829       if (bfd_mach_o_read_uuid (abfd, command) != 0)
3830         return -1;
3831       break;
3832     case BFD_MACH_O_LC_CODE_SIGNATURE:
3833     case BFD_MACH_O_LC_SEGMENT_SPLIT_INFO:
3834     case BFD_MACH_O_LC_FUNCTION_STARTS:
3835       if (bfd_mach_o_read_linkedit (abfd, command) != 0)
3836         return -1;
3837       break;
3838     case BFD_MACH_O_LC_ENCRYPTION_INFO:
3839       if (!bfd_mach_o_read_encryption_info (abfd, command))
3840         return -1;
3841       break;
3842     case BFD_MACH_O_LC_DYLD_INFO:
3843       if (bfd_mach_o_read_dyld_info (abfd, command) != 0)
3844         return -1;
3845       break;
3846     case BFD_MACH_O_LC_VERSION_MIN_MACOSX:
3847     case BFD_MACH_O_LC_VERSION_MIN_IPHONEOS:
3848       if (!bfd_mach_o_read_version_min (abfd, command))
3849         return -1;
3850       break;
3851     default:
3852       (*_bfd_error_handler)(_("%B: unknown load command 0x%lx"),
3853          abfd, (unsigned long) command->type);
3854       break;
3855     }
3856
3857   return 0;
3858 }
3859
3860 static void
3861 bfd_mach_o_flatten_sections (bfd *abfd)
3862 {
3863   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3864   long csect = 0;
3865   unsigned long i;
3866
3867   /* Count total number of sections.  */
3868   mdata->nsects = 0;
3869
3870   for (i = 0; i < mdata->header.ncmds; i++)
3871     {
3872       if (mdata->commands[i].type == BFD_MACH_O_LC_SEGMENT
3873           || mdata->commands[i].type == BFD_MACH_O_LC_SEGMENT_64)
3874         {
3875           bfd_mach_o_segment_command *seg;
3876
3877           seg = &mdata->commands[i].command.segment;
3878           mdata->nsects += seg->nsects;
3879         }
3880     }
3881
3882   /* Allocate sections array.  */
3883   mdata->sections = bfd_alloc (abfd,
3884                                mdata->nsects * sizeof (bfd_mach_o_section *));
3885
3886   /* Fill the array.  */
3887   csect = 0;
3888
3889   for (i = 0; i < mdata->header.ncmds; i++)
3890     {
3891       if (mdata->commands[i].type == BFD_MACH_O_LC_SEGMENT
3892           || mdata->commands[i].type == BFD_MACH_O_LC_SEGMENT_64)
3893         {
3894           bfd_mach_o_segment_command *seg;
3895           bfd_mach_o_section *sec;
3896
3897           seg = &mdata->commands[i].command.segment;
3898           BFD_ASSERT (csect + seg->nsects <= mdata->nsects);
3899
3900           for (sec = seg->sect_head; sec != NULL; sec = sec->next)
3901             mdata->sections[csect++] = sec;
3902         }
3903     }
3904 }
3905
3906 static bfd_boolean
3907 bfd_mach_o_scan_start_address (bfd *abfd)
3908 {
3909   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
3910   bfd_mach_o_thread_command *cmd = NULL;
3911   unsigned long i;
3912
3913   for (i = 0; i < mdata->header.ncmds; i++)
3914     if ((mdata->commands[i].type == BFD_MACH_O_LC_THREAD) ||
3915         (mdata->commands[i].type == BFD_MACH_O_LC_UNIXTHREAD))
3916       {
3917         cmd = &mdata->commands[i].command.thread;
3918         break;
3919       }
3920
3921   if (cmd == NULL)
3922     return FALSE;
3923
3924   /* FIXME: create a subtarget hook ?  */
3925   for (i = 0; i < cmd->nflavours; i++)
3926     {
3927       if ((mdata->header.cputype == BFD_MACH_O_CPU_TYPE_I386)
3928           && (cmd->flavours[i].flavour
3929               == (unsigned long) BFD_MACH_O_x86_THREAD_STATE32))
3930         {
3931           unsigned char buf[4];
3932
3933           if (bfd_seek (abfd, cmd->flavours[i].offset + 40, SEEK_SET) != 0
3934               || bfd_bread (buf, 4, abfd) != 4)
3935             return FALSE;
3936
3937           abfd->start_address = bfd_h_get_32 (abfd, buf);
3938         }
3939       else if ((mdata->header.cputype == BFD_MACH_O_CPU_TYPE_POWERPC)
3940                && (cmd->flavours[i].flavour == BFD_MACH_O_PPC_THREAD_STATE))
3941         {
3942           unsigned char buf[4];
3943
3944           if (bfd_seek (abfd, cmd->flavours[i].offset + 0, SEEK_SET) != 0
3945               || bfd_bread (buf, 4, abfd) != 4)
3946             return FALSE;
3947
3948           abfd->start_address = bfd_h_get_32 (abfd, buf);
3949         }
3950       else if ((mdata->header.cputype == BFD_MACH_O_CPU_TYPE_POWERPC_64)
3951                && (cmd->flavours[i].flavour == BFD_MACH_O_PPC_THREAD_STATE64))
3952         {
3953           unsigned char buf[8];
3954
3955           if (bfd_seek (abfd, cmd->flavours[i].offset + 0, SEEK_SET) != 0
3956               || bfd_bread (buf, 8, abfd) != 8)
3957             return FALSE;
3958
3959           abfd->start_address = bfd_h_get_64 (abfd, buf);
3960         }
3961       else if ((mdata->header.cputype == BFD_MACH_O_CPU_TYPE_X86_64)
3962                && (cmd->flavours[i].flavour == BFD_MACH_O_x86_THREAD_STATE64))
3963         {
3964           unsigned char buf[8];
3965
3966           if (bfd_seek (abfd, cmd->flavours[i].offset + (16 * 8), SEEK_SET) != 0
3967               || bfd_bread (buf, 8, abfd) != 8)
3968             return FALSE;
3969
3970           abfd->start_address = bfd_h_get_64 (abfd, buf);
3971         }
3972     }
3973
3974   return TRUE;
3975 }
3976
3977 bfd_boolean
3978 bfd_mach_o_set_arch_mach (bfd *abfd,
3979                           enum bfd_architecture arch,
3980                           unsigned long machine)
3981 {
3982   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
3983
3984   /* If this isn't the right architecture for this backend, and this
3985      isn't the generic backend, fail.  */
3986   if (arch != bed->arch
3987       && arch != bfd_arch_unknown
3988       && bed->arch != bfd_arch_unknown)
3989     return FALSE;
3990
3991   return bfd_default_set_arch_mach (abfd, arch, machine);
3992 }
3993
3994 static bfd_boolean
3995 bfd_mach_o_scan (bfd *abfd,
3996                  bfd_mach_o_header *header,
3997                  bfd_mach_o_data_struct *mdata)
3998 {
3999   unsigned int i;
4000   enum bfd_architecture cputype;
4001   unsigned long cpusubtype;
4002   unsigned int hdrsize;
4003
4004   hdrsize = mach_o_wide_p (header) ?
4005     BFD_MACH_O_HEADER_64_SIZE : BFD_MACH_O_HEADER_SIZE;
4006
4007   mdata->header = *header;
4008
4009   abfd->flags = abfd->flags & BFD_IN_MEMORY;
4010   switch (header->filetype)
4011     {
4012     case BFD_MACH_O_MH_OBJECT:
4013       abfd->flags |= HAS_RELOC;
4014       break;
4015     case BFD_MACH_O_MH_EXECUTE:
4016       abfd->flags |= EXEC_P;
4017       break;
4018     case BFD_MACH_O_MH_DYLIB:
4019     case BFD_MACH_O_MH_BUNDLE:
4020       abfd->flags |= DYNAMIC;
4021       break;
4022     }
4023
4024   abfd->tdata.mach_o_data = mdata;
4025
4026   bfd_mach_o_convert_architecture (header->cputype, header->cpusubtype,
4027                                    &cputype, &cpusubtype);
4028   if (cputype == bfd_arch_unknown)
4029     {
4030       (*_bfd_error_handler)
4031         (_("bfd_mach_o_scan: unknown architecture 0x%lx/0x%lx"),
4032          header->cputype, header->cpusubtype);
4033       return FALSE;
4034     }
4035
4036   bfd_set_arch_mach (abfd, cputype, cpusubtype);
4037
4038   if (header->ncmds != 0)
4039     {
4040       mdata->commands = bfd_alloc
4041         (abfd, header->ncmds * sizeof (bfd_mach_o_load_command));
4042       if (mdata->commands == NULL)
4043         return FALSE;
4044
4045       for (i = 0; i < header->ncmds; i++)
4046         {
4047           bfd_mach_o_load_command *cur = &mdata->commands[i];
4048
4049           if (i == 0)
4050             cur->offset = hdrsize;
4051           else
4052             {
4053               bfd_mach_o_load_command *prev = &mdata->commands[i - 1];
4054               cur->offset = prev->offset + prev->len;
4055             }
4056
4057           if (bfd_mach_o_read_command (abfd, cur) < 0)
4058             return FALSE;
4059         }
4060     }
4061
4062   if (bfd_mach_o_scan_start_address (abfd) < 0)
4063     return FALSE;
4064
4065   bfd_mach_o_flatten_sections (abfd);
4066   return TRUE;
4067 }
4068
4069 bfd_boolean
4070 bfd_mach_o_mkobject_init (bfd *abfd)
4071 {
4072   bfd_mach_o_data_struct *mdata = NULL;
4073
4074   mdata = bfd_alloc (abfd, sizeof (bfd_mach_o_data_struct));
4075   if (mdata == NULL)
4076     return FALSE;
4077   abfd->tdata.mach_o_data = mdata;
4078
4079   mdata->header.magic = 0;
4080   mdata->header.cputype = 0;
4081   mdata->header.cpusubtype = 0;
4082   mdata->header.filetype = 0;
4083   mdata->header.ncmds = 0;
4084   mdata->header.sizeofcmds = 0;
4085   mdata->header.flags = 0;
4086   mdata->header.byteorder = BFD_ENDIAN_UNKNOWN;
4087   mdata->commands = NULL;
4088   mdata->nsects = 0;
4089   mdata->sections = NULL;
4090   mdata->dyn_reloc_cache = NULL;
4091
4092   return TRUE;
4093 }
4094
4095 static bfd_boolean
4096 bfd_mach_o_gen_mkobject (bfd *abfd)
4097 {
4098   bfd_mach_o_data_struct *mdata;
4099
4100   if (!bfd_mach_o_mkobject_init (abfd))
4101     return FALSE;
4102
4103   mdata = bfd_mach_o_get_data (abfd);
4104   mdata->header.magic = BFD_MACH_O_MH_MAGIC;
4105   mdata->header.cputype = 0;
4106   mdata->header.cpusubtype = 0;
4107   mdata->header.byteorder = abfd->xvec->byteorder;
4108   mdata->header.version = 1;
4109
4110   return TRUE;
4111 }
4112
4113 const bfd_target *
4114 bfd_mach_o_header_p (bfd *abfd,
4115                      bfd_mach_o_filetype filetype,
4116                      bfd_mach_o_cpu_type cputype)
4117 {
4118   struct bfd_preserve preserve;
4119   bfd_mach_o_header header;
4120
4121   preserve.marker = NULL;
4122   if (!bfd_mach_o_read_header (abfd, &header))
4123     goto wrong;
4124
4125   if (! (header.byteorder == BFD_ENDIAN_BIG
4126          || header.byteorder == BFD_ENDIAN_LITTLE))
4127     {
4128       (*_bfd_error_handler) (_("unknown header byte-order value 0x%lx"),
4129                              (unsigned long) header.byteorder);
4130       goto wrong;
4131     }
4132
4133   if (! ((header.byteorder == BFD_ENDIAN_BIG
4134           && abfd->xvec->byteorder == BFD_ENDIAN_BIG
4135           && abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
4136          || (header.byteorder == BFD_ENDIAN_LITTLE
4137              && abfd->xvec->byteorder == BFD_ENDIAN_LITTLE
4138              && abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)))
4139     goto wrong;
4140
4141   /* Check cputype and filetype.
4142      In case of wildcard, do not accept magics that are handled by existing
4143      targets.  */
4144   if (cputype)
4145     {
4146       if (header.cputype != cputype)
4147         goto wrong;
4148     }
4149
4150   if (filetype)
4151     {
4152       if (header.filetype != filetype)
4153         goto wrong;
4154     }
4155   else
4156     {
4157       switch (header.filetype)
4158         {
4159         case BFD_MACH_O_MH_CORE:
4160           /* Handled by core_p */
4161           goto wrong;
4162         default:
4163           break;
4164         }
4165     }
4166
4167   preserve.marker = bfd_zalloc (abfd, sizeof (bfd_mach_o_data_struct));
4168   if (preserve.marker == NULL
4169       || !bfd_preserve_save (abfd, &preserve))
4170     goto fail;
4171
4172   if (!bfd_mach_o_scan (abfd, &header,
4173                         (bfd_mach_o_data_struct *) preserve.marker))
4174     goto wrong;
4175
4176   bfd_preserve_finish (abfd, &preserve);
4177   return abfd->xvec;
4178
4179  wrong:
4180   bfd_set_error (bfd_error_wrong_format);
4181
4182  fail:
4183   if (preserve.marker != NULL)
4184     bfd_preserve_restore (abfd, &preserve);
4185   return NULL;
4186 }
4187
4188 static const bfd_target *
4189 bfd_mach_o_gen_object_p (bfd *abfd)
4190 {
4191   return bfd_mach_o_header_p (abfd, 0, 0);
4192 }
4193
4194 static const bfd_target *
4195 bfd_mach_o_gen_core_p (bfd *abfd)
4196 {
4197   return bfd_mach_o_header_p (abfd, BFD_MACH_O_MH_CORE, 0);
4198 }
4199
4200 typedef struct mach_o_fat_archentry
4201 {
4202   unsigned long cputype;
4203   unsigned long cpusubtype;
4204   unsigned long offset;
4205   unsigned long size;
4206   unsigned long align;
4207 } mach_o_fat_archentry;
4208
4209 typedef struct mach_o_fat_data_struct
4210 {
4211   unsigned long magic;
4212   unsigned long nfat_arch;
4213   mach_o_fat_archentry *archentries;
4214 } mach_o_fat_data_struct;
4215
4216 const bfd_target *
4217 bfd_mach_o_archive_p (bfd *abfd)
4218 {
4219   mach_o_fat_data_struct *adata = NULL;
4220   struct mach_o_fat_header_external hdr;
4221   unsigned long i;
4222
4223   if (bfd_seek (abfd, 0, SEEK_SET) != 0
4224       || bfd_bread (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
4225     goto error;
4226
4227   adata = bfd_alloc (abfd, sizeof (mach_o_fat_data_struct));
4228   if (adata == NULL)
4229     goto error;
4230
4231   adata->magic = bfd_getb32 (hdr.magic);
4232   adata->nfat_arch = bfd_getb32 (hdr.nfat_arch);
4233   if (adata->magic != 0xcafebabe)
4234     goto error;
4235   /* Avoid matching Java bytecode files, which have the same magic number.
4236      In the Java bytecode file format this field contains the JVM version,
4237      which starts at 43.0.  */
4238   if (adata->nfat_arch > 30)
4239     goto error;
4240
4241   adata->archentries =
4242     bfd_alloc (abfd, adata->nfat_arch * sizeof (mach_o_fat_archentry));
4243   if (adata->archentries == NULL)
4244     goto error;
4245
4246   for (i = 0; i < adata->nfat_arch; i++)
4247     {
4248       struct mach_o_fat_arch_external arch;
4249       if (bfd_bread (&arch, sizeof (arch), abfd) != sizeof (arch))
4250         goto error;
4251       adata->archentries[i].cputype = bfd_getb32 (arch.cputype);
4252       adata->archentries[i].cpusubtype = bfd_getb32 (arch.cpusubtype);
4253       adata->archentries[i].offset = bfd_getb32 (arch.offset);
4254       adata->archentries[i].size = bfd_getb32 (arch.size);
4255       adata->archentries[i].align = bfd_getb32 (arch.align);
4256     }
4257
4258   abfd->tdata.mach_o_fat_data = adata;
4259   return abfd->xvec;
4260
4261  error:
4262   if (adata != NULL)
4263     bfd_release (abfd, adata);
4264   bfd_set_error (bfd_error_wrong_format);
4265   return NULL;
4266 }
4267
4268 /* Set the filename for a fat binary member ABFD, whose bfd architecture is
4269    ARCH_TYPE/ARCH_SUBTYPE and corresponding entry in header is ENTRY.
4270    Set arelt_data and origin fields too.  */
4271
4272 static void
4273 bfd_mach_o_fat_member_init (bfd *abfd,
4274                             enum bfd_architecture arch_type,
4275                             unsigned long arch_subtype,
4276                             mach_o_fat_archentry *entry)
4277 {
4278   struct areltdata *areltdata;
4279   /* Create the member filename. Use ARCH_NAME.  */
4280   const bfd_arch_info_type *ap = bfd_lookup_arch (arch_type, arch_subtype);
4281
4282   if (ap)
4283     {
4284       /* Use the architecture name if known.  */
4285       abfd->filename = ap->printable_name;
4286     }
4287   else
4288     {
4289       /* Forge a uniq id.  */
4290       const size_t namelen = 2 + 8 + 1 + 2 + 8 + 1;
4291       char *name = bfd_alloc (abfd, namelen);
4292       snprintf (name, namelen, "0x%lx-0x%lx",
4293                 entry->cputype, entry->cpusubtype);
4294       abfd->filename = name;
4295     }
4296
4297   areltdata = bfd_zalloc (abfd, sizeof (struct areltdata));
4298   areltdata->parsed_size = entry->size;
4299   abfd->arelt_data = areltdata;
4300   abfd->iostream = NULL;
4301   abfd->origin = entry->offset;
4302 }
4303
4304 bfd *
4305 bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
4306 {
4307   mach_o_fat_data_struct *adata;
4308   mach_o_fat_archentry *entry = NULL;
4309   unsigned long i;
4310   bfd *nbfd;
4311   enum bfd_architecture arch_type;
4312   unsigned long arch_subtype;
4313
4314   adata = (mach_o_fat_data_struct *) archive->tdata.mach_o_fat_data;
4315   BFD_ASSERT (adata != NULL);
4316
4317   /* Find index of previous entry.  */
4318   if (prev == NULL)
4319     {
4320       /* Start at first one.  */
4321       i = 0;
4322     }
4323   else
4324     {
4325       /* Find index of PREV.  */
4326       for (i = 0; i < adata->nfat_arch; i++)
4327         {
4328           if (adata->archentries[i].offset == prev->origin)
4329             break;
4330         }
4331
4332       if (i == adata->nfat_arch)
4333         {
4334           /* Not found.  */
4335           bfd_set_error (bfd_error_bad_value);
4336           return NULL;
4337         }
4338
4339       /* Get next entry.  */
4340       i++;
4341     }
4342
4343   if (i >= adata->nfat_arch)
4344     {
4345       bfd_set_error (bfd_error_no_more_archived_files);
4346       return NULL;
4347     }
4348
4349   entry = &adata->archentries[i];
4350   nbfd = _bfd_new_bfd_contained_in (archive);
4351   if (nbfd == NULL)
4352     return NULL;
4353
4354   bfd_mach_o_convert_architecture (entry->cputype, entry->cpusubtype,
4355                                    &arch_type, &arch_subtype);
4356
4357   bfd_mach_o_fat_member_init (nbfd, arch_type, arch_subtype, entry);
4358
4359   bfd_set_arch_mach (nbfd, arch_type, arch_subtype);
4360
4361   return nbfd;
4362 }
4363
4364 /* Analogous to stat call.  */
4365
4366 static int
4367 bfd_mach_o_fat_stat_arch_elt (bfd *abfd, struct stat *buf)
4368 {
4369   if (abfd->arelt_data == NULL)
4370     {
4371       bfd_set_error (bfd_error_invalid_operation);
4372       return -1;
4373     }
4374
4375   buf->st_mtime = 0;
4376   buf->st_uid = 0;
4377   buf->st_gid = 0;
4378   buf->st_mode = 0644;
4379   buf->st_size = arelt_size (abfd);
4380
4381   return 0;
4382 }
4383
4384 /* If ABFD format is FORMAT and architecture is ARCH, return it.
4385    If ABFD is a fat image containing a member that corresponds to FORMAT
4386    and ARCH, returns it.
4387    In other case, returns NULL.
4388    This function allows transparent uses of fat images.  */
4389
4390 bfd *
4391 bfd_mach_o_fat_extract (bfd *abfd,
4392                         bfd_format format,
4393                         const bfd_arch_info_type *arch)
4394 {
4395   bfd *res;
4396   mach_o_fat_data_struct *adata;
4397   unsigned int i;
4398
4399   if (bfd_check_format (abfd, format))
4400     {
4401       if (bfd_get_arch_info (abfd) == arch)
4402         return abfd;
4403       return NULL;
4404     }
4405   if (!bfd_check_format (abfd, bfd_archive)
4406       || abfd->xvec != &mach_o_fat_vec)
4407     return NULL;
4408
4409   /* This is a Mach-O fat image.  */
4410   adata = (mach_o_fat_data_struct *) abfd->tdata.mach_o_fat_data;
4411   BFD_ASSERT (adata != NULL);
4412
4413   for (i = 0; i < adata->nfat_arch; i++)
4414     {
4415       struct mach_o_fat_archentry *e = &adata->archentries[i];
4416       enum bfd_architecture cpu_type;
4417       unsigned long cpu_subtype;
4418
4419       bfd_mach_o_convert_architecture (e->cputype, e->cpusubtype,
4420                                        &cpu_type, &cpu_subtype);
4421       if (cpu_type != arch->arch || cpu_subtype != arch->mach)
4422         continue;
4423
4424       /* The architecture is found.  */
4425       res = _bfd_new_bfd_contained_in (abfd);
4426       if (res == NULL)
4427         return NULL;
4428
4429       bfd_mach_o_fat_member_init (res, cpu_type, cpu_subtype, e);
4430
4431       if (bfd_check_format (res, format))
4432         {
4433           BFD_ASSERT (bfd_get_arch_info (res) == arch);
4434           return res;
4435         }
4436       bfd_close (res);
4437       return NULL;
4438     }
4439
4440   return NULL;
4441 }
4442
4443 int
4444 bfd_mach_o_lookup_command (bfd *abfd,
4445                            bfd_mach_o_load_command_type type,
4446                            bfd_mach_o_load_command **mcommand)
4447 {
4448   struct mach_o_data_struct *md = bfd_mach_o_get_data (abfd);
4449   bfd_mach_o_load_command *ncmd = NULL;
4450   unsigned int i, num;
4451
4452   BFD_ASSERT (md != NULL);
4453   BFD_ASSERT (mcommand != NULL);
4454
4455   num = 0;
4456   for (i = 0; i < md->header.ncmds; i++)
4457     {
4458       struct bfd_mach_o_load_command *cmd = &md->commands[i];
4459
4460       if (cmd->type != type)
4461         continue;
4462
4463       if (num == 0)
4464         ncmd = cmd;
4465       num++;
4466     }
4467
4468   *mcommand = ncmd;
4469   return num;
4470 }
4471
4472 unsigned long
4473 bfd_mach_o_stack_addr (enum bfd_mach_o_cpu_type type)
4474 {
4475   switch (type)
4476     {
4477     case BFD_MACH_O_CPU_TYPE_MC680x0:
4478       return 0x04000000;
4479     case BFD_MACH_O_CPU_TYPE_MC88000:
4480       return 0xffffe000;
4481     case BFD_MACH_O_CPU_TYPE_POWERPC:
4482       return 0xc0000000;
4483     case BFD_MACH_O_CPU_TYPE_I386:
4484       return 0xc0000000;
4485     case BFD_MACH_O_CPU_TYPE_SPARC:
4486       return 0xf0000000;
4487     case BFD_MACH_O_CPU_TYPE_I860:
4488       return 0;
4489     case BFD_MACH_O_CPU_TYPE_HPPA:
4490       return 0xc0000000 - 0x04000000;
4491     default:
4492       return 0;
4493     }
4494 }
4495
4496 /* The following two tables should be kept, as far as possible, in order of
4497    most frequently used entries to optimize their use from gas.  */
4498
4499 const bfd_mach_o_xlat_name bfd_mach_o_section_type_name[] =
4500 {
4501   { "regular", BFD_MACH_O_S_REGULAR},
4502   { "coalesced", BFD_MACH_O_S_COALESCED},
4503   { "zerofill", BFD_MACH_O_S_ZEROFILL},
4504   { "cstring_literals", BFD_MACH_O_S_CSTRING_LITERALS},
4505   { "4byte_literals", BFD_MACH_O_S_4BYTE_LITERALS},
4506   { "8byte_literals", BFD_MACH_O_S_8BYTE_LITERALS},
4507   { "16byte_literals", BFD_MACH_O_S_16BYTE_LITERALS},
4508   { "literal_pointers", BFD_MACH_O_S_LITERAL_POINTERS},
4509   { "mod_init_func_pointers", BFD_MACH_O_S_MOD_INIT_FUNC_POINTERS},
4510   { "mod_fini_func_pointers", BFD_MACH_O_S_MOD_FINI_FUNC_POINTERS},
4511   { "gb_zerofill", BFD_MACH_O_S_GB_ZEROFILL},
4512   { "interposing", BFD_MACH_O_S_INTERPOSING},
4513   { "dtrace_dof", BFD_MACH_O_S_DTRACE_DOF},
4514   { "non_lazy_symbol_pointers", BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS},
4515   { "lazy_symbol_pointers", BFD_MACH_O_S_LAZY_SYMBOL_POINTERS},
4516   { "symbol_stubs", BFD_MACH_O_S_SYMBOL_STUBS},
4517   { "lazy_dylib_symbol_pointers", BFD_MACH_O_S_LAZY_DYLIB_SYMBOL_POINTERS},
4518   { NULL, 0}
4519 };
4520
4521 const bfd_mach_o_xlat_name bfd_mach_o_section_attribute_name[] =
4522 {
4523   { "pure_instructions", BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS },
4524   { "some_instructions", BFD_MACH_O_S_ATTR_SOME_INSTRUCTIONS },
4525   { "loc_reloc", BFD_MACH_O_S_ATTR_LOC_RELOC },
4526   { "ext_reloc", BFD_MACH_O_S_ATTR_EXT_RELOC },
4527   { "debug", BFD_MACH_O_S_ATTR_DEBUG },
4528   { "live_support", BFD_MACH_O_S_ATTR_LIVE_SUPPORT },
4529   { "no_dead_strip", BFD_MACH_O_S_ATTR_NO_DEAD_STRIP },
4530   { "strip_static_syms", BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS },
4531   { "no_toc", BFD_MACH_O_S_ATTR_NO_TOC },
4532   { "self_modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
4533   { "modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
4534   { NULL, 0}
4535 };
4536
4537 /* Get the section type from NAME.  Return 256 if NAME is unknown.  */
4538
4539 unsigned int
4540 bfd_mach_o_get_section_type_from_name (bfd *abfd, const char *name)
4541 {
4542   const bfd_mach_o_xlat_name *x;
4543   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
4544
4545   for (x = bfd_mach_o_section_type_name; x->name; x++)
4546     if (strcmp (x->name, name) == 0)
4547       {
4548         /* We found it... does the target support it?  */
4549         if (bed->bfd_mach_o_section_type_valid_for_target == NULL
4550             || bed->bfd_mach_o_section_type_valid_for_target (x->val))
4551           return x->val; /* OK.  */
4552         else
4553           break; /* Not supported.  */
4554       }
4555   /* Maximum section ID = 0xff.  */
4556   return 256;
4557 }
4558
4559 /* Get the section attribute from NAME.  Return -1 if NAME is unknown.  */
4560
4561 unsigned int
4562 bfd_mach_o_get_section_attribute_from_name (const char *name)
4563 {
4564   const bfd_mach_o_xlat_name *x;
4565
4566   for (x = bfd_mach_o_section_attribute_name; x->name; x++)
4567     if (strcmp (x->name, name) == 0)
4568       return x->val;
4569   return (unsigned int)-1;
4570 }
4571
4572 int
4573 bfd_mach_o_core_fetch_environment (bfd *abfd,
4574                                    unsigned char **rbuf,
4575                                    unsigned int *rlen)
4576 {
4577   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
4578   unsigned long stackaddr = bfd_mach_o_stack_addr (mdata->header.cputype);
4579   unsigned int i = 0;
4580
4581   for (i = 0; i < mdata->header.ncmds; i++)
4582     {
4583       bfd_mach_o_load_command *cur = &mdata->commands[i];
4584       bfd_mach_o_segment_command *seg = NULL;
4585
4586       if (cur->type != BFD_MACH_O_LC_SEGMENT)
4587         continue;
4588
4589       seg = &cur->command.segment;
4590
4591       if ((seg->vmaddr + seg->vmsize) == stackaddr)
4592         {
4593           unsigned long start = seg->fileoff;
4594           unsigned long end = seg->fileoff + seg->filesize;
4595           unsigned char *buf = bfd_malloc (1024);
4596           unsigned long size = 1024;
4597
4598           for (;;)
4599             {
4600               bfd_size_type nread = 0;
4601               unsigned long offset;
4602               int found_nonnull = 0;
4603
4604               if (size > (end - start))
4605                 size = (end - start);
4606
4607               buf = bfd_realloc_or_free (buf, size);
4608               if (buf == NULL)
4609                 return -1;
4610
4611               if (bfd_seek (abfd, end - size, SEEK_SET) != 0)
4612                 {
4613                   free (buf);
4614                   return -1;
4615                 }
4616
4617               nread = bfd_bread (buf, size, abfd);
4618
4619               if (nread != size)
4620                 {
4621                   free (buf);
4622                   return -1;
4623                 }
4624
4625               for (offset = 4; offset <= size; offset += 4)
4626                 {
4627                   unsigned long val;
4628
4629                   val = *((unsigned long *) (buf + size - offset));
4630                   if (! found_nonnull)
4631                     {
4632                       if (val != 0)
4633                         found_nonnull = 1;
4634                     }
4635                   else if (val == 0x0)
4636                     {
4637                       unsigned long bottom;
4638                       unsigned long top;
4639
4640                       bottom = seg->fileoff + seg->filesize - offset;
4641                       top = seg->fileoff + seg->filesize - 4;
4642                       *rbuf = bfd_malloc (top - bottom);
4643                       *rlen = top - bottom;
4644
4645                       memcpy (*rbuf, buf + size - *rlen, *rlen);
4646                       free (buf);
4647                       return 0;
4648                     }
4649                 }
4650
4651               if (size == (end - start))
4652                 break;
4653
4654               size *= 2;
4655             }
4656
4657           free (buf);
4658         }
4659     }
4660
4661   return -1;
4662 }
4663
4664 char *
4665 bfd_mach_o_core_file_failing_command (bfd *abfd)
4666 {
4667   unsigned char *buf = NULL;
4668   unsigned int len = 0;
4669   int ret = -1;
4670
4671   ret = bfd_mach_o_core_fetch_environment (abfd, &buf, &len);
4672   if (ret < 0)
4673     return NULL;
4674
4675   return (char *) buf;
4676 }
4677
4678 int
4679 bfd_mach_o_core_file_failing_signal (bfd *abfd ATTRIBUTE_UNUSED)
4680 {
4681   return 0;
4682 }
4683
4684 static bfd_mach_o_uuid_command *
4685 bfd_mach_o_lookup_uuid_command (bfd *abfd)
4686 {
4687   bfd_mach_o_load_command *uuid_cmd;
4688   int ncmd = bfd_mach_o_lookup_command (abfd, BFD_MACH_O_LC_UUID, &uuid_cmd);
4689   if (ncmd != 1)
4690     return FALSE;
4691   return &uuid_cmd->command.uuid;
4692 }
4693
4694 /* Return true if ABFD is a dSYM file and its UUID matches UUID_CMD. */
4695
4696 static bfd_boolean
4697 bfd_mach_o_dsym_for_uuid_p (bfd *abfd, const bfd_mach_o_uuid_command *uuid_cmd)
4698 {
4699   bfd_mach_o_uuid_command *dsym_uuid_cmd;
4700
4701   BFD_ASSERT (abfd);
4702   BFD_ASSERT (uuid_cmd);
4703
4704   if (!bfd_check_format (abfd, bfd_object))
4705     return FALSE;
4706
4707   if (bfd_get_flavour (abfd) != bfd_target_mach_o_flavour
4708       || bfd_mach_o_get_data (abfd) == NULL
4709       || bfd_mach_o_get_data (abfd)->header.filetype != BFD_MACH_O_MH_DSYM)
4710     return FALSE;
4711
4712   dsym_uuid_cmd = bfd_mach_o_lookup_uuid_command (abfd);
4713   if (dsym_uuid_cmd == NULL)
4714     return FALSE;
4715
4716   if (memcmp (uuid_cmd->uuid, dsym_uuid_cmd->uuid,
4717               sizeof (uuid_cmd->uuid)) != 0)
4718     return FALSE;
4719
4720   return TRUE;
4721 }
4722
4723 /* Find a BFD in DSYM_FILENAME which matches ARCH and UUID_CMD.
4724    The caller is responsible for closing the returned BFD object and
4725    its my_archive if the returned BFD is in a fat dSYM. */
4726
4727 static bfd *
4728 bfd_mach_o_find_dsym (const char *dsym_filename,
4729                       const bfd_mach_o_uuid_command *uuid_cmd,
4730                       const bfd_arch_info_type *arch)
4731 {
4732   bfd *base_dsym_bfd, *dsym_bfd;
4733
4734   BFD_ASSERT (uuid_cmd);
4735
4736   base_dsym_bfd = bfd_openr (dsym_filename, NULL);
4737   if (base_dsym_bfd == NULL)
4738     return NULL;
4739
4740   dsym_bfd = bfd_mach_o_fat_extract (base_dsym_bfd, bfd_object, arch);
4741   if (bfd_mach_o_dsym_for_uuid_p (dsym_bfd, uuid_cmd))
4742     return dsym_bfd;
4743
4744   bfd_close (dsym_bfd);
4745   if (base_dsym_bfd != dsym_bfd)
4746     bfd_close (base_dsym_bfd);
4747
4748   return NULL;
4749 }
4750
4751 /* Return a BFD created from a dSYM file for ABFD.
4752    The caller is responsible for closing the returned BFD object, its
4753    filename, and its my_archive if the returned BFD is in a fat dSYM. */
4754
4755 static bfd *
4756 bfd_mach_o_follow_dsym (bfd *abfd)
4757 {
4758   char *dsym_filename;
4759   bfd_mach_o_uuid_command *uuid_cmd;
4760   bfd *dsym_bfd, *base_bfd = abfd;
4761   const char *base_basename;
4762
4763   if (abfd == NULL || bfd_get_flavour (abfd) != bfd_target_mach_o_flavour)
4764     return NULL;
4765
4766   if (abfd->my_archive)
4767     base_bfd = abfd->my_archive;
4768   /* BFD may have been opened from a stream. */
4769   if (base_bfd->filename == NULL)
4770     {
4771       bfd_set_error (bfd_error_invalid_operation);
4772       return NULL;
4773     }
4774   base_basename = lbasename (base_bfd->filename);
4775
4776   uuid_cmd = bfd_mach_o_lookup_uuid_command (abfd);
4777   if (uuid_cmd == NULL)
4778     return NULL;
4779
4780   /* TODO: We assume the DWARF file has the same as the binary's.
4781      It seems apple's GDB checks all files in the dSYM bundle directory.
4782      http://opensource.apple.com/source/gdb/gdb-1708/src/gdb/macosx/macosx-tdep.c
4783   */
4784   dsym_filename = (char *)bfd_malloc (strlen (base_bfd->filename)
4785                                        + strlen (dsym_subdir) + 1
4786                                        + strlen (base_basename) + 1);
4787   sprintf (dsym_filename, "%s%s/%s",
4788            base_bfd->filename, dsym_subdir, base_basename);
4789
4790   dsym_bfd = bfd_mach_o_find_dsym (dsym_filename, uuid_cmd,
4791                                    bfd_get_arch_info (abfd));
4792   if (dsym_bfd == NULL)
4793     free (dsym_filename);
4794
4795   return dsym_bfd;
4796 }
4797
4798 bfd_boolean
4799 bfd_mach_o_find_nearest_line (bfd *abfd,
4800                               asection *section,
4801                               asymbol **symbols,
4802                               bfd_vma offset,
4803                               const char **filename_ptr,
4804                               const char **functionname_ptr,
4805                               unsigned int *line_ptr)
4806 {
4807   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
4808   if (mdata == NULL)
4809     return FALSE;
4810   switch (mdata->header.filetype)
4811     {
4812     case BFD_MACH_O_MH_OBJECT:
4813       break;
4814     case BFD_MACH_O_MH_EXECUTE:
4815     case BFD_MACH_O_MH_DYLIB:
4816     case BFD_MACH_O_MH_BUNDLE:
4817     case BFD_MACH_O_MH_KEXT_BUNDLE:
4818       if (mdata->dwarf2_find_line_info == NULL)
4819         {
4820           mdata->dsym_bfd = bfd_mach_o_follow_dsym (abfd);
4821           /* When we couldn't find dSYM for this binary, we look for
4822              the debug information in the binary itself. In this way,
4823              we won't try finding separated dSYM again because
4824              mdata->dwarf2_find_line_info will be filled. */
4825           if (! mdata->dsym_bfd)
4826             break;
4827           if (! _bfd_dwarf2_slurp_debug_info (abfd, mdata->dsym_bfd,
4828                                               dwarf_debug_sections, symbols,
4829                                               &mdata->dwarf2_find_line_info))
4830             return FALSE;
4831         }
4832       break;
4833     default:
4834       return FALSE;
4835     }
4836   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
4837                                      section, symbols, offset,
4838                                      filename_ptr, functionname_ptr,
4839                                      line_ptr, 0,
4840                                      &mdata->dwarf2_find_line_info))
4841     return TRUE;
4842   return FALSE;
4843 }
4844
4845 bfd_boolean
4846 bfd_mach_o_close_and_cleanup (bfd *abfd)
4847 {
4848   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
4849   if (bfd_get_format (abfd) == bfd_object && mdata != NULL)
4850     {
4851       _bfd_dwarf2_cleanup_debug_info (abfd, &mdata->dwarf2_find_line_info);
4852       bfd_mach_o_free_cached_info (abfd);
4853       if (mdata->dsym_bfd != NULL)
4854         {
4855           bfd *fat_bfd = mdata->dsym_bfd->my_archive;
4856           char *dsym_filename = (char *)(fat_bfd
4857                                          ? fat_bfd->filename
4858                                          : mdata->dsym_bfd->filename);
4859           bfd_close (mdata->dsym_bfd);
4860           mdata->dsym_bfd = NULL;
4861           if (fat_bfd)
4862             bfd_close (fat_bfd);
4863           free (dsym_filename);
4864         }
4865     }
4866
4867   return _bfd_generic_close_and_cleanup (abfd);
4868 }
4869
4870 bfd_boolean bfd_mach_o_free_cached_info (bfd *abfd)
4871 {
4872   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
4873   asection *asect;
4874   free (mdata->dyn_reloc_cache);
4875   mdata->dyn_reloc_cache = NULL;
4876   for (asect = abfd->sections; asect != NULL; asect = asect->next)
4877     {
4878       free (asect->relocation);
4879       asect->relocation = NULL;
4880     }
4881
4882   return TRUE;
4883 }
4884
4885 #define bfd_mach_o_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup 
4886 #define bfd_mach_o_bfd_reloc_name_lookup _bfd_norelocs_bfd_reloc_name_lookup
4887
4888 #define bfd_mach_o_swap_reloc_in NULL
4889 #define bfd_mach_o_swap_reloc_out NULL
4890 #define bfd_mach_o_print_thread NULL
4891 #define bfd_mach_o_tgt_seg_table NULL
4892 #define bfd_mach_o_section_type_valid_for_tgt NULL
4893
4894 #define TARGET_NAME             mach_o_be_vec
4895 #define TARGET_STRING           "mach-o-be"
4896 #define TARGET_ARCHITECTURE     bfd_arch_unknown
4897 #define TARGET_BIG_ENDIAN       1
4898 #define TARGET_ARCHIVE          0
4899 #define TARGET_PRIORITY         1
4900 #include "mach-o-target.c"
4901
4902 #undef TARGET_NAME
4903 #undef TARGET_STRING
4904 #undef TARGET_ARCHITECTURE
4905 #undef TARGET_BIG_ENDIAN
4906 #undef TARGET_ARCHIVE
4907 #undef TARGET_PRIORITY
4908
4909 #define TARGET_NAME             mach_o_le_vec
4910 #define TARGET_STRING           "mach-o-le"
4911 #define TARGET_ARCHITECTURE     bfd_arch_unknown
4912 #define TARGET_BIG_ENDIAN       0
4913 #define TARGET_ARCHIVE          0
4914 #define TARGET_PRIORITY         1
4915
4916 #include "mach-o-target.c"
4917
4918 #undef TARGET_NAME
4919 #undef TARGET_STRING
4920 #undef TARGET_ARCHITECTURE
4921 #undef TARGET_BIG_ENDIAN
4922 #undef TARGET_ARCHIVE
4923 #undef TARGET_PRIORITY
4924
4925 /* Not yet handled: creating an archive.  */
4926 #define bfd_mach_o_mkarchive                      _bfd_noarchive_mkarchive
4927
4928 /* Not used.  */
4929 #define bfd_mach_o_read_ar_hdr                    _bfd_noarchive_read_ar_hdr
4930 #define bfd_mach_o_write_ar_hdr                   _bfd_noarchive_write_ar_hdr
4931 #define bfd_mach_o_slurp_armap                    _bfd_noarchive_slurp_armap
4932 #define bfd_mach_o_slurp_extended_name_table      _bfd_noarchive_slurp_extended_name_table
4933 #define bfd_mach_o_construct_extended_name_table  _bfd_noarchive_construct_extended_name_table
4934 #define bfd_mach_o_truncate_arname                _bfd_noarchive_truncate_arname
4935 #define bfd_mach_o_write_armap                    _bfd_noarchive_write_armap
4936 #define bfd_mach_o_get_elt_at_index               _bfd_noarchive_get_elt_at_index
4937 #define bfd_mach_o_generic_stat_arch_elt          bfd_mach_o_fat_stat_arch_elt
4938 #define bfd_mach_o_update_armap_timestamp         _bfd_noarchive_update_armap_timestamp
4939
4940 #define TARGET_NAME             mach_o_fat_vec
4941 #define TARGET_STRING           "mach-o-fat"
4942 #define TARGET_ARCHITECTURE     bfd_arch_unknown
4943 #define TARGET_BIG_ENDIAN       1
4944 #define TARGET_ARCHIVE          1
4945 #define TARGET_PRIORITY         0
4946
4947 #include "mach-o-target.c"
4948
4949 #undef TARGET_NAME
4950 #undef TARGET_STRING
4951 #undef TARGET_ARCHITECTURE
4952 #undef TARGET_BIG_ENDIAN
4953 #undef TARGET_ARCHIVE
4954 #undef TARGET_PRIORITY