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