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