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