Handle R_X86_64_64 properly for x32
[deliverable/binutils-gdb.git] / bfd / mach-o.c
index c768689fda0772e8ccbb7887eb0fb2b909b4e23f..1f9fc17608539692303a4c1c4c181d047355b730 100644 (file)
@@ -1,6 +1,6 @@
 /* Mach-O support for BFD.
    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
 /* Mach-O support for BFD.
    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
-   2009, 2010, 2011
+   2009, 2010, 2011, 2012
    Free Software Foundation, Inc.
 
    This file is part of BFD, the Binary File Descriptor library.
    Free Software Foundation, Inc.
 
    This file is part of BFD, the Binary File Descriptor library.
@@ -29,6 +29,8 @@
 #include "mach-o/reloc.h"
 #include "mach-o/external.h"
 #include <ctype.h>
 #include "mach-o/reloc.h"
 #include "mach-o/external.h"
 #include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
 
 #define bfd_mach_o_object_p bfd_mach_o_gen_object_p
 #define bfd_mach_o_core_p bfd_mach_o_gen_core_p
 
 #define bfd_mach_o_object_p bfd_mach_o_gen_object_p
 #define bfd_mach_o_core_p bfd_mach_o_gen_core_p
@@ -119,10 +121,10 @@ static const mach_o_section_name_xlat text_section_names_xlat[] =
        SEC_CODE | SEC_LOAD,                    BFD_MACH_O_S_REGULAR,
        BFD_MACH_O_S_ATTR_NONE,                 0},
     {  ".eh_frame",                            "__eh_frame",
        SEC_CODE | SEC_LOAD,                    BFD_MACH_O_S_REGULAR,
        BFD_MACH_O_S_ATTR_NONE,                 0},
     {  ".eh_frame",                            "__eh_frame",
-       SEC_READONLY | SEC_LOAD,                BFD_MACH_O_S_COALESCED,
+       SEC_READONLY | SEC_DATA | SEC_LOAD,     BFD_MACH_O_S_COALESCED,
        BFD_MACH_O_S_ATTR_LIVE_SUPPORT
        | BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS
        BFD_MACH_O_S_ATTR_LIVE_SUPPORT
        | BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS
-       | BFD_MACH_O_S_ATTR_NO_TOC,             3},
+       | BFD_MACH_O_S_ATTR_NO_TOC,             2},
     { NULL, NULL, 0, 0, 0, 0}
   };
 
     { NULL, NULL, 0, 0, 0, 0}
   };
 
@@ -277,6 +279,8 @@ static const mach_o_segment_name_xlat segsec_names_xlat[] =
     { NULL, NULL }
   };
 
     { NULL, NULL }
   };
 
+static const char dsym_subdir[] = ".dSYM/Contents/Resources/DWARF";
+
 /* For both cases bfd-name => mach-o name and vice versa, the specific target
    is checked before the generic.  This allows a target (e.g. ppc for cstring)
    to override the generic definition with a more specific one.  */
 /* For both cases bfd-name => mach-o name and vice versa, the specific target
    is checked before the generic.  This allows a target (e.g. ppc for cstring)
    to override the generic definition with a more specific one.  */
@@ -529,10 +533,17 @@ bfd_mach_o_section_get_nbr_indirect (bfd *abfd, bfd_mach_o_section *sec)
 
 bfd_boolean
 bfd_mach_o_bfd_copy_private_symbol_data (bfd *ibfd ATTRIBUTE_UNUSED,
 
 bfd_boolean
 bfd_mach_o_bfd_copy_private_symbol_data (bfd *ibfd ATTRIBUTE_UNUSED,
-                                        asymbol *isymbol ATTRIBUTE_UNUSED,
+                                        asymbol *isymbol,
                                         bfd *obfd ATTRIBUTE_UNUSED,
                                         bfd *obfd ATTRIBUTE_UNUSED,
-                                        asymbol *osymbol ATTRIBUTE_UNUSED)
+                                        asymbol *osymbol)
 {
 {
+  bfd_mach_o_asymbol *os, *is;
+  os = (bfd_mach_o_asymbol *)osymbol;
+  is = (bfd_mach_o_asymbol *)isymbol;
+  os->n_type = is->n_type;
+  os->n_sect = is->n_sect;
+  os->n_desc = is->n_desc;
+  os->symbol.udata.i = is->symbol.udata.i;
   return TRUE;
 }
 
   return TRUE;
 }
 
@@ -576,6 +587,22 @@ bfd_mach_o_bfd_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
   return TRUE;
 }
 
   return TRUE;
 }
 
+/* This allows us to set up to 32 bits of flags (unless we invent some
+   fiendish scheme to subdivide).  For now, we'll just set the file flags
+   without error checking - just overwrite.  */
+   
+bfd_boolean
+bfd_mach_o_bfd_set_private_flags (bfd *abfd, flagword flags)
+{
+  bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
+
+  if (!mdata)
+    return FALSE;
+
+  mdata->header.flags = flags;
+  return TRUE;
+}
+
 /* Count the total number of symbols.  */
 
 static long
 /* Count the total number of symbols.  */
 
 static long
@@ -631,6 +658,8 @@ bfd_mach_o_canonicalize_symtab (bfd *abfd, asymbol **alocation)
   return nsyms;
 }
 
   return nsyms;
 }
 
+/* Create synthetic symbols for indirect symbols.  */
+
 long
 bfd_mach_o_get_synthetic_symtab (bfd *abfd,
                                  long symcount ATTRIBUTE_UNUSED,
 long
 bfd_mach_o_get_synthetic_symtab (bfd *abfd,
                                  long symcount ATTRIBUTE_UNUSED,
@@ -650,19 +679,23 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,
 
   *ret = NULL;
 
 
   *ret = NULL;
 
+  /* Stop now if no symbols or no indirect symbols.  */
   if (dysymtab == NULL || symtab == NULL || symtab->symbols == NULL)
     return 0;
 
   if (dysymtab->nindirectsyms == 0)
     return 0;
 
   if (dysymtab == NULL || symtab == NULL || symtab->symbols == NULL)
     return 0;
 
   if (dysymtab->nindirectsyms == 0)
     return 0;
 
+  /* We need to allocate a bfd symbol for every indirect symbol and to
+     allocate the memory for its name.  */
   count = dysymtab->nindirectsyms;
   size = count * sizeof (asymbol) + 1;
 
   for (j = 0; j < count; j++)
     {
       unsigned int isym = dysymtab->indirect_syms[j];
   count = dysymtab->nindirectsyms;
   size = count * sizeof (asymbol) + 1;
 
   for (j = 0; j < count; j++)
     {
       unsigned int isym = dysymtab->indirect_syms[j];
-              
+
+      /* Some indirect symbols are anonymous.  */
       if (isym < symtab->nsyms && symtab->symbols[isym].symbol.name)
         size += strlen (symtab->symbols[isym].symbol.name) + sizeof ("$stub");
     }
       if (isym < symtab->nsyms && symtab->symbols[isym].symbol.name)
         size += strlen (symtab->symbols[isym].symbol.name) + sizeof ("$stub");
     }
@@ -687,6 +720,7 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,
         case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
         case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
         case BFD_MACH_O_S_SYMBOL_STUBS:
         case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
         case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
         case BFD_MACH_O_S_SYMBOL_STUBS:
+          /* Only these sections have indirect symbols.  */
           first = sec->reserved1;
           last = first + bfd_mach_o_section_get_nbr_indirect (abfd, sec);
           addr = sec->addr;
           first = sec->reserved1;
           last = first + bfd_mach_o_section_get_nbr_indirect (abfd, sec);
           addr = sec->addr;
@@ -794,7 +828,7 @@ bfd_mach_o_print_symbol (bfd *abfd,
 
 static void
 bfd_mach_o_convert_architecture (bfd_mach_o_cpu_type mtype,
 
 static void
 bfd_mach_o_convert_architecture (bfd_mach_o_cpu_type mtype,
-                                bfd_mach_o_cpu_subtype msubtype ATTRIBUTE_UNUSED,
+                                bfd_mach_o_cpu_subtype msubtype,
                                 enum bfd_architecture *type,
                                 unsigned long *subtype)
 {
                                 enum bfd_architecture *type,
                                 unsigned long *subtype)
 {
@@ -802,8 +836,12 @@ bfd_mach_o_convert_architecture (bfd_mach_o_cpu_type mtype,
 
   switch (mtype)
     {
 
   switch (mtype)
     {
-    case BFD_MACH_O_CPU_TYPE_VAX: *type = bfd_arch_vax; break;
-    case BFD_MACH_O_CPU_TYPE_MC680x0: *type = bfd_arch_m68k; break;
+    case BFD_MACH_O_CPU_TYPE_VAX:
+      *type = bfd_arch_vax;
+      break;
+    case BFD_MACH_O_CPU_TYPE_MC680x0:
+      *type = bfd_arch_m68k;
+      break;
     case BFD_MACH_O_CPU_TYPE_I386:
       *type = bfd_arch_i386;
       *subtype = bfd_mach_i386_i386;
     case BFD_MACH_O_CPU_TYPE_I386:
       *type = bfd_arch_i386;
       *subtype = bfd_mach_i386_i386;
@@ -812,17 +850,52 @@ bfd_mach_o_convert_architecture (bfd_mach_o_cpu_type mtype,
       *type = bfd_arch_i386;
       *subtype = bfd_mach_x86_64;
       break;
       *type = bfd_arch_i386;
       *subtype = bfd_mach_x86_64;
       break;
-    case BFD_MACH_O_CPU_TYPE_MIPS: *type = bfd_arch_mips; break;
-    case BFD_MACH_O_CPU_TYPE_MC98000: *type = bfd_arch_m98k; break;
-    case BFD_MACH_O_CPU_TYPE_HPPA: *type = bfd_arch_hppa; break;
-    case BFD_MACH_O_CPU_TYPE_ARM: *type = bfd_arch_arm; break;
-    case BFD_MACH_O_CPU_TYPE_MC88000: *type = bfd_arch_m88k; break;
+    case BFD_MACH_O_CPU_TYPE_MIPS:
+      *type = bfd_arch_mips;
+      break;
+    case BFD_MACH_O_CPU_TYPE_MC98000:
+      *type = bfd_arch_m98k;
+      break;
+    case BFD_MACH_O_CPU_TYPE_HPPA:
+      *type = bfd_arch_hppa;
+      break;
+    case BFD_MACH_O_CPU_TYPE_ARM:
+      *type = bfd_arch_arm;
+      switch (msubtype)
+        {
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_V4T:
+          *subtype = bfd_mach_arm_4T;
+          break;
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_V6:
+          *subtype = bfd_mach_arm_4T;  /* Best fit ?  */
+          break;
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_V5TEJ:
+          *subtype = bfd_mach_arm_5TE;
+          break;
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_XSCALE:
+          *subtype = bfd_mach_arm_XScale;
+          break;
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_V7:
+          *subtype = bfd_mach_arm_5TE; /* Best fit ?  */
+          break;
+        case BFD_MACH_O_CPU_SUBTYPE_ARM_ALL:
+        default:
+          break;
+        }
+      break;
+    case BFD_MACH_O_CPU_TYPE_MC88000:
+      *type = bfd_arch_m88k;
+      break;
     case BFD_MACH_O_CPU_TYPE_SPARC:
       *type = bfd_arch_sparc;
       *subtype = bfd_mach_sparc;
       break;
     case BFD_MACH_O_CPU_TYPE_SPARC:
       *type = bfd_arch_sparc;
       *subtype = bfd_mach_sparc;
       break;
-    case BFD_MACH_O_CPU_TYPE_I860: *type = bfd_arch_i860; break;
-    case BFD_MACH_O_CPU_TYPE_ALPHA: *type = bfd_arch_alpha; break;
+    case BFD_MACH_O_CPU_TYPE_I860:
+      *type = bfd_arch_i860;
+      break;
+    case BFD_MACH_O_CPU_TYPE_ALPHA:
+      *type = bfd_arch_alpha;
+      break;
     case BFD_MACH_O_CPU_TYPE_POWERPC:
       *type = bfd_arch_powerpc;
       *subtype = bfd_mach_ppc;
     case BFD_MACH_O_CPU_TYPE_POWERPC:
       *type = bfd_arch_powerpc;
       *subtype = bfd_mach_ppc;
@@ -902,6 +975,35 @@ bfd_mach_o_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
   return (asect->reloc_count + 1) * sizeof (arelent *);
 }
 
   return (asect->reloc_count + 1) * sizeof (arelent *);
 }
 
+/* In addition to the need to byte-swap the symbol number, the bit positions
+   of the fields in the relocation information vary per target endian-ness.  */
+
+static void
+bfd_mach_o_swap_in_non_scattered_reloc (bfd *abfd, bfd_mach_o_reloc_info *rel,
+                                      unsigned char *fields)
+{
+  unsigned char info = fields[3];
+
+  if (bfd_big_endian (abfd))
+    {
+      rel->r_value = (fields[0] << 16) | (fields[1] << 8) | fields[2];
+      rel->r_type = (info >> BFD_MACH_O_BE_TYPE_SHIFT) & BFD_MACH_O_TYPE_MASK;
+      rel->r_pcrel = (info & BFD_MACH_O_BE_PCREL) ? 1 : 0;
+      rel->r_length = (info >> BFD_MACH_O_BE_LENGTH_SHIFT) 
+                     & BFD_MACH_O_LENGTH_MASK;
+      rel->r_extern = (info & BFD_MACH_O_BE_EXTERN) ? 1 : 0;
+    }
+  else
+    {
+      rel->r_value = (fields[2] << 16) | (fields[1] << 8) | fields[0];
+      rel->r_type = (info >> BFD_MACH_O_LE_TYPE_SHIFT) & BFD_MACH_O_TYPE_MASK;
+      rel->r_pcrel = (info & BFD_MACH_O_LE_PCREL) ? 1 : 0;
+      rel->r_length = (info >> BFD_MACH_O_LE_LENGTH_SHIFT) 
+                     & BFD_MACH_O_LENGTH_MASK;
+      rel->r_extern = (info & BFD_MACH_O_LE_EXTERN) ? 1 : 0;
+    }
+}
+
 static int
 bfd_mach_o_canonicalize_one_reloc (bfd *abfd,
                                    struct mach_o_reloc_info_external *raw,
 static int
 bfd_mach_o_canonicalize_one_reloc (bfd *abfd,
                                    struct mach_o_reloc_info_external *raw,
@@ -911,20 +1013,28 @@ bfd_mach_o_canonicalize_one_reloc (bfd *abfd,
   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
   bfd_mach_o_reloc_info reloc;
   bfd_vma addr;
   bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
   bfd_mach_o_reloc_info reloc;
   bfd_vma addr;
-  bfd_vma symnum;
   asymbol **sym;
 
   addr = bfd_get_32 (abfd, raw->r_address);
   asymbol **sym;
 
   addr = bfd_get_32 (abfd, raw->r_address);
-  symnum = bfd_get_32 (abfd, raw->r_symbolnum);
+  res->sym_ptr_ptr = NULL;
+  res->addend = 0;
   
   if (addr & BFD_MACH_O_SR_SCATTERED)
     {
       unsigned int j;
   
   if (addr & BFD_MACH_O_SR_SCATTERED)
     {
       unsigned int j;
+      bfd_vma symnum = bfd_get_32 (abfd, raw->r_symbolnum);
 
 
-      /* Scattered relocation.
-         Extract section and offset from r_value.  */
-      res->sym_ptr_ptr = NULL;
-      res->addend = 0;
+      /* Scattered relocation, can't be extern. */
+      reloc.r_scattered = 1;
+      reloc.r_extern = 0;
+
+      /*   Extract section and offset from r_value (symnum).  */
+      reloc.r_value = symnum;
+      /* FIXME: This breaks when a symbol in a reloc exactly follows the
+        end of the data for the section (e.g. in a calculation of section
+        data length).  At present, the symbol will end up associated with
+        the following section or, if it falls within alignment padding, as
+        null - which will assert later.  */
       for (j = 0; j < mdata->nsects; j++)
         {
           bfd_mach_o_section *sect = mdata->sections[j];
       for (j = 0; j < mdata->nsects; j++)
         {
           bfd_mach_o_section *sect = mdata->sections[j];
@@ -935,42 +1045,62 @@ bfd_mach_o_canonicalize_one_reloc (bfd *abfd,
               break;
             }
         }
               break;
             }
         }
-      res->address = BFD_MACH_O_GET_SR_ADDRESS (addr);
+
+      /* Extract the info and address fields from r_address.  */
       reloc.r_type = BFD_MACH_O_GET_SR_TYPE (addr);
       reloc.r_length = BFD_MACH_O_GET_SR_LENGTH (addr);
       reloc.r_pcrel = addr & BFD_MACH_O_SR_PCREL;
       reloc.r_type = BFD_MACH_O_GET_SR_TYPE (addr);
       reloc.r_length = BFD_MACH_O_GET_SR_LENGTH (addr);
       reloc.r_pcrel = addr & BFD_MACH_O_SR_PCREL;
-      reloc.r_scattered = 1;
+      reloc.r_address = BFD_MACH_O_GET_SR_TYPE (addr);
+      res->address = BFD_MACH_O_GET_SR_ADDRESS (addr);
     }
   else
     {
     }
   else
     {
-      unsigned int num = BFD_MACH_O_GET_R_SYMBOLNUM (symnum);
-      res->addend = 0;
-      res->address = addr;
-      if (symnum & BFD_MACH_O_R_EXTERN)
-        {
+      unsigned int num;
+      
+      /* Non-scattered relocation.  */
+      reloc.r_scattered = 0;
+      
+      /* The value and info fields have to be extracted dependent on target
+         endian-ness.  */
+      bfd_mach_o_swap_in_non_scattered_reloc (abfd, &reloc, raw->r_symbolnum);
+      num = reloc.r_value;
+
+      if (reloc.r_extern)
           sym = syms + num;
           sym = syms + num;
-          reloc.r_extern = 1;
-        }
-      else
+      else if (reloc.r_scattered
+              || (reloc.r_type != BFD_MACH_O_GENERIC_RELOC_PAIR))
         {
           BFD_ASSERT (num != 0);
           BFD_ASSERT (num <= mdata->nsects);
           sym = mdata->sections[num - 1]->bfdsection->symbol_ptr_ptr;
           /* For a symbol defined in section S, the addend (stored in the
              binary) contains the address of the section.  To comply with
         {
           BFD_ASSERT (num != 0);
           BFD_ASSERT (num <= mdata->nsects);
           sym = mdata->sections[num - 1]->bfdsection->symbol_ptr_ptr;
           /* For a symbol defined in section S, the addend (stored in the
              binary) contains the address of the section.  To comply with
-             bfd conventio, substract the section address.
+             bfd convention, subtract the section address.
              Use the address from the header, so that the user can modify
              the vma of the section.  */
           res->addend = -mdata->sections[num - 1]->addr;
              Use the address from the header, so that the user can modify
              the vma of the section.  */
           res->addend = -mdata->sections[num - 1]->addr;
-          reloc.r_extern = 0;
+        }
+      else /* ... The 'symnum' in a non-scattered PAIR will be 0x00ffffff.  */
+        {
+          /* Pairs for PPC LO/HI/HA are not scattered, but contain the offset
+             in the lower 16bits of the address value.  So we have to find the
+             'symbol' from the preceding reloc.  We do this even thoough the
+             section symbol is probably not needed here, because NULL symbol
+             values cause an assert in generic BFD code.  */
+          sym = (res - 1)->sym_ptr_ptr;
         }
       res->sym_ptr_ptr = sym;
         }
       res->sym_ptr_ptr = sym;
-      reloc.r_type = BFD_MACH_O_GET_R_TYPE (symnum);
-      reloc.r_length = BFD_MACH_O_GET_R_LENGTH (symnum);
-      reloc.r_pcrel = (symnum & BFD_MACH_O_R_PCREL) ? 1 : 0;
-      reloc.r_scattered = 0;
+      
+      /* The 'address' is just r_address.
+         ??? maybe this should be masked with  0xffffff for safety.  */
+      res->address = addr;
+      reloc.r_address = addr;
     }
   
     }
   
+  /* We have set up a reloc with all the information present, so the swapper can
+     modify address, value and addend fields, if necessary, to convey information
+     in the generic BFD reloc that is mach-o specific.  */
+
   if (!(*bed->_bfd_mach_o_swap_reloc_in)(res, &reloc))
     return -1;
   return 0;
   if (!(*bed->_bfd_mach_o_swap_reloc_in)(res, &reloc))
     return -1;
   return 0;
@@ -1024,21 +1154,25 @@ bfd_mach_o_canonicalize_reloc (bfd *abfd, asection *asect,
   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
     return 0;
 
   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
     return 0;
 
-  res = bfd_malloc (asect->reloc_count * sizeof (arelent));
-  if (res == NULL)
-    return -1;
-
-  if (bfd_mach_o_canonicalize_relocs (abfd, asect->rel_filepos,
-                                      asect->reloc_count, res, syms) < 0)
+  if (asect->relocation == NULL)
     {
     {
-      free (res);
-      return -1;
+      res = bfd_malloc (asect->reloc_count * sizeof (arelent));
+      if (res == NULL)
+        return -1;
+
+      if (bfd_mach_o_canonicalize_relocs (abfd, asect->rel_filepos,
+                                          asect->reloc_count, res, syms) < 0)
+        {
+          free (res);
+          return -1;
+        }
+      asect->relocation = res;
     }
 
     }
 
+  res = asect->relocation;
   for (i = 0; i < asect->reloc_count; i++)
     rels[i] = &res[i];
   rels[i] = NULL;
   for (i = 0; i < asect->reloc_count; i++)
     rels[i] = &res[i];
   rels[i] = NULL;
-  asect->relocation = res;
 
   return i;
 }
 
   return i;
 }
@@ -1050,7 +1184,7 @@ bfd_mach_o_get_dynamic_reloc_upper_bound (bfd *abfd)
 
   if (mdata->dysymtab == NULL)
     return 1;
 
   if (mdata->dysymtab == NULL)
     return 1;
-  return (mdata->dysymtab->nextrel + mdata->dysymtab->nlocrel)
+  return (mdata->dysymtab->nextrel + mdata->dysymtab->nlocrel + 1)
     * sizeof (arelent *);
 }
 
     * sizeof (arelent *);
 }
 
@@ -1073,35 +1207,76 @@ bfd_mach_o_canonicalize_dynamic_reloc (bfd *abfd, arelent **rels,
   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
     return 0;
 
   if (bed->_bfd_mach_o_swap_reloc_in == NULL)
     return 0;
 
-  res = bfd_malloc ((dysymtab->nextrel + dysymtab->nlocrel) * sizeof (arelent));
-  if (res == NULL)
-    return -1;
-
-  if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->extreloff,
-                                      dysymtab->nextrel, res, syms) < 0)
+  if (mdata->dyn_reloc_cache == NULL)
     {
     {
-      free (res);
-      return -1;
-    }
+      res = bfd_malloc ((dysymtab->nextrel + dysymtab->nlocrel)
+                        * sizeof (arelent));
+      if (res == NULL)
+        return -1;
 
 
-  if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->locreloff,
-                                      dysymtab->nlocrel,
-                                      res + dysymtab->nextrel, syms) < 0)
-    {
-      free (res);
-      return -1;
+      if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->extreloff,
+                                          dysymtab->nextrel, res, syms) < 0)
+        {
+          free (res);
+          return -1;
+        }
+
+      if (bfd_mach_o_canonicalize_relocs (abfd, dysymtab->locreloff,
+                                          dysymtab->nlocrel,
+                                          res + dysymtab->nextrel, syms) < 0)
+        {
+          free (res);
+          return -1;
+        }
+
+      mdata->dyn_reloc_cache = res;
     }
 
     }
 
+  res = mdata->dyn_reloc_cache;
   for (i = 0; i < dysymtab->nextrel + dysymtab->nlocrel; i++)
     rels[i] = &res[i];
   rels[i] = NULL;
   return i;
 }
 
   for (i = 0; i < dysymtab->nextrel + dysymtab->nlocrel; i++)
     rels[i] = &res[i];
   rels[i] = NULL;
   return i;
 }
 
+/* In addition to the need to byte-swap the symbol number, the bit positions
+   of the fields in the relocation information vary per target endian-ness.  */
+
+static void
+bfd_mach_o_swap_out_non_scattered_reloc (bfd *abfd, unsigned char *fields,
+                                      bfd_mach_o_reloc_info *rel)
+{
+  unsigned char info = 0;
+
+  BFD_ASSERT (rel->r_type <= 15);
+  BFD_ASSERT (rel->r_length <= 3);
+
+  if (bfd_big_endian (abfd))
+    {
+      fields[0] = (rel->r_value >> 16) & 0xff;
+      fields[1] = (rel->r_value >> 8) & 0xff;
+      fields[2] = rel->r_value & 0xff;
+      info |= rel->r_type << BFD_MACH_O_BE_TYPE_SHIFT;
+      info |= rel->r_pcrel ? BFD_MACH_O_BE_PCREL : 0;
+      info |= rel->r_length << BFD_MACH_O_BE_LENGTH_SHIFT;
+      info |= rel->r_extern ? BFD_MACH_O_BE_EXTERN : 0;
+    }
+  else
+    {
+      fields[2] = (rel->r_value >> 16) & 0xff;
+      fields[1] = (rel->r_value >> 8) & 0xff;
+      fields[0] = rel->r_value & 0xff;
+      info |= rel->r_type << BFD_MACH_O_LE_TYPE_SHIFT;
+      info |= rel->r_pcrel ? BFD_MACH_O_LE_PCREL : 0;
+      info |= rel->r_length << BFD_MACH_O_LE_LENGTH_SHIFT;
+      info |= rel->r_extern ? BFD_MACH_O_LE_EXTERN : 0;
+    }
+  fields[3] = info;
+}
+
 static bfd_boolean
 bfd_mach_o_write_relocs (bfd *abfd, bfd_mach_o_section *section)
 {
 static bfd_boolean
 bfd_mach_o_write_relocs (bfd *abfd, bfd_mach_o_section *section)
 {
-  bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
   unsigned int i;
   arelent **entries;
   asection *sec;
   unsigned int i;
   arelent **entries;
   asection *sec;
@@ -1114,13 +1289,6 @@ bfd_mach_o_write_relocs (bfd *abfd, bfd_mach_o_section *section)
   if (bed->_bfd_mach_o_swap_reloc_out == NULL)
     return TRUE;
 
   if (bed->_bfd_mach_o_swap_reloc_out == NULL)
     return TRUE;
 
-  /* Allocate relocation room.  */
-  mdata->filelen = FILE_ALIGN(mdata->filelen, 2);
-  section->nreloc = sec->reloc_count;
-  sec->rel_filepos = mdata->filelen;
-  section->reloff = sec->rel_filepos;
-  mdata->filelen += sec->reloc_count * BFD_MACH_O_RELENT_SIZE;
-
   if (bfd_seek (abfd, section->reloff, SEEK_SET) != 0)
     return FALSE;
 
   if (bfd_seek (abfd, section->reloff, SEEK_SET) != 0)
     return FALSE;
 
@@ -1152,15 +1320,9 @@ bfd_mach_o_write_relocs (bfd *abfd, bfd_mach_o_section *section)
         }
       else
         {
         }
       else
         {
-          unsigned long v;
-
           bfd_put_32 (abfd, pinfo->r_address, raw.r_address);
           bfd_put_32 (abfd, pinfo->r_address, raw.r_address);
-          v = BFD_MACH_O_SET_R_SYMBOLNUM (pinfo->r_value)
-            | (pinfo->r_pcrel ? BFD_MACH_O_R_PCREL : 0)
-            | BFD_MACH_O_SET_R_LENGTH (pinfo->r_length)
-            | (pinfo->r_extern ? BFD_MACH_O_R_EXTERN : 0)
-            | BFD_MACH_O_SET_R_TYPE (pinfo->r_type);
-          bfd_put_32 (abfd, v, raw.r_symbolnum);
+          bfd_mach_o_swap_out_non_scattered_reloc (abfd, raw.r_symbolnum,
+                                                  pinfo);
         }
 
       if (bfd_bwrite (&raw, BFD_MACH_O_RELENT_SIZE, abfd)
         }
 
       if (bfd_bwrite (&raw, BFD_MACH_O_RELENT_SIZE, abfd)
@@ -1323,14 +1485,14 @@ bfd_mach_o_write_symtab (bfd *abfd, bfd_mach_o_load_command *command)
     {
       bfd_size_type str_index;
       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
     {
       bfd_size_type str_index;
       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
-
-      /* Compute name index.  */
-      /* An index of 0 always means the empty string.  */
+     
       if (s->symbol.name == 0 || s->symbol.name[0] == '\0')
       if (s->symbol.name == 0 || s->symbol.name[0] == '\0')
+       /* An index of 0 always means the empty string.  */
         str_index = 0;
       else
         {
           str_index = _bfd_stringtab_add (strtab, s->symbol.name, TRUE, FALSE);
         str_index = 0;
       else
         {
           str_index = _bfd_stringtab_add (strtab, s->symbol.name, TRUE, FALSE);
+
           if (str_index == (bfd_size_type) -1)
             goto err;
         }
           if (str_index == (bfd_size_type) -1)
             goto err;
         }
@@ -1393,8 +1555,258 @@ bfd_mach_o_write_symtab (bfd *abfd, bfd_mach_o_load_command *command)
   return FALSE;
 }
 
   return FALSE;
 }
 
-/* Process the symbols and generate Mach-O specific fields.
-   Number them.  */
+/* Write a dysymtab command.
+   TODO: Possibly coalesce writes of smaller objects.  */
+
+static bfd_boolean
+bfd_mach_o_write_dysymtab (bfd *abfd, bfd_mach_o_load_command *command)
+{
+  bfd_mach_o_dysymtab_command *cmd = &command->command.dysymtab;
+
+  BFD_ASSERT (command->type == BFD_MACH_O_LC_DYSYMTAB);
+
+  if (cmd->nmodtab != 0)
+    {
+      unsigned int i;
+
+      if (bfd_seek (abfd, cmd->modtaboff, SEEK_SET) != 0)
+       return FALSE;
+
+      for (i = 0; i < cmd->nmodtab; i++)
+       {
+         bfd_mach_o_dylib_module *module = &cmd->dylib_module[i];
+         unsigned int iinit;
+         unsigned int ninit;
+
+         iinit = module->iinit & 0xffff;
+         iinit |= ((module->iterm & 0xffff) << 16);
+
+         ninit = module->ninit & 0xffff;
+         ninit |= ((module->nterm & 0xffff) << 16);
+
+         if (bfd_mach_o_wide_p (abfd))
+           {
+             struct mach_o_dylib_module_64_external w;
+
+             bfd_h_put_32 (abfd, module->module_name_idx, &w.module_name);
+             bfd_h_put_32 (abfd, module->iextdefsym, &w.iextdefsym);
+             bfd_h_put_32 (abfd, module->nextdefsym, &w.nextdefsym);
+             bfd_h_put_32 (abfd, module->irefsym, &w.irefsym);
+             bfd_h_put_32 (abfd, module->nrefsym, &w.nrefsym);
+             bfd_h_put_32 (abfd, module->ilocalsym, &w.ilocalsym);
+             bfd_h_put_32 (abfd, module->nlocalsym, &w.nlocalsym);
+             bfd_h_put_32 (abfd, module->iextrel, &w.iextrel);
+             bfd_h_put_32 (abfd, module->nextrel, &w.nextrel);
+             bfd_h_put_32 (abfd, iinit, &w.iinit_iterm);
+             bfd_h_put_32 (abfd, ninit, &w.ninit_nterm);
+             bfd_h_put_64 (abfd, module->objc_module_info_addr,
+                           &w.objc_module_info_addr);
+             bfd_h_put_32 (abfd, module->objc_module_info_size,
+                           &w.objc_module_info_size);
+
+             if (bfd_bwrite ((void *) &w, sizeof (w), abfd) != sizeof (w))
+               return FALSE;
+           }
+         else
+           {
+             struct mach_o_dylib_module_external n;
+
+             bfd_h_put_32 (abfd, module->module_name_idx, &n.module_name);
+             bfd_h_put_32 (abfd, module->iextdefsym, &n.iextdefsym);
+             bfd_h_put_32 (abfd, module->nextdefsym, &n.nextdefsym);
+             bfd_h_put_32 (abfd, module->irefsym, &n.irefsym);
+             bfd_h_put_32 (abfd, module->nrefsym, &n.nrefsym);
+             bfd_h_put_32 (abfd, module->ilocalsym, &n.ilocalsym);
+             bfd_h_put_32 (abfd, module->nlocalsym, &n.nlocalsym);
+             bfd_h_put_32 (abfd, module->iextrel, &n.iextrel);
+             bfd_h_put_32 (abfd, module->nextrel, &n.nextrel);
+             bfd_h_put_32 (abfd, iinit, &n.iinit_iterm);
+             bfd_h_put_32 (abfd, ninit, &n.ninit_nterm);
+             bfd_h_put_32 (abfd, module->objc_module_info_addr,
+                           &n.objc_module_info_addr);
+             bfd_h_put_32 (abfd, module->objc_module_info_size,
+                           &n.objc_module_info_size);
+
+             if (bfd_bwrite ((void *) &n, sizeof (n), abfd) != sizeof (n))
+               return FALSE;
+           }
+       }
+    }
+
+  if (cmd->ntoc != 0)
+    {
+      unsigned int i;
+
+      if (bfd_seek (abfd, cmd->tocoff, SEEK_SET) != 0)
+       return FALSE;
+
+      for (i = 0; i < cmd->ntoc; i++)
+       {
+         struct mach_o_dylib_table_of_contents_external raw;
+         bfd_mach_o_dylib_table_of_content *toc = &cmd->dylib_toc[i];
+
+         bfd_h_put_32 (abfd, toc->symbol_index, &raw.symbol_index);
+         bfd_h_put_32 (abfd, toc->module_index, &raw.module_index);
+
+         if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
+           return FALSE;
+       }
+    }
+  
+  if (cmd->nindirectsyms > 0)
+    {
+      unsigned int i;
+
+      if (bfd_seek (abfd, cmd->indirectsymoff, SEEK_SET) != 0)
+       return FALSE;
+
+      for (i = 0; i < cmd->nindirectsyms; ++i)
+       {
+         unsigned char raw[4];
+
+         bfd_h_put_32 (abfd, cmd->indirect_syms[i], &raw);
+         if (bfd_bwrite (raw, sizeof (raw), abfd) != sizeof (raw))
+           return FALSE;
+       }    
+    }
+
+  if (cmd->nextrefsyms != 0)
+    {
+      unsigned int i;
+
+      if (bfd_seek (abfd, cmd->extrefsymoff, SEEK_SET) != 0)
+       return FALSE;
+
+      for (i = 0; i < cmd->nextrefsyms; i++)
+       {
+         unsigned long v;
+         unsigned char raw[4];
+         bfd_mach_o_dylib_reference *ref = &cmd->ext_refs[i];
+
+         /* Fields isym and flags are written as bit-fields, thus we need
+            a specific processing for endianness.  */
+
+         if (bfd_big_endian (abfd))
+           {
+             v = ((ref->isym & 0xffffff) << 8);
+             v |= ref->flags & 0xff;
+           }
+         else
+           {
+             v = ref->isym  & 0xffffff;
+             v |= ((ref->flags & 0xff) << 24);
+           }
+
+         bfd_h_put_32 (abfd, v, raw);
+         if (bfd_bwrite (raw, sizeof (raw), abfd) != sizeof (raw))
+           return FALSE;
+       }
+    }
+
+  /* The command.  */
+  if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0)
+    return FALSE;
+  else
+    {
+      struct mach_o_dysymtab_command_external raw;
+
+      bfd_h_put_32 (abfd, cmd->ilocalsym, &raw.ilocalsym);
+      bfd_h_put_32 (abfd, cmd->nlocalsym, &raw.nlocalsym);
+      bfd_h_put_32 (abfd, cmd->iextdefsym, &raw.iextdefsym);
+      bfd_h_put_32 (abfd, cmd->nextdefsym, &raw.nextdefsym);
+      bfd_h_put_32 (abfd, cmd->iundefsym, &raw.iundefsym);
+      bfd_h_put_32 (abfd, cmd->nundefsym, &raw.nundefsym);
+      bfd_h_put_32 (abfd, cmd->tocoff, &raw.tocoff);
+      bfd_h_put_32 (abfd, cmd->ntoc, &raw.ntoc);
+      bfd_h_put_32 (abfd, cmd->modtaboff, &raw.modtaboff);
+      bfd_h_put_32 (abfd, cmd->nmodtab, &raw.nmodtab);
+      bfd_h_put_32 (abfd, cmd->extrefsymoff, &raw.extrefsymoff);
+      bfd_h_put_32 (abfd, cmd->nextrefsyms, &raw.nextrefsyms);
+      bfd_h_put_32 (abfd, cmd->indirectsymoff, &raw.indirectsymoff);
+      bfd_h_put_32 (abfd, cmd->nindirectsyms, &raw.nindirectsyms);
+      bfd_h_put_32 (abfd, cmd->extreloff, &raw.extreloff);
+      bfd_h_put_32 (abfd, cmd->nextrel, &raw.nextrel);
+      bfd_h_put_32 (abfd, cmd->locreloff, &raw.locreloff);
+      bfd_h_put_32 (abfd, cmd->nlocrel, &raw.nlocrel);
+
+      if (bfd_bwrite (&raw, sizeof (raw), abfd) != sizeof (raw))
+       return FALSE;
+    }
+
+  return TRUE;
+}
+
+static unsigned
+bfd_mach_o_primary_symbol_sort_key (bfd_mach_o_asymbol *s)
+{
+  unsigned mtyp = s->n_type & BFD_MACH_O_N_TYPE;
+
+  /* Just leave debug symbols where they are (pretend they are local, and
+     then they will just be sorted on position).  */
+  if (s->n_type & BFD_MACH_O_N_STAB)
+    return 0;
+
+  /* Local (we should never see an undefined local AFAICT).  */
+  if (! (s->n_type & (BFD_MACH_O_N_EXT | BFD_MACH_O_N_PEXT)))
+    return 0;
+
+  /* Common symbols look like undefined externs.  */
+  if (mtyp == BFD_MACH_O_N_UNDF)
+    return 2;
+
+  /* A defined non-local, non-debug symbol.  */
+  return 1;
+}
+
+static int
+bfd_mach_o_cf_symbols (const void *a, const void *b)
+{
+  bfd_mach_o_asymbol *sa = *(bfd_mach_o_asymbol **) a;
+  bfd_mach_o_asymbol *sb = *(bfd_mach_o_asymbol **) b;
+  unsigned int soa, sob;
+
+  soa = bfd_mach_o_primary_symbol_sort_key (sa);
+  sob = bfd_mach_o_primary_symbol_sort_key (sb);
+  if (soa < sob)
+    return -1;
+
+  if (soa > sob)
+    return 1;
+
+  /* If it's local or stab, just preserve the input order.  */
+  if (soa == 0)
+    {
+      if (sa->symbol.udata.i < sb->symbol.udata.i)
+        return -1;
+      if (sa->symbol.udata.i > sb->symbol.udata.i)
+        return  1;
+
+      /* This is probably an error.  */
+      return 0;
+    }
+
+  /* The second sort key is name.  */
+  return strcmp (sa->symbol.name, sb->symbol.name);
+}
+
+/* Process the symbols.
+
+   This should be OK for single-module files - but it is not likely to work
+   for multi-module shared libraries.
+
+   (a) If the application has not filled in the relevant mach-o fields, make
+       an estimate.
+
+   (b) Order them, like this:
+       (  i) local.
+               (unsorted)
+       ( ii) external defined
+               (by name)
+       (iii) external undefined/common
+               (by name)
+       ( iv) common
+               (by name)
+*/
 
 static bfd_boolean
 bfd_mach_o_mangle_symbols (bfd *abfd)
 
 static bfd_boolean
 bfd_mach_o_mangle_symbols (bfd *abfd)
@@ -1402,15 +1814,22 @@ bfd_mach_o_mangle_symbols (bfd *abfd)
   unsigned long i;
   asymbol **symbols = bfd_get_outsymbols (abfd);
 
   unsigned long i;
   asymbol **symbols = bfd_get_outsymbols (abfd);
 
+  if (symbols == NULL || bfd_get_symcount (abfd) == 0)
+    return TRUE;
+
   for (i = 0; i < bfd_get_symcount (abfd); i++)
     {
       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
 
   for (i = 0; i < bfd_get_symcount (abfd); i++)
     {
       bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
 
-      if (s->n_type == BFD_MACH_O_N_UNDF && !(s->symbol.flags & BSF_DEBUGGING))
+      /* We use this value, which is out-of-range as a symbol index, to signal
+        that the mach-o-specific data are not filled in and need to be created
+        from the bfd values.  It is much preferable for the application to do
+        this, since more meaningful diagnostics can be made that way.  */
+
+      if (s->symbol.udata.i == SYM_MACHO_FIELDS_UNSET)
         {
         {
-          /* As genuine Mach-O symbols type shouldn't be N_UNDF (undefined
-             symbols should be N_UNDEF | N_EXT), we suppose the back-end
-             values haven't been set.  */
+          /* No symbol information has been set - therefore determine
+             it from the bfd symbol flags/info.  */
           if (s->symbol.section == bfd_abs_section_ptr)
             s->n_type = BFD_MACH_O_N_ABS;
           else if (s->symbol.section == bfd_und_section_ptr)
           if (s->symbol.section == bfd_abs_section_ptr)
             s->n_type = BFD_MACH_O_N_ABS;
           else if (s->symbol.section == bfd_und_section_ptr)
@@ -1418,9 +1837,15 @@ bfd_mach_o_mangle_symbols (bfd *abfd)
               s->n_type = BFD_MACH_O_N_UNDF;
               if (s->symbol.flags & BSF_WEAK)
                 s->n_desc |= BFD_MACH_O_N_WEAK_REF;
               s->n_type = BFD_MACH_O_N_UNDF;
               if (s->symbol.flags & BSF_WEAK)
                 s->n_desc |= BFD_MACH_O_N_WEAK_REF;
+              /* mach-o automatically makes undefined symbols extern.  */
+             s->n_type |= BFD_MACH_O_N_EXT;
+             s->symbol.flags |= BSF_GLOBAL;
             }
           else if (s->symbol.section == bfd_com_section_ptr)
             }
           else if (s->symbol.section == bfd_com_section_ptr)
-            s->n_type = BFD_MACH_O_N_UNDF | BFD_MACH_O_N_EXT;
+           {
+              s->n_type = BFD_MACH_O_N_UNDF | BFD_MACH_O_N_EXT;
+              s->symbol.flags |= BSF_GLOBAL;
+            }
           else
             s->n_type = BFD_MACH_O_N_SECT;
           
           else
             s->n_type = BFD_MACH_O_N_SECT;
           
@@ -1428,15 +1853,82 @@ bfd_mach_o_mangle_symbols (bfd *abfd)
             s->n_type |= BFD_MACH_O_N_EXT;
         }
 
             s->n_type |= BFD_MACH_O_N_EXT;
         }
 
-      /* Compute section index.  */
-      if (s->symbol.section != bfd_abs_section_ptr
+      /* Put the section index in, where required.  */
+      if ((s->symbol.section != bfd_abs_section_ptr
           && s->symbol.section != bfd_und_section_ptr
           && s->symbol.section != bfd_com_section_ptr)
           && s->symbol.section != bfd_und_section_ptr
           && s->symbol.section != bfd_com_section_ptr)
-        s->n_sect = s->symbol.section->target_index;
+          || ((s->n_type & BFD_MACH_O_N_STAB) != 0
+               && s->symbol.name == NULL))
+       s->n_sect = s->symbol.section->target_index;
 
 
-      /* Number symbols.  */
+      /* Number to preserve order for local and debug syms.  */
       s->symbol.udata.i = i;
     }
       s->symbol.udata.i = i;
     }
+
+  /* Sort the symbols.  */
+  qsort ((void *) symbols, (size_t) bfd_get_symcount (abfd),
+        sizeof (asymbol *), bfd_mach_o_cf_symbols);
+
+  for (i = 0; i < bfd_get_symcount (abfd); ++i)
+    {
+      bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
+      s->symbol.udata.i = i;  /* renumber.  */
+    }
+
+  return TRUE;
+}
+
+/* We build a flat table of sections, which can be re-ordered if necessary.
+   Fill in the section number and other mach-o-specific data.  */
+
+static bfd_boolean
+bfd_mach_o_mangle_sections (bfd *abfd, bfd_mach_o_data_struct *mdata)
+{
+  asection *sec;
+  unsigned target_index;
+  unsigned nsect;
+
+  nsect = bfd_count_sections (abfd);
+  
+  /* Don't do it if it's already set - assume the application knows what it's
+     doing.  */
+  if (mdata->nsects == nsect
+      && (mdata->nsects == 0 || mdata->sections != NULL))
+    return TRUE;
+
+  mdata->nsects = nsect;
+  mdata->sections = bfd_alloc (abfd, 
+                              mdata->nsects * sizeof (bfd_mach_o_section *));
+  if (mdata->sections == NULL)
+    return FALSE;
+
+  /* We need to check that this can be done...  */
+  if (nsect > 255)
+    (*_bfd_error_handler) (_("mach-o: there are too many sections (%d)"
+                            " maximum is 255,\n"), nsect);
+
+  /* Create Mach-O sections.
+     Section type, attribute and align should have been set when the 
+     section was created - either read in or specified.  */
+  target_index = 0;
+  for (sec = abfd->sections; sec; sec = sec->next)
+    {
+      unsigned bfd_align = bfd_get_section_alignment (abfd, sec);
+      bfd_mach_o_section *msect = bfd_mach_o_get_mach_o_section (sec);
+
+      mdata->sections[target_index] = msect;
+
+      msect->addr = bfd_get_section_vma (abfd, sec);
+      msect->size = bfd_get_section_size (sec);
+
+      /* Use the largest alignment set, in case it was bumped after the 
+        section was created.  */
+      msect->align = msect->align > bfd_align ? msect->align : bfd_align;
+
+      msect->offset = 0;
+      sec->target_index = ++target_index;
+    }
+
   return TRUE;
 }
 
   return TRUE;
 }
 
@@ -1446,27 +1938,14 @@ bfd_mach_o_write_contents (bfd *abfd)
   unsigned int i;
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
 
   unsigned int i;
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
 
+  /* Make the commands, if not already present.  */
   if (mdata->header.ncmds == 0)
     if (!bfd_mach_o_build_commands (abfd))
       return FALSE;
 
   if (mdata->header.ncmds == 0)
     if (!bfd_mach_o_build_commands (abfd))
       return FALSE;
 
-  /* Now write header information.  */
-  if (mdata->header.filetype == 0)
-    {
-      if (abfd->flags & EXEC_P)
-        mdata->header.filetype = BFD_MACH_O_MH_EXECUTE;
-      else if (abfd->flags & DYNAMIC)
-        mdata->header.filetype = BFD_MACH_O_MH_DYLIB;
-      else
-        mdata->header.filetype = BFD_MACH_O_MH_OBJECT;
-    }
   if (!bfd_mach_o_write_header (abfd, &mdata->header))
     return FALSE;
 
   if (!bfd_mach_o_write_header (abfd, &mdata->header))
     return FALSE;
 
-  /* Assign a number to each symbols.  */
-  if (!bfd_mach_o_mangle_symbols (abfd))
-    return FALSE;
-
   for (i = 0; i < mdata->header.ncmds; i++)
     {
       struct mach_o_load_command_external raw;
   for (i = 0; i < mdata->header.ncmds; i++)
     {
       struct mach_o_load_command_external raw;
@@ -1496,6 +1975,10 @@ bfd_mach_o_write_contents (bfd *abfd)
          if (!bfd_mach_o_write_symtab (abfd, cur))
            return FALSE;
          break;
          if (!bfd_mach_o_write_symtab (abfd, cur))
            return FALSE;
          break;
+       case BFD_MACH_O_LC_DYSYMTAB:
+         if (!bfd_mach_o_write_dysymtab (abfd, cur))
+           return FALSE;
+         break;
        case BFD_MACH_O_LC_SYMSEG:
          break;
        case BFD_MACH_O_LC_THREAD:
        case BFD_MACH_O_LC_SYMSEG:
          break;
        case BFD_MACH_O_LC_THREAD:
@@ -1508,7 +1991,6 @@ bfd_mach_o_write_contents (bfd *abfd)
        case BFD_MACH_O_LC_IDENT:
        case BFD_MACH_O_LC_FVMFILE:
        case BFD_MACH_O_LC_PREPAGE:
        case BFD_MACH_O_LC_IDENT:
        case BFD_MACH_O_LC_FVMFILE:
        case BFD_MACH_O_LC_PREPAGE:
-       case BFD_MACH_O_LC_DYSYMTAB:
        case BFD_MACH_O_LC_LOAD_DYLIB:
        case BFD_MACH_O_LC_LOAD_WEAK_DYLIB:
        case BFD_MACH_O_LC_ID_DYLIB:
        case BFD_MACH_O_LC_LOAD_DYLIB:
        case BFD_MACH_O_LC_LOAD_WEAK_DYLIB:
        case BFD_MACH_O_LC_ID_DYLIB:
@@ -1564,110 +2046,493 @@ bfd_mach_o_set_section_flags_from_bfd (bfd *abfd ATTRIBUTE_UNUSED, asection *sec
     s->flags = BFD_MACH_O_S_REGULAR;
 }
 
     s->flags = BFD_MACH_O_S_REGULAR;
 }
 
-/* Build Mach-O load commands from the sections.  */
+/* Count the number of sections in the list for the segment named.
+
+   The special case of NULL or "" for the segment name is valid for
+   an MH_OBJECT file and means 'all sections available'.  
+   
+   Requires that the sections table in mdata be filled in.  
+
+   Returns the number of sections (0 is valid).
+   Any number > 255 signals an invalid section count, although we will,
+   perhaps, allow the file to be written (in line with Darwin tools up
+   to XCode 4). 
+   
+   A section count of (unsigned long) -1 signals a definite error.  */
+
+static unsigned long
+bfd_mach_o_count_sections_for_seg (const char *segment,
+                                  bfd_mach_o_data_struct *mdata)
+{
+  unsigned i,j;
+  if (mdata == NULL || mdata->sections == NULL)
+    return (unsigned long) -1;
+
+  /* The MH_OBJECT case, all sections are considered; Although nsects is
+     is an unsigned long, the maximum valid section count is 255 and this
+     will have been checked already by mangle_sections.  */
+  if (segment == NULL || segment[0] == '\0')
+    return mdata->nsects;
+
+  /* Count the number of sections we see in this segment.  */
+  j = 0;
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *s = mdata->sections[i];
+      if (strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) == 0)
+        j++;
+    }
+  return j;
+}
+
+static bfd_boolean
+bfd_mach_o_build_seg_command (const char *segment,
+                             bfd_mach_o_data_struct *mdata,
+                             bfd_mach_o_segment_command *seg)
+{
+  unsigned i;
+  int is_mho = (segment == NULL || segment[0] == '\0');
+
+  /* Fill segment command.  */
+  if (is_mho)
+    memset (seg->segname, 0, sizeof (seg->segname));
+  else
+    strncpy (seg->segname, segment, sizeof (seg->segname));
+
+  /* TODO: fix this up for non-MH_OBJECT cases.  */
+  seg->vmaddr = 0;
+  seg->vmsize = 0;
+
+  seg->fileoff = mdata->filelen;
+  seg->filesize = 0;
+  seg->maxprot = BFD_MACH_O_PROT_READ | BFD_MACH_O_PROT_WRITE
+                | BFD_MACH_O_PROT_EXECUTE;
+  seg->initprot = seg->maxprot;
+  seg->flags = 0;
+  seg->sect_head = NULL;
+  seg->sect_tail = NULL;
+
+  /*  Append sections to the segment.  
+
+      This is a little tedious, we have to honor the need to account zerofill
+      sections after all the rest.  This forces us to do the calculation of
+      total vmsize in three passes so that any alignment increments are 
+      properly accounted.  */
+
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *s = mdata->sections[i];
+      asection *sec = s->bfdsection;
+
+      /* If we're not making an MH_OBJECT, check whether this section is from
+        our segment, and skip if not.  Otherwise, just add all sections.  */
+      if (! is_mho 
+         && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
+       continue;
+
+      /* Although we account for zerofill section sizes in vm order, they are
+        placed in the file in source sequence.  */
+      bfd_mach_o_append_section_to_segment (seg, sec);
+      s->offset = 0;
+      
+      /* Zerofill sections have zero file size & offset, 
+        and are not written.  */
+      if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) == BFD_MACH_O_S_ZEROFILL
+          || (s->flags & BFD_MACH_O_SECTION_TYPE_MASK) 
+             == BFD_MACH_O_S_GB_ZEROFILL)
+        continue;
+
+      if (s->size > 0)
+       {
+         seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
+         seg->vmsize += s->size;
+
+         seg->filesize = FILE_ALIGN (seg->filesize, s->align);
+         seg->filesize += s->size;
+
+          mdata->filelen = FILE_ALIGN (mdata->filelen, s->align);
+          s->offset = mdata->filelen;
+        }
+
+      sec->filepos = s->offset;
+      mdata->filelen += s->size;
+    }
+
+  /* Now pass through again, for zerofill, only now we just update the vmsize.  */
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *s = mdata->sections[i];
+
+      if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) != BFD_MACH_O_S_ZEROFILL)
+        continue;
+
+      if (! is_mho 
+         && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
+       continue;
+
+      if (s->size > 0)
+       {
+         seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
+         seg->vmsize += s->size;
+       }
+    }
+
+  /* Now pass through again, for zerofill_GB.  */
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *s = mdata->sections[i];
+      if ((s->flags & BFD_MACH_O_SECTION_TYPE_MASK) != BFD_MACH_O_S_GB_ZEROFILL)
+        continue;
+
+      if (! is_mho 
+         && strncmp (segment, s->segname, BFD_MACH_O_SEGNAME_SIZE) != 0)
+       continue;
+
+      if (s->size > 0)
+       {
+         seg->vmsize = FILE_ALIGN (seg->vmsize, s->align);
+         seg->vmsize += s->size;
+       }
+    }
+
+  /* Allocate space for the relocations.  */
+  mdata->filelen = FILE_ALIGN(mdata->filelen, 2);
+
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *ms = mdata->sections[i];
+      asection *sec = ms->bfdsection;
+        
+      if ((ms->nreloc = sec->reloc_count) == 0)
+        {
+         ms->reloff = 0;
+         continue;
+        }
+      sec->rel_filepos = mdata->filelen;
+      ms->reloff = sec->rel_filepos;
+      mdata->filelen += sec->reloc_count * BFD_MACH_O_RELENT_SIZE;
+    }
+
+  return TRUE;
+}
+
+/* Count the number of indirect symbols in the image.
+   Requires that the sections are in their final order.  */
+
+static unsigned int
+bfd_mach_o_count_indirect_symbols (bfd *abfd, bfd_mach_o_data_struct *mdata)
+{
+  unsigned int i;
+  unsigned int nisyms = 0;
+
+  for (i = 0; i < mdata->nsects; ++i)
+    {
+      bfd_mach_o_section *sec = mdata->sections[i];
+
+      switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
+       {
+         case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
+         case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
+         case BFD_MACH_O_S_SYMBOL_STUBS:
+           nisyms += bfd_mach_o_section_get_nbr_indirect (abfd, sec);
+           break;
+         default:
+           break;
+       }
+    }
+  return nisyms;
+}
+
+static bfd_boolean
+bfd_mach_o_build_dysymtab_command (bfd *abfd,
+                                  bfd_mach_o_data_struct *mdata,
+                                  bfd_mach_o_load_command *cmd)
+{
+  bfd_mach_o_dysymtab_command *dsym = &cmd->command.dysymtab;
+
+  /* TODO:
+     We are not going to try and fill these in yet and, moreover, we are
+     going to bail if they are already set.  */
+  if (dsym->nmodtab != 0
+      || dsym->ntoc != 0
+      || dsym->nextrefsyms != 0)
+    {
+      (*_bfd_error_handler) (_("sorry: modtab, toc and extrefsyms are not yet"
+                               " implemented for dysymtab commands."));
+      return FALSE;
+    }
+
+  dsym->ilocalsym = 0;
+
+  if (bfd_get_symcount (abfd) > 0)
+    {
+      asymbol **symbols = bfd_get_outsymbols (abfd);
+      unsigned long i;
+
+       /* Count the number of each kind of symbol.  */
+      for (i = 0; i < bfd_get_symcount (abfd); ++i)
+       {
+         bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
+         if (s->n_type & (BFD_MACH_O_N_EXT | BFD_MACH_O_N_PEXT))
+           break;
+       }
+      dsym->nlocalsym = i;
+      dsym->iextdefsym = i;
+      for (; i < bfd_get_symcount (abfd); ++i)
+       {
+         bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *)symbols[i];
+         if ((s->n_type & BFD_MACH_O_N_TYPE) == BFD_MACH_O_N_UNDF)
+           break;
+       }
+      dsym->nextdefsym = i - dsym->nlocalsym;
+      dsym->iundefsym = dsym->nextdefsym + dsym->iextdefsym;
+      dsym->nundefsym = bfd_get_symcount (abfd) 
+                       - dsym->nlocalsym 
+                       - dsym->nextdefsym;
+    }
+  else
+    {
+      dsym->nlocalsym = 0;
+      dsym->iextdefsym = 0;
+      dsym->nextdefsym = 0;
+      dsym->iundefsym = 0;
+      dsym->nundefsym = 0;
+    }
+
+  dsym->nindirectsyms = bfd_mach_o_count_indirect_symbols (abfd, mdata);
+  if (dsym->nindirectsyms > 0)
+    {
+      unsigned i;
+      unsigned n;
+
+      mdata->filelen = FILE_ALIGN (mdata->filelen, 2);
+      dsym->indirectsymoff = mdata->filelen;
+      mdata->filelen += dsym->nindirectsyms * 4;
+      
+      dsym->indirect_syms = bfd_zalloc (abfd, dsym->nindirectsyms * 4);
+      if (dsym->indirect_syms == NULL)
+        return FALSE;
+                 
+      n = 0;
+      for (i = 0; i < mdata->nsects; ++i)
+       {
+         bfd_mach_o_section *sec = mdata->sections[i];
+
+         switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
+           {
+             case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
+             case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
+             case BFD_MACH_O_S_SYMBOL_STUBS:
+               {
+                 unsigned j, num;
+                 bfd_mach_o_asymbol **isyms = sec->indirect_syms;
+                 
+                 num = bfd_mach_o_section_get_nbr_indirect (abfd, sec);
+                 if (isyms == NULL || num == 0)
+                   break;
+                 /* Record the starting index in the reserved1 field.  */
+                 sec->reserved1 = n;
+                 for (j = 0; j < num; j++, n++)
+                   {
+                     if (isyms[j] == NULL)
+                       dsym->indirect_syms[n] = BFD_MACH_O_INDIRECT_SYM_LOCAL;
+                     else if (isyms[j]->symbol.section == bfd_abs_section_ptr
+                              && ! (isyms[j]->n_type & BFD_MACH_O_N_EXT))
+                       dsym->indirect_syms[n] = BFD_MACH_O_INDIRECT_SYM_LOCAL
+                                                | BFD_MACH_O_INDIRECT_SYM_ABS;
+                     else
+                       dsym->indirect_syms[n] = isyms[j]->symbol.udata.i;
+                   }
+               }
+               break;
+             default:
+               break;
+           }
+       }
+    }
+
+  return TRUE;
+}
+
+/* Build Mach-O load commands (currently assuming an MH_OBJECT file).
+   TODO: Other file formats, rebuilding symtab/dysymtab commands for strip
+   and copy functionality.  */
 
 bfd_boolean
 bfd_mach_o_build_commands (bfd *abfd)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
 
 bfd_boolean
 bfd_mach_o_build_commands (bfd *abfd)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
-  unsigned int wide = mach_o_wide_p (&mdata->header);
-  bfd_mach_o_segment_command *seg;
-  asection *sec;
-  bfd_mach_o_load_command *cmd;
-  bfd_mach_o_load_command *symtab_cmd;
-  int target_index;
+  unsigned wide = mach_o_wide_p (&mdata->header);
+  int segcmd_idx = -1;
+  int symtab_idx = -1;
+  int dysymtab_idx = -1;
+  unsigned long base_offset = 0;
 
 
-  /* Return now if commands are already built.  */
+  /* Return now if commands are already present.  */
   if (mdata->header.ncmds)
     return FALSE;
 
   if (mdata->header.ncmds)
     return FALSE;
 
-  /* Very simple version: a command (segment) to contain all the sections and
-     a command for the symbol table.  */
-  mdata->header.ncmds = 2;
-  mdata->commands = bfd_alloc (abfd, mdata->header.ncmds
-                               * sizeof (bfd_mach_o_load_command));
-  if (mdata->commands == NULL)
+  /* Fill in the file type, if not already set.  */
+
+  if (mdata->header.filetype == 0)
+    {
+      if (abfd->flags & EXEC_P)
+        mdata->header.filetype = BFD_MACH_O_MH_EXECUTE;
+      else if (abfd->flags & DYNAMIC)
+        mdata->header.filetype = BFD_MACH_O_MH_DYLIB;
+      else
+        mdata->header.filetype = BFD_MACH_O_MH_OBJECT;
+    }
+
+  /* If hasn't already been done, flatten sections list, and sort
+     if/when required.  Must be done before the symbol table is adjusted,
+     since that depends on properly numbered sections.  */
+  if (mdata->nsects == 0 || mdata->sections == NULL)
+    if (! bfd_mach_o_mangle_sections (abfd, mdata))
+      return FALSE;
+
+  /* Order the symbol table, fill-in/check mach-o specific fields and
+     partition out any indirect symbols.  */
+  if (!bfd_mach_o_mangle_symbols (abfd))
     return FALSE;
     return FALSE;
-  cmd = &mdata->commands[0];
-  seg = &cmd->command.segment;
 
 
-  seg->nsects = bfd_count_sections (abfd);
+  /* Very simple command set (only really applicable to MH_OBJECTs):
+     All the commands are optional - present only when there is suitable data.
+     (i.e. it is valid to have an empty file)
 
 
-  /* Set segment command.  */
-  if (wide)
+       a command (segment) to contain all the sections,
+       command for the symbol table,
+       a command for the dysymtab.  
+
+     ??? maybe we should assert that this is an MH_OBJECT?  */
+
+  if (mdata->nsects > 0)
     {
     {
-      cmd->type = BFD_MACH_O_LC_SEGMENT_64;
-      cmd->offset = BFD_MACH_O_HEADER_64_SIZE;
-      cmd->len = BFD_MACH_O_LC_SEGMENT_64_SIZE
-        + BFD_MACH_O_SECTION_64_SIZE * seg->nsects;
+      segcmd_idx = 0;
+      mdata->header.ncmds = 1;
     }
     }
-  else
+
+  if (bfd_get_symcount (abfd) > 0)
     {
     {
-      cmd->type = BFD_MACH_O_LC_SEGMENT;
-      cmd->offset = BFD_MACH_O_HEADER_SIZE;
-      cmd->len = BFD_MACH_O_LC_SEGMENT_SIZE
-        + BFD_MACH_O_SECTION_SIZE * seg->nsects;
+      mdata->header.ncmds++;
+      symtab_idx = segcmd_idx + 1; /* 0 if the seg command is absent.  */
     }
     }
-  cmd->type_required = FALSE;
-  mdata->header.sizeofcmds = cmd->len;
-  mdata->filelen = cmd->offset + cmd->len;
 
 
-  /* Set symtab command.  */
-  symtab_cmd = &mdata->commands[1];
-  
-  symtab_cmd->type = BFD_MACH_O_LC_SYMTAB;
-  symtab_cmd->offset = cmd->offset + cmd->len;
-  symtab_cmd->len = 6 * 4;
-  symtab_cmd->type_required = FALSE;
-  
-  mdata->header.sizeofcmds += symtab_cmd->len;
-  mdata->filelen += symtab_cmd->len;
+  /* FIXME:
+     This is a rather crude test for whether we should build a dysymtab.  */
+  if (bfd_mach_o_should_emit_dysymtab ()
+      && bfd_get_symcount (abfd))
+    {
+      mdata->header.ncmds++;
+      /* If there should be a case where a dysymtab could be emitted without
+        a symtab (seems improbable), this would need amending.  */
+      dysymtab_idx = symtab_idx + 1;
+    }
 
 
-  /* Fill segment command.  */
-  memset (seg->segname, 0, sizeof (seg->segname));
-  seg->vmaddr = 0;
-  seg->fileoff = mdata->filelen;
-  seg->filesize = 0;
-  seg->maxprot = BFD_MACH_O_PROT_READ | BFD_MACH_O_PROT_WRITE
-    | BFD_MACH_O_PROT_EXECUTE;
-  seg->initprot = seg->maxprot;
-  seg->flags = 0;
-  seg->sect_head = NULL;
-  seg->sect_tail = NULL;
+  if (wide)
+    base_offset = BFD_MACH_O_HEADER_64_SIZE;
+  else
+    base_offset = BFD_MACH_O_HEADER_SIZE;
 
 
-  /* Create Mach-O sections.
-     Section type, attribute and align should have been set when the 
-     section was created - either read in or specified.  */
-  target_index = 0;
-  for (sec = abfd->sections; sec; sec = sec->next)
-    {
-      unsigned bfd_align = bfd_get_section_alignment (abfd, sec);
-      bfd_mach_o_section *msect = bfd_mach_o_get_mach_o_section (sec);
+  /* Well, we must have a header, at least.  */
+  mdata->filelen = base_offset;
 
 
-      bfd_mach_o_append_section_to_segment (seg, sec);
+  /* A bit unusual, but no content is valid;
+     as -n empty.s -o empty.o  */
+  if (mdata->header.ncmds == 0)
+    return TRUE;
 
 
-      msect->addr = bfd_get_section_vma (abfd, sec);
-      msect->size = bfd_get_section_size (sec);
-      /* Use the largest alignment set, in case it was bumped after the 
-        section was created.  */
-      msect->align = msect->align > bfd_align ? msect->align : bfd_align;
+  mdata->commands = bfd_zalloc (abfd, mdata->header.ncmds
+                                * sizeof (bfd_mach_o_load_command));
+  if (mdata->commands == NULL)
+    return FALSE;
 
 
-      if (msect->size != 0)
-        {
-          mdata->filelen = FILE_ALIGN (mdata->filelen, msect->align);
-          msect->offset = mdata->filelen;
-        }
+  if (segcmd_idx >= 0)
+    {  
+      bfd_mach_o_load_command *cmd = &mdata->commands[segcmd_idx];
+      bfd_mach_o_segment_command *seg = &cmd->command.segment;
+
+      /* Count the segctions in the special blank segment used for MH_OBJECT.  */
+      seg->nsects = bfd_mach_o_count_sections_for_seg (NULL, mdata);
+      if (seg->nsects == (unsigned long) -1)
+       return FALSE;
+
+      /* Init segment command.  */
+      cmd->offset = base_offset;
+      if (wide)
+       {
+         cmd->type = BFD_MACH_O_LC_SEGMENT_64;
+         cmd->len = BFD_MACH_O_LC_SEGMENT_64_SIZE
+                       + BFD_MACH_O_SECTION_64_SIZE * seg->nsects;
+       }
       else
       else
-        msect->offset = 0;
+       {
+         cmd->type = BFD_MACH_O_LC_SEGMENT;
+         cmd->len = BFD_MACH_O_LC_SEGMENT_SIZE
+                       + BFD_MACH_O_SECTION_SIZE * seg->nsects;
+       }
 
 
-      sec->filepos = msect->offset;
-      sec->target_index = ++target_index;
+      cmd->type_required = FALSE;
+      mdata->header.sizeofcmds = cmd->len;
+      mdata->filelen += cmd->len;
+    }
+
+  if (symtab_idx >= 0)
+    {
+      /* Init symtab command.  */
+      bfd_mach_o_load_command *cmd = &mdata->commands[symtab_idx];
+  
+      cmd->type = BFD_MACH_O_LC_SYMTAB;
+      cmd->offset = base_offset;
+      if (segcmd_idx >= 0)
+        cmd->offset += mdata->commands[segcmd_idx].len;
+
+      cmd->len = sizeof (struct mach_o_symtab_command_external)
+                + BFD_MACH_O_LC_SIZE;
+      cmd->type_required = FALSE;
+      mdata->header.sizeofcmds += cmd->len;
+      mdata->filelen += cmd->len;
+    }
+
+  /* If required, setup symtab command, see comment above about the quality
+     of this test.  */
+  if (dysymtab_idx >= 0)
+    {
+      bfd_mach_o_load_command *cmd = &mdata->commands[dysymtab_idx];
+
+      cmd->type = BFD_MACH_O_LC_DYSYMTAB;
+      if (symtab_idx >= 0)
+        cmd->offset = mdata->commands[symtab_idx].offset 
+                   + mdata->commands[symtab_idx].len;
+      else if (segcmd_idx >= 0)
+        cmd->offset = mdata->commands[segcmd_idx].offset 
+                   + mdata->commands[segcmd_idx].len;
+      else
+       cmd->offset = base_offset;
 
 
-      mdata->filelen += msect->size;
+      cmd->type_required = FALSE;
+      cmd->len = sizeof (struct mach_o_dysymtab_command_external)
+                + BFD_MACH_O_LC_SIZE;
+
+      mdata->header.sizeofcmds += cmd->len;
+      mdata->filelen += cmd->len;
     }
     }
-  seg->filesize = mdata->filelen - seg->fileoff;
-  seg->vmsize = seg->filesize;
 
 
+  /* So, now we have sized the commands and the filelen set to that.
+     Now we can build the segment command and set the section file offsets.  */
+  if (segcmd_idx >= 0
+      && ! bfd_mach_o_build_seg_command 
+               (NULL, mdata, &mdata->commands[segcmd_idx].command.segment))
+    return FALSE;
+
+  /* If we're doing a dysymtab, cmd points to its load command.  */
+  if (dysymtab_idx >= 0
+      && ! bfd_mach_o_build_dysymtab_command (abfd, mdata, 
+                                             &mdata->commands[dysymtab_idx]))
+    return FALSE;
+
+  /* The symtab command is filled in when the symtab is written.  */
   return TRUE;
 }
 
   return TRUE;
 }
 
@@ -1682,8 +2547,8 @@ bfd_mach_o_set_section_contents (bfd *abfd,
 {
   file_ptr pos;
 
 {
   file_ptr pos;
 
-  /* This must be done first, because bfd_set_section_contents is
-     going to set output_has_begun to TRUE.  */
+  /* Trying to write the first section contents will trigger the creation of
+     the load commands if they are not already present.  */
   if (! abfd->output_has_begun && ! bfd_mach_o_build_commands (abfd))
     return FALSE;
 
   if (! abfd->output_has_begun && ! bfd_mach_o_build_commands (abfd))
     return FALSE;
 
@@ -1717,7 +2582,7 @@ bfd_mach_o_make_empty_symbol (bfd *abfd)
   if (new_symbol == NULL)
     return new_symbol;
   new_symbol->the_bfd = abfd;
   if (new_symbol == NULL)
     return new_symbol;
   new_symbol->the_bfd = abfd;
-  new_symbol->udata.i = 0;
+  new_symbol->udata.i = SYM_MACHO_FIELDS_UNSET;
   return new_symbol;
 }
 
   return new_symbol;
 }
 
@@ -1784,6 +2649,8 @@ bfd_mach_o_read_header (bfd *abfd, bfd_mach_o_header *header)
 
   if (mach_o_wide_p (header))
     header->reserved = (*get32) (raw.reserved);
 
   if (mach_o_wide_p (header))
     header->reserved = (*get32) (raw.reserved);
+  else
+    header->reserved = 0;
 
   return TRUE;
 }
 
   return TRUE;
 }
@@ -2045,7 +2912,7 @@ bfd_mach_o_read_symtab_symbol (bfd *abfd,
   s->symbol.name = sym->strtab + stroff;
   s->symbol.value = value;
   s->symbol.flags = 0x0;
   s->symbol.name = sym->strtab + stroff;
   s->symbol.value = value;
   s->symbol.flags = 0x0;
-  s->symbol.udata.i = 0;
+  s->symbol.udata.i = i;
   s->n_type = type;
   s->n_sect = section;
   s->n_desc = desc;
   s->n_type = type;
   s->n_sect = section;
   s->n_desc = desc;
@@ -2076,13 +2943,9 @@ bfd_mach_o_read_symtab_symbol (bfd *abfd,
     }
   else
     {
     }
   else
     {
-      if (type & BFD_MACH_O_N_PEXT)
-       s->symbol.flags |= BSF_GLOBAL;
-
-      if (type & BFD_MACH_O_N_EXT)
+      if (type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT))
        s->symbol.flags |= BSF_GLOBAL;
        s->symbol.flags |= BSF_GLOBAL;
-
-      if (!(type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT)))
+      else
        s->symbol.flags |= BSF_LOCAL;
 
       switch (symtype)
        s->symbol.flags |= BSF_LOCAL;
 
       switch (symtype)
@@ -2338,6 +3201,32 @@ bfd_mach_o_read_prebound_dylib (bfd *abfd ATTRIBUTE_UNUSED,
   return 0;
 }
 
   return 0;
 }
 
+static int
+bfd_mach_o_read_fvmlib (bfd *abfd, bfd_mach_o_load_command *command)
+{
+  bfd_mach_o_fvmlib_command *fvm = &command->command.fvmlib;
+  struct mach_o_fvmlib_command_external raw;
+  unsigned int nameoff;
+
+  if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
+      || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
+    return -1;
+
+  nameoff = bfd_h_get_32 (abfd, raw.name);
+  fvm->minor_version = bfd_h_get_32 (abfd, raw.minor_version);
+  fvm->header_addr = bfd_h_get_32 (abfd, raw.header_addr);
+
+  fvm->name_offset = command->offset + nameoff;
+  fvm->name_len = command->len - nameoff;
+  fvm->name_str = bfd_alloc (abfd, fvm->name_len);
+  if (fvm->name_str == NULL)
+    return -1;
+  if (bfd_seek (abfd, fvm->name_offset, SEEK_SET) != 0
+      || bfd_bread (fvm->name_str, fvm->name_len, abfd) != fvm->name_len)
+    return -1;
+  return 0;
+}
+
 static int
 bfd_mach_o_read_thread (bfd *abfd, bfd_mach_o_load_command *command)
 {
 static int
 bfd_mach_o_read_thread (bfd *abfd, bfd_mach_o_load_command *command)
 {
@@ -2751,6 +3640,22 @@ bfd_mach_o_read_version_min (bfd *abfd, bfd_mach_o_load_command *command)
   return TRUE;
 }
 
   return TRUE;
 }
 
+static bfd_boolean
+bfd_mach_o_read_encryption_info (bfd *abfd, bfd_mach_o_load_command *command)
+{
+  bfd_mach_o_encryption_info_command *cmd = &command->command.encryption_info;
+  struct mach_o_encryption_info_command_external raw;
+
+  if (bfd_seek (abfd, command->offset + BFD_MACH_O_LC_SIZE, SEEK_SET) != 0
+      || bfd_bread (&raw, sizeof (raw), abfd) != sizeof (raw))
+    return FALSE;
+
+  cmd->cryptoff = bfd_get_32 (abfd, raw.cryptoff);
+  cmd->cryptsize = bfd_get_32 (abfd, raw.cryptsize);
+  cmd->cryptid = bfd_get_32 (abfd, raw.cryptid);
+  return TRUE;
+}
+
 static int
 bfd_mach_o_read_segment (bfd *abfd,
                          bfd_mach_o_load_command *command,
 static int
 bfd_mach_o_read_segment (bfd *abfd,
                          bfd_mach_o_load_command *command,
@@ -2896,6 +3801,9 @@ bfd_mach_o_read_command (bfd *abfd, bfd_mach_o_load_command *command)
       break;
     case BFD_MACH_O_LC_LOADFVMLIB:
     case BFD_MACH_O_LC_IDFVMLIB:
       break;
     case BFD_MACH_O_LC_LOADFVMLIB:
     case BFD_MACH_O_LC_IDFVMLIB:
+      if (bfd_mach_o_read_fvmlib (abfd, command) != 0)
+       return -1;
+      break;
     case BFD_MACH_O_LC_IDENT:
     case BFD_MACH_O_LC_FVMFILE:
     case BFD_MACH_O_LC_PREPAGE:
     case BFD_MACH_O_LC_IDENT:
     case BFD_MACH_O_LC_FVMFILE:
     case BFD_MACH_O_LC_PREPAGE:
@@ -2927,6 +3835,10 @@ bfd_mach_o_read_command (bfd *abfd, bfd_mach_o_load_command *command)
       if (bfd_mach_o_read_linkedit (abfd, command) != 0)
        return -1;
       break;
       if (bfd_mach_o_read_linkedit (abfd, command) != 0)
        return -1;
       break;
+    case BFD_MACH_O_LC_ENCRYPTION_INFO:
+      if (!bfd_mach_o_read_encryption_info (abfd, command))
+       return -1;
+      break;
     case BFD_MACH_O_LC_DYLD_INFO:
       if (bfd_mach_o_read_dyld_info (abfd, command) != 0)
        return -1;
     case BFD_MACH_O_LC_DYLD_INFO:
       if (bfd_mach_o_read_dyld_info (abfd, command) != 0)
        return -1;
@@ -2937,7 +3849,7 @@ bfd_mach_o_read_command (bfd *abfd, bfd_mach_o_load_command *command)
        return -1;
       break;
     default:
        return -1;
       break;
     default:
-      (*_bfd_error_handler)(_("%B: unable to read unknown load command 0x%lx"),
+      (*_bfd_error_handler)(_("%B: unknown load command 0x%lx"),
          abfd, (unsigned long) command->type);
       break;
     }
          abfd, (unsigned long) command->type);
       break;
     }
@@ -3175,6 +4087,7 @@ bfd_mach_o_mkobject_init (bfd *abfd)
   mdata->commands = NULL;
   mdata->nsects = 0;
   mdata->sections = NULL;
   mdata->commands = NULL;
   mdata->nsects = 0;
   mdata->sections = NULL;
+  mdata->dyn_reloc_cache = NULL;
 
   return TRUE;
 }
 
   return TRUE;
 }
@@ -3233,17 +4146,7 @@ bfd_mach_o_header_p (bfd *abfd,
       if (header.cputype != cputype)
         goto wrong;
     }
       if (header.cputype != cputype)
         goto wrong;
     }
-  else
-    {
-      switch (header.cputype)
-        {
-        case BFD_MACH_O_CPU_TYPE_I386:
-          /* Handled by mach-o-i386 */
-          goto wrong;
-        default:
-          break;
-        }
-    }
+
   if (filetype)
     {
       if (header.filetype != filetype)
   if (filetype)
     {
       if (header.filetype != filetype)
@@ -3362,6 +4265,42 @@ bfd_mach_o_archive_p (bfd *abfd)
   return NULL;
 }
 
   return NULL;
 }
 
+/* Set the filename for a fat binary member ABFD, whose bfd architecture is
+   ARCH_TYPE/ARCH_SUBTYPE and corresponding entry in header is ENTRY.
+   Set arelt_data and origin fields too.  */
+
+static void
+bfd_mach_o_fat_member_init (bfd *abfd,
+                            enum bfd_architecture arch_type,
+                            unsigned long arch_subtype,
+                            mach_o_fat_archentry *entry)
+{
+  struct areltdata *areltdata;
+  /* Create the member filename. Use ARCH_NAME.  */
+  const bfd_arch_info_type *ap = bfd_lookup_arch (arch_type, arch_subtype);
+
+  if (ap)
+    {
+      /* Use the architecture name if known.  */
+      abfd->filename = ap->printable_name;
+    }
+  else
+    {
+      /* Forge a uniq id.  */
+      const size_t namelen = 2 + 8 + 1 + 2 + 8 + 1;
+      char *name = bfd_alloc (abfd, namelen);
+      snprintf (name, namelen, "0x%lx-0x%lx",
+                entry->cputype, entry->cpusubtype);
+      abfd->filename = name;
+    }
+
+  areltdata = bfd_zalloc (abfd, sizeof (struct areltdata));
+  areltdata->parsed_size = entry->size;
+  abfd->arelt_data = areltdata;
+  abfd->iostream = NULL;
+  abfd->origin = entry->offset;
+}
+
 bfd *
 bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
 {
 bfd *
 bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
 {
@@ -3377,9 +4316,13 @@ bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
 
   /* Find index of previous entry.  */
   if (prev == NULL)
 
   /* Find index of previous entry.  */
   if (prev == NULL)
-    i = 0;     /* Start at first one.  */
+    {
+      /* Start at first one.  */
+      i = 0;
+    }
   else
     {
   else
     {
+      /* Find index of PREV.  */
       for (i = 0; i < adata->nfat_arch; i++)
        {
          if (adata->archentries[i].offset == prev->origin)
       for (i = 0; i < adata->nfat_arch; i++)
        {
          if (adata->archentries[i].offset == prev->origin)
@@ -3392,8 +4335,10 @@ bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
          bfd_set_error (bfd_error_bad_value);
          return NULL;
        }
          bfd_set_error (bfd_error_bad_value);
          return NULL;
        }
-    i++;       /* Get next entry.  */
-  }
+
+      /* Get next entry.  */
+      i++;
+    }
 
   if (i >= adata->nfat_arch)
     {
 
   if (i >= adata->nfat_arch)
     {
@@ -3406,24 +4351,42 @@ bfd_mach_o_openr_next_archived_file (bfd *archive, bfd *prev)
   if (nbfd == NULL)
     return NULL;
 
   if (nbfd == NULL)
     return NULL;
 
-  nbfd->origin = entry->offset;
-
   bfd_mach_o_convert_architecture (entry->cputype, entry->cpusubtype,
                                   &arch_type, &arch_subtype);
 
   bfd_mach_o_convert_architecture (entry->cputype, entry->cpusubtype,
                                   &arch_type, &arch_subtype);
 
-  /* Create the member filename. Use ARCH_NAME.  */
-  nbfd->filename = bfd_printable_arch_mach (arch_type, arch_subtype);
-  nbfd->iostream = NULL;
+  bfd_mach_o_fat_member_init (nbfd, arch_type, arch_subtype, entry);
+
   bfd_set_arch_mach (nbfd, arch_type, arch_subtype);
 
   return nbfd;
 }
 
   bfd_set_arch_mach (nbfd, arch_type, arch_subtype);
 
   return nbfd;
 }
 
+/* Analogous to stat call.  */
+
+static int
+bfd_mach_o_fat_stat_arch_elt (bfd *abfd, struct stat *buf)
+{
+  if (abfd->arelt_data == NULL)
+    {
+      bfd_set_error (bfd_error_invalid_operation);
+      return -1;
+    }
+
+  buf->st_mtime = 0;
+  buf->st_uid = 0;
+  buf->st_gid = 0;
+  buf->st_mode = 0644;
+  buf->st_size = arelt_size (abfd);
+
+  return 0;
+}
+
 /* If ABFD format is FORMAT and architecture is ARCH, return it.
    If ABFD is a fat image containing a member that corresponds to FORMAT
    and ARCH, returns it.
    In other case, returns NULL.
    This function allows transparent uses of fat images.  */
 /* If ABFD format is FORMAT and architecture is ARCH, return it.
    If ABFD is a fat image containing a member that corresponds to FORMAT
    and ARCH, returns it.
    In other case, returns NULL.
    This function allows transparent uses of fat images.  */
+
 bfd *
 bfd_mach_o_fat_extract (bfd *abfd,
                        bfd_format format,
 bfd *
 bfd_mach_o_fat_extract (bfd *abfd,
                        bfd_format format,
@@ -3463,10 +4426,7 @@ bfd_mach_o_fat_extract (bfd *abfd,
       if (res == NULL)
        return NULL;
 
       if (res == NULL)
        return NULL;
 
-      res->origin = e->offset;
-
-      res->filename = bfd_printable_arch_mach (cpu_type, cpu_subtype);
-      res->iostream = NULL;
+      bfd_mach_o_fat_member_init (res, cpu_type, cpu_subtype, e);
 
       if (bfd_check_format (res, format))
        {
 
       if (bfd_check_format (res, format))
        {
@@ -3533,24 +4493,26 @@ bfd_mach_o_stack_addr (enum bfd_mach_o_cpu_type type)
     }
 }
 
     }
 }
 
+/* The following two tables should be kept, as far as possible, in order of
+   most frequently used entries to optimize their use from gas.  */
+
 const bfd_mach_o_xlat_name bfd_mach_o_section_type_name[] =
 {
   { "regular", BFD_MACH_O_S_REGULAR},
 const bfd_mach_o_xlat_name bfd_mach_o_section_type_name[] =
 {
   { "regular", BFD_MACH_O_S_REGULAR},
+  { "coalesced", BFD_MACH_O_S_COALESCED},
   { "zerofill", BFD_MACH_O_S_ZEROFILL},
   { "cstring_literals", BFD_MACH_O_S_CSTRING_LITERALS},
   { "4byte_literals", BFD_MACH_O_S_4BYTE_LITERALS},
   { "8byte_literals", BFD_MACH_O_S_8BYTE_LITERALS},
   { "zerofill", BFD_MACH_O_S_ZEROFILL},
   { "cstring_literals", BFD_MACH_O_S_CSTRING_LITERALS},
   { "4byte_literals", BFD_MACH_O_S_4BYTE_LITERALS},
   { "8byte_literals", BFD_MACH_O_S_8BYTE_LITERALS},
+  { "16byte_literals", BFD_MACH_O_S_16BYTE_LITERALS},
   { "literal_pointers", BFD_MACH_O_S_LITERAL_POINTERS},
   { "literal_pointers", BFD_MACH_O_S_LITERAL_POINTERS},
-  { "non_lazy_symbol_pointers", BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS},
-  { "lazy_symbol_pointers", BFD_MACH_O_S_LAZY_SYMBOL_POINTERS},
-  { "symbol_stubs", BFD_MACH_O_S_SYMBOL_STUBS},
   { "mod_init_func_pointers", BFD_MACH_O_S_MOD_INIT_FUNC_POINTERS},
   { "mod_fini_func_pointers", BFD_MACH_O_S_MOD_FINI_FUNC_POINTERS},
   { "mod_init_func_pointers", BFD_MACH_O_S_MOD_INIT_FUNC_POINTERS},
   { "mod_fini_func_pointers", BFD_MACH_O_S_MOD_FINI_FUNC_POINTERS},
-  { "coalesced", BFD_MACH_O_S_COALESCED},
   { "gb_zerofill", BFD_MACH_O_S_GB_ZEROFILL},
   { "interposing", BFD_MACH_O_S_INTERPOSING},
   { "gb_zerofill", BFD_MACH_O_S_GB_ZEROFILL},
   { "interposing", BFD_MACH_O_S_INTERPOSING},
-  { "16byte_literals", BFD_MACH_O_S_16BYTE_LITERALS},
   { "dtrace_dof", BFD_MACH_O_S_DTRACE_DOF},
   { "dtrace_dof", BFD_MACH_O_S_DTRACE_DOF},
+  { "non_lazy_symbol_pointers", BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS},
+  { "lazy_symbol_pointers", BFD_MACH_O_S_LAZY_SYMBOL_POINTERS},
   { "symbol_stubs", BFD_MACH_O_S_SYMBOL_STUBS},
   { "lazy_dylib_symbol_pointers", BFD_MACH_O_S_LAZY_DYLIB_SYMBOL_POINTERS},
   { NULL, 0}
   { "symbol_stubs", BFD_MACH_O_S_SYMBOL_STUBS},
   { "lazy_dylib_symbol_pointers", BFD_MACH_O_S_LAZY_DYLIB_SYMBOL_POINTERS},
   { NULL, 0}
@@ -3558,30 +4520,38 @@ const bfd_mach_o_xlat_name bfd_mach_o_section_type_name[] =
 
 const bfd_mach_o_xlat_name bfd_mach_o_section_attribute_name[] =
 {
 
 const bfd_mach_o_xlat_name bfd_mach_o_section_attribute_name[] =
 {
+  { "pure_instructions", BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS },
+  { "some_instructions", BFD_MACH_O_S_ATTR_SOME_INSTRUCTIONS },
   { "loc_reloc", BFD_MACH_O_S_ATTR_LOC_RELOC },
   { "ext_reloc", BFD_MACH_O_S_ATTR_EXT_RELOC },
   { "loc_reloc", BFD_MACH_O_S_ATTR_LOC_RELOC },
   { "ext_reloc", BFD_MACH_O_S_ATTR_EXT_RELOC },
-  { "some_instructions", BFD_MACH_O_S_ATTR_SOME_INSTRUCTIONS },
   { "debug", BFD_MACH_O_S_ATTR_DEBUG },
   { "debug", BFD_MACH_O_S_ATTR_DEBUG },
-  { "modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
   { "live_support", BFD_MACH_O_S_ATTR_LIVE_SUPPORT },
   { "no_dead_strip", BFD_MACH_O_S_ATTR_NO_DEAD_STRIP },
   { "strip_static_syms", BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS },
   { "no_toc", BFD_MACH_O_S_ATTR_NO_TOC },
   { "live_support", BFD_MACH_O_S_ATTR_LIVE_SUPPORT },
   { "no_dead_strip", BFD_MACH_O_S_ATTR_NO_DEAD_STRIP },
   { "strip_static_syms", BFD_MACH_O_S_ATTR_STRIP_STATIC_SYMS },
   { "no_toc", BFD_MACH_O_S_ATTR_NO_TOC },
-  { "pure_instructions", BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS },
   { "self_modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
   { "self_modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
+  { "modifying_code", BFD_MACH_O_S_SELF_MODIFYING_CODE },
   { NULL, 0}
 };
 
 /* Get the section type from NAME.  Return 256 if NAME is unknown.  */
 
 unsigned int
   { NULL, 0}
 };
 
 /* Get the section type from NAME.  Return 256 if NAME is unknown.  */
 
 unsigned int
-bfd_mach_o_get_section_type_from_name (const char *name)
+bfd_mach_o_get_section_type_from_name (bfd *abfd, const char *name)
 {
   const bfd_mach_o_xlat_name *x;
 {
   const bfd_mach_o_xlat_name *x;
+  bfd_mach_o_backend_data *bed = bfd_mach_o_get_backend_data (abfd);
 
   for (x = bfd_mach_o_section_type_name; x->name; x++)
     if (strcmp (x->name, name) == 0)
 
   for (x = bfd_mach_o_section_type_name; x->name; x++)
     if (strcmp (x->name, name) == 0)
-      return x->val;
+      {
+       /* We found it... does the target support it?  */
+       if (bed->bfd_mach_o_section_type_valid_for_target == NULL
+           || bed->bfd_mach_o_section_type_valid_for_target (x->val))
+         return x->val; /* OK.  */
+       else
+         break; /* Not supported.  */
+      }
   /* Maximum section ID = 0xff.  */
   return 256;
 }
   /* Maximum section ID = 0xff.  */
   return 256;
 }
@@ -3711,6 +4681,120 @@ bfd_mach_o_core_file_failing_signal (bfd *abfd ATTRIBUTE_UNUSED)
   return 0;
 }
 
   return 0;
 }
 
+static bfd_mach_o_uuid_command *
+bfd_mach_o_lookup_uuid_command (bfd *abfd)
+{
+  bfd_mach_o_load_command *uuid_cmd;
+  int ncmd = bfd_mach_o_lookup_command (abfd, BFD_MACH_O_LC_UUID, &uuid_cmd);
+  if (ncmd != 1)
+    return FALSE;
+  return &uuid_cmd->command.uuid;
+}
+
+/* Return true if ABFD is a dSYM file and its UUID matches UUID_CMD. */
+
+static bfd_boolean
+bfd_mach_o_dsym_for_uuid_p (bfd *abfd, const bfd_mach_o_uuid_command *uuid_cmd)
+{
+  bfd_mach_o_uuid_command *dsym_uuid_cmd;
+
+  BFD_ASSERT (abfd);
+  BFD_ASSERT (uuid_cmd);
+
+  if (!bfd_check_format (abfd, bfd_object))
+    return FALSE;
+
+  if (bfd_get_flavour (abfd) != bfd_target_mach_o_flavour
+      || bfd_mach_o_get_data (abfd) == NULL
+      || bfd_mach_o_get_data (abfd)->header.filetype != BFD_MACH_O_MH_DSYM)
+    return FALSE;
+
+  dsym_uuid_cmd = bfd_mach_o_lookup_uuid_command (abfd);
+  if (dsym_uuid_cmd == NULL)
+    return FALSE;
+
+  if (memcmp (uuid_cmd->uuid, dsym_uuid_cmd->uuid,
+              sizeof (uuid_cmd->uuid)) != 0)
+    return FALSE;
+
+  return TRUE;
+}
+
+/* Find a BFD in DSYM_FILENAME which matches ARCH and UUID_CMD.
+   The caller is responsible for closing the returned BFD object and
+   its my_archive if the returned BFD is in a fat dSYM. */
+
+static bfd *
+bfd_mach_o_find_dsym (const char *dsym_filename,
+                      const bfd_mach_o_uuid_command *uuid_cmd,
+                      const bfd_arch_info_type *arch)
+{
+  bfd *base_dsym_bfd, *dsym_bfd;
+
+  BFD_ASSERT (uuid_cmd);
+
+  base_dsym_bfd = bfd_openr (dsym_filename, NULL);
+  if (base_dsym_bfd == NULL)
+    return NULL;
+
+  dsym_bfd = bfd_mach_o_fat_extract (base_dsym_bfd, bfd_object, arch);
+  if (bfd_mach_o_dsym_for_uuid_p (dsym_bfd, uuid_cmd))
+    return dsym_bfd;
+
+  bfd_close (dsym_bfd);
+  if (base_dsym_bfd != dsym_bfd)
+    bfd_close (base_dsym_bfd);
+
+  return NULL;
+}
+
+/* Return a BFD created from a dSYM file for ABFD.
+   The caller is responsible for closing the returned BFD object, its
+   filename, and its my_archive if the returned BFD is in a fat dSYM. */
+
+static bfd *
+bfd_mach_o_follow_dsym (bfd *abfd)
+{
+  char *dsym_filename;
+  bfd_mach_o_uuid_command *uuid_cmd;
+  bfd *dsym_bfd, *base_bfd = abfd;
+  const char *base_basename;
+
+  if (abfd == NULL || bfd_get_flavour (abfd) != bfd_target_mach_o_flavour)
+    return NULL;
+
+  if (abfd->my_archive)
+    base_bfd = abfd->my_archive;
+  /* BFD may have been opened from a stream. */
+  if (base_bfd->filename == NULL)
+    {
+      bfd_set_error (bfd_error_invalid_operation);
+      return NULL;
+    }
+  base_basename = lbasename (base_bfd->filename);
+
+  uuid_cmd = bfd_mach_o_lookup_uuid_command (abfd);
+  if (uuid_cmd == NULL)
+    return NULL;
+
+  /* TODO: We assume the DWARF file has the same as the binary's.
+     It seems apple's GDB checks all files in the dSYM bundle directory.
+     http://opensource.apple.com/source/gdb/gdb-1708/src/gdb/macosx/macosx-tdep.c
+  */
+  dsym_filename = (char *)bfd_malloc (strlen (base_bfd->filename)
+                                       + strlen (dsym_subdir) + 1
+                                       + strlen (base_basename) + 1);
+  sprintf (dsym_filename, "%s%s/%s",
+           base_bfd->filename, dsym_subdir, base_basename);
+
+  dsym_bfd = bfd_mach_o_find_dsym (dsym_filename, uuid_cmd,
+                                   bfd_get_arch_info (abfd));
+  if (dsym_bfd == NULL)
+    free (dsym_filename);
+
+  return dsym_bfd;
+}
+
 bfd_boolean
 bfd_mach_o_find_nearest_line (bfd *abfd,
                              asection *section,
 bfd_boolean
 bfd_mach_o_find_nearest_line (bfd *abfd,
                              asection *section,
@@ -3721,9 +4805,34 @@ bfd_mach_o_find_nearest_line (bfd *abfd,
                              unsigned int *line_ptr)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
                              unsigned int *line_ptr)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
-  /* TODO: Handle executables and dylibs by using dSYMs. */
-  if (mdata->header.filetype != BFD_MACH_O_MH_OBJECT)
+  if (mdata == NULL)
     return FALSE;
     return FALSE;
+  switch (mdata->header.filetype)
+    {
+    case BFD_MACH_O_MH_OBJECT:
+      break;
+    case BFD_MACH_O_MH_EXECUTE:
+    case BFD_MACH_O_MH_DYLIB:
+    case BFD_MACH_O_MH_BUNDLE:
+    case BFD_MACH_O_MH_KEXT_BUNDLE:
+      if (mdata->dwarf2_find_line_info == NULL)
+        {
+          mdata->dsym_bfd = bfd_mach_o_follow_dsym (abfd);
+          /* When we couldn't find dSYM for this binary, we look for
+             the debug information in the binary itself. In this way,
+             we won't try finding separated dSYM again because
+             mdata->dwarf2_find_line_info will be filled. */
+          if (! mdata->dsym_bfd)
+            break;
+          if (! _bfd_dwarf2_slurp_debug_info (abfd, mdata->dsym_bfd,
+                                              dwarf_debug_sections, symbols,
+                                              &mdata->dwarf2_find_line_info))
+            return FALSE;
+        }
+      break;
+    default:
+      return FALSE;
+    }
   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
                                     section, symbols, offset,
                                     filename_ptr, functionname_ptr,
   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
                                     section, symbols, offset,
                                     filename_ptr, functionname_ptr,
@@ -3738,11 +4847,41 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
   if (bfd_get_format (abfd) == bfd_object && mdata != NULL)
 {
   bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
   if (bfd_get_format (abfd) == bfd_object && mdata != NULL)
-    _bfd_dwarf2_cleanup_debug_info (abfd, &mdata->dwarf2_find_line_info);
+    {
+      _bfd_dwarf2_cleanup_debug_info (abfd, &mdata->dwarf2_find_line_info);
+      bfd_mach_o_free_cached_info (abfd);
+      if (mdata->dsym_bfd != NULL)
+        {
+          bfd *fat_bfd = mdata->dsym_bfd->my_archive;
+          char *dsym_filename = (char *)(fat_bfd
+                                         ? fat_bfd->filename
+                                         : mdata->dsym_bfd->filename);
+          bfd_close (mdata->dsym_bfd);
+          mdata->dsym_bfd = NULL;
+          if (fat_bfd)
+            bfd_close (fat_bfd);
+          free (dsym_filename);
+        }
+    }
 
   return _bfd_generic_close_and_cleanup (abfd);
 }
 
 
   return _bfd_generic_close_and_cleanup (abfd);
 }
 
+bfd_boolean bfd_mach_o_free_cached_info (bfd *abfd)
+{
+  bfd_mach_o_data_struct *mdata = bfd_mach_o_get_data (abfd);
+  asection *asect;
+  free (mdata->dyn_reloc_cache);
+  mdata->dyn_reloc_cache = NULL;
+  for (asect = abfd->sections; asect != NULL; asect = asect->next)
+    {
+      free (asect->relocation);
+      asect->relocation = NULL;
+    }
+
+  return TRUE;
+}
+
 #define bfd_mach_o_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup 
 #define bfd_mach_o_bfd_reloc_name_lookup _bfd_norelocs_bfd_reloc_name_lookup
 
 #define bfd_mach_o_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup 
 #define bfd_mach_o_bfd_reloc_name_lookup _bfd_norelocs_bfd_reloc_name_lookup
 
@@ -3750,12 +4889,14 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #define bfd_mach_o_swap_reloc_out NULL
 #define bfd_mach_o_print_thread NULL
 #define bfd_mach_o_tgt_seg_table NULL
 #define bfd_mach_o_swap_reloc_out NULL
 #define bfd_mach_o_print_thread NULL
 #define bfd_mach_o_tgt_seg_table NULL
+#define bfd_mach_o_section_type_valid_for_tgt NULL
 
 #define TARGET_NAME            mach_o_be_vec
 #define TARGET_STRING          "mach-o-be"
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      1
 #define TARGET_ARCHIVE                 0
 
 #define TARGET_NAME            mach_o_be_vec
 #define TARGET_STRING          "mach-o-be"
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      1
 #define TARGET_ARCHIVE                 0
+#define TARGET_PRIORITY                1
 #include "mach-o-target.c"
 
 #undef TARGET_NAME
 #include "mach-o-target.c"
 
 #undef TARGET_NAME
@@ -3763,12 +4904,14 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
+#undef TARGET_PRIORITY
 
 #define TARGET_NAME            mach_o_le_vec
 #define TARGET_STRING          "mach-o-le"
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      0
 #define TARGET_ARCHIVE                 0
 
 #define TARGET_NAME            mach_o_le_vec
 #define TARGET_STRING          "mach-o-le"
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      0
 #define TARGET_ARCHIVE                 0
+#define TARGET_PRIORITY                1
 
 #include "mach-o-target.c"
 
 
 #include "mach-o-target.c"
 
@@ -3777,6 +4920,7 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
+#undef TARGET_PRIORITY
 
 /* Not yet handled: creating an archive.  */
 #define bfd_mach_o_mkarchive                      _bfd_noarchive_mkarchive
 
 /* Not yet handled: creating an archive.  */
 #define bfd_mach_o_mkarchive                      _bfd_noarchive_mkarchive
@@ -3790,7 +4934,7 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #define bfd_mach_o_truncate_arname                _bfd_noarchive_truncate_arname
 #define bfd_mach_o_write_armap                    _bfd_noarchive_write_armap
 #define bfd_mach_o_get_elt_at_index               _bfd_noarchive_get_elt_at_index
 #define bfd_mach_o_truncate_arname                _bfd_noarchive_truncate_arname
 #define bfd_mach_o_write_armap                    _bfd_noarchive_write_armap
 #define bfd_mach_o_get_elt_at_index               _bfd_noarchive_get_elt_at_index
-#define bfd_mach_o_generic_stat_arch_elt          _bfd_noarchive_generic_stat_arch_elt
+#define bfd_mach_o_generic_stat_arch_elt          bfd_mach_o_fat_stat_arch_elt
 #define bfd_mach_o_update_armap_timestamp         _bfd_noarchive_update_armap_timestamp
 
 #define TARGET_NAME            mach_o_fat_vec
 #define bfd_mach_o_update_armap_timestamp         _bfd_noarchive_update_armap_timestamp
 
 #define TARGET_NAME            mach_o_fat_vec
@@ -3798,6 +4942,7 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      1
 #define TARGET_ARCHIVE                 1
 #define TARGET_ARCHITECTURE    bfd_arch_unknown
 #define TARGET_BIG_ENDIAN      1
 #define TARGET_ARCHIVE                 1
+#define TARGET_PRIORITY                0
 
 #include "mach-o-target.c"
 
 
 #include "mach-o-target.c"
 
@@ -3806,3 +4951,4 @@ bfd_mach_o_close_and_cleanup (bfd *abfd)
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
 #undef TARGET_ARCHITECTURE
 #undef TARGET_BIG_ENDIAN
 #undef TARGET_ARCHIVE
+#undef TARGET_PRIORITY
This page took 0.045894 seconds and 4 git commands to generate.