Fix the output of llvm-nm for Mach-O files to use the characters ‘d’ and ‘b’ for
[oota-llvm.git] / tools / llvm-nm / llvm-nm.cpp
index 3a72862776f17ec0d8c3cd766beabd5107c5f81e..5062435d8971e467eb6ef6ae2257b44b172882ce 100644 (file)
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/IR/Function.h"
+#include "llvm/IR/GlobalAlias.h"
+#include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/LLVMContext.h"
-#include "llvm/Bitcode/ReaderWriter.h"
-#include "llvm/IR/Module.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/COFF.h"
 #include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/IRObjectFile.h"
 #include "llvm/Object/MachO.h"
 #include "llvm/Object/MachOUniversal.h"
 #include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/COFF.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/system_error.h"
 #include <algorithm>
 #include <cctype>
 #include <cerrno>
 #include <cstring>
+#include <system_error>
 #include <vector>
 using namespace llvm;
 using namespace object;
 
 namespace {
-enum OutputFormatTy { bsd, sysv, posix };
+enum OutputFormatTy { bsd, sysv, posix, darwin };
 cl::opt<OutputFormatTy> OutputFormat(
     "format", cl::desc("Specify output format"),
     cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
-               clEnumVal(posix, "POSIX.2 format"), clEnumValEnd),
+               clEnumVal(posix, "POSIX.2 format"),
+               clEnumVal(darwin, "Darwin -m format"), clEnumValEnd),
     cl::init(bsd));
 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
                         cl::aliasopt(OutputFormat));
 
-cl::list<std::string> InputFilenames(cl::Positional,
-                                     cl::desc("<input bitcode files>"),
+cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
                                      cl::ZeroOrMore);
 
 cl::opt<bool> UndefinedOnly("undefined-only",
@@ -129,7 +132,7 @@ static void error(Twine Message, Twine Path = Twine()) {
   errs() << ToolName << ": " << Path << ": " << Message << ".\n";
 }
 
-static bool error(error_code EC, Twine Path = Twine()) {
+static bool error(std::error_code EC, Twine Path = Twine()) {
   if (EC) {
     error(EC.message(), Path);
     return true;
@@ -143,6 +146,7 @@ struct NMSymbol {
   uint64_t Size;
   char TypeChar;
   StringRef Name;
+  DataRefImpl Symb;
 };
 }
 
@@ -179,11 +183,193 @@ static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
     return false;
 }
 
+static char isSymbolList64Bit(SymbolicFile *Obj) {
+  if (isa<IRObjectFile>(Obj))
+    return false;
+  else if (isa<COFFObjectFile>(Obj))
+    return false;
+  else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
+    return MachO->is64Bit();
+  else if (isa<ELF32LEObjectFile>(Obj))
+    return false;
+  else if (isa<ELF64LEObjectFile>(Obj))
+    return true;
+  else if (isa<ELF32BEObjectFile>(Obj))
+    return false;
+  else if(isa<ELF64BEObjectFile>(Obj))
+    return true;
+  else
+    return false;
+}
+
 static StringRef CurrentFilename;
 typedef std::vector<NMSymbol> SymbolListT;
 static SymbolListT SymbolList;
 
-static void sortAndPrintSymbolList() {
+// darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
+// the OutputFormat is darwin.  It produces the same output as darwin's nm(1) -m
+// output.
+static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
+                              char *SymbolAddrStr, const char *printBlanks) {
+  MachO::mach_header H;
+  MachO::mach_header_64 H_64;
+  uint32_t Filetype, Flags;
+  MachO::nlist_64 STE_64;
+  MachO::nlist STE;
+  uint8_t NType;
+  uint16_t NDesc;
+  uint64_t NValue;
+  if (MachO->is64Bit()) {
+    H_64 = MachO->MachOObjectFile::getHeader64();
+    Filetype = H_64.filetype;
+    Flags = H_64.flags;
+    STE_64 = MachO->getSymbol64TableEntry(I->Symb);
+    NType = STE_64.n_type;
+    NDesc = STE_64.n_desc;
+    NValue = STE_64.n_value;
+  } else {
+    H = MachO->MachOObjectFile::getHeader();
+    Filetype = H.filetype;
+    Flags = H.flags;
+    STE = MachO->getSymbolTableEntry(I->Symb);
+    NType = STE.n_type;
+    NDesc = STE.n_desc;
+    NValue = STE.n_value;
+  }
+
+  if (PrintAddress) {
+    if ((NType & MachO::N_TYPE) == MachO::N_INDR)
+      strcpy(SymbolAddrStr, printBlanks);
+    outs() << SymbolAddrStr << ' ';
+  }
+
+  switch (NType & MachO::N_TYPE) {
+  case MachO::N_UNDF:
+    if (NValue != 0) {
+      outs() << "(common) ";
+      if (MachO::GET_COMM_ALIGN(NDesc) != 0)
+        outs() << "(alignment 2^" <<
+                   (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
+    } else {
+      if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
+        outs() << "(prebound ";
+      else
+        outs() << "(";
+      if ((NDesc & MachO::REFERENCE_TYPE) ==
+          MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
+        outs() << "undefined [lazy bound]) ";
+      else if ((NDesc & MachO::REFERENCE_TYPE) ==
+               MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
+        outs() << "undefined [private lazy bound]) ";
+      else if ((NDesc & MachO::REFERENCE_TYPE) ==
+               MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
+        outs() << "undefined [private]) ";
+      else
+        outs() << "undefined) ";
+    }
+    break;
+  case MachO::N_ABS:
+    outs() << "(absolute) ";
+    break;
+  case MachO::N_INDR:
+    outs() << "(indirect) ";
+    break;
+  case MachO::N_SECT: {
+    section_iterator Sec = MachO->section_end();
+    MachO->getSymbolSection(I->Symb, Sec);
+    DataRefImpl Ref = Sec->getRawDataRefImpl();
+    StringRef SectionName;
+    MachO->getSectionName(Ref, SectionName);
+    StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
+    outs() << "(" << SegmentName << "," << SectionName << ") ";
+    break;
+  }
+  default:
+    outs() << "(?) ";
+    break;
+  }
+
+  if (NType & MachO::N_EXT) {
+    if (NDesc & MachO::REFERENCED_DYNAMICALLY)
+      outs() << "[referenced dynamically] ";
+    if (NType & MachO::N_PEXT) {
+      if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
+        outs() <<  "weak private external ";
+      else
+        outs() <<  "private external ";
+    } else {
+      if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
+          (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF){
+        if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
+            (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
+          outs() << "weak external automatically hidden ";
+        else
+          outs() << "weak external ";
+      }
+      else
+        outs() << "external ";
+    }
+  } else {
+    if (NType & MachO::N_PEXT)
+      outs() << "non-external (was a private external) ";
+    else
+      outs() << "non-external ";
+  }
+
+  if (Filetype == MachO::MH_OBJECT &&
+      (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
+    outs() << "[no dead strip] ";
+
+  if (Filetype == MachO::MH_OBJECT &&
+      ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
+      (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
+    outs() << "[symbol resolver] ";
+
+  if (Filetype == MachO::MH_OBJECT &&
+      ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
+      (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
+    outs() << "[alt entry] ";
+
+  if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
+    outs() << "[Thumb] ";
+
+  if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
+    outs() << I->Name << " (for ";
+    StringRef IndirectName;
+    if (MachO->getIndirectName(I->Symb, IndirectName))
+      outs() << "?)";
+    else
+      outs() << IndirectName << ")";
+  }
+  else
+    outs() << I->Name;
+
+  if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
+      (((NType & MachO::N_TYPE) == MachO::N_UNDF &&
+        NValue == 0) ||
+       (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
+    uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
+    if (LibraryOrdinal != 0) {
+      if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
+        outs() << " (from executable)";
+      else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
+        outs() << " (dynamically looked up)";
+      else {
+        StringRef LibraryName;
+        if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1,
+                                              LibraryName))
+          outs() << " (from bad library ordinal " <<
+                 LibraryOrdinal << ")";
+        else
+          outs() << " (from " << LibraryName << ")";
+      }
+    }
+  }
+
+  outs() << "\n";
+}
+
+static void sortAndPrintSymbolList(SymbolicFile *Obj) {
   if (!NoSort) {
     if (NumericSort)
       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
@@ -203,6 +389,15 @@ static void sortAndPrintSymbolList() {
            << "         Size   Line  Section\n";
   }
 
+  const char *printBlanks, *printFormat;
+  if (isSymbolList64Bit(Obj)) {
+    printBlanks = "                ";
+    printFormat = "%016" PRIx64;
+  } else {
+    printBlanks = "        ";
+    printFormat = "%08" PRIx64;
+  }
+
   for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
        I != E; ++I) {
     if ((I->TypeChar != 'U') && UndefinedOnly)
@@ -212,24 +407,30 @@ static void sortAndPrintSymbolList() {
     if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
       continue;
 
-    char SymbolAddrStr[10] = "";
-    char SymbolSizeStr[10] = "";
+    char SymbolAddrStr[18] = "";
+    char SymbolSizeStr[18] = "";
 
     if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
-      strcpy(SymbolAddrStr, "        ");
+      strcpy(SymbolAddrStr, printBlanks);
     if (OutputFormat == sysv)
-      strcpy(SymbolSizeStr, "        ");
+      strcpy(SymbolSizeStr, printBlanks);
 
     if (I->Address != UnknownAddressOrSize)
-      format("%08" PRIx64, I->Address)
+      format(printFormat, I->Address)
           .print(SymbolAddrStr, sizeof(SymbolAddrStr));
     if (I->Size != UnknownAddressOrSize)
-      format("%08" PRIx64, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
-
-    if (OutputFormat == posix) {
+      format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
+
+    // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
+    // nm(1) -m output, else if OutputFormat is darwin and not a Mach-O object
+    // fall back to OutputFormat bsd (see below).
+    MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
+    if (OutputFormat == darwin && MachO) {
+      darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
+    } else if (OutputFormat == posix) {
       outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
              << SymbolSizeStr << "\n";
-    } else if (OutputFormat == bsd) {
+    } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
       if (PrintAddress)
         outs() << SymbolAddrStr << ' ';
       if (PrintSize) {
@@ -250,67 +451,15 @@ static void sortAndPrintSymbolList() {
   SymbolList.clear();
 }
 
-static char typeCharForSymbol(GlobalValue &GV) {
-  if (GV.isDeclaration())
-    return 'U';
-  if (GV.hasLinkOnceLinkage())
-    return 'C';
-  if (GV.hasCommonLinkage())
-    return 'C';
-  if (GV.hasWeakLinkage())
-    return 'W';
-  if (isa<Function>(GV) && GV.hasInternalLinkage())
-    return 't';
-  if (isa<Function>(GV))
-    return 'T';
-  if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())
-    return 'd';
-  if (isa<GlobalVariable>(GV))
-    return 'D';
-  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
-    const GlobalValue *AliasedGV = GA->getAliasedGlobal();
-    if (isa<Function>(AliasedGV))
-      return 'T';
-    if (isa<GlobalVariable>(AliasedGV))
-      return 'D';
-  }
-  return '?';
-}
-
-static void dumpSymbolNameForGlobalValue(GlobalValue &GV) {
-  // Private linkage and available_externally linkage don't exist in symtab.
-  if (GV.hasPrivateLinkage() || GV.hasLinkerPrivateLinkage() ||
-      GV.hasLinkerPrivateWeakLinkage() || GV.hasAvailableExternallyLinkage())
-    return;
-  char TypeChar = typeCharForSymbol(GV);
-  if (GV.hasLocalLinkage() && ExternalOnly)
-    return;
-
-  NMSymbol S;
-  S.Address = UnknownAddressOrSize;
-  S.Size = UnknownAddressOrSize;
-  S.TypeChar = TypeChar;
-  S.Name = GV.getName();
-  SymbolList.push_back(S);
-}
-
-static void dumpSymbolNamesFromModule(Module *M) {
-  CurrentFilename = M->getModuleIdentifier();
-  std::for_each(M->begin(), M->end(), dumpSymbolNameForGlobalValue);
-  std::for_each(M->global_begin(), M->global_end(),
-                dumpSymbolNameForGlobalValue);
-  if (!WithoutAliases)
-    std::for_each(M->alias_begin(), M->alias_end(),
-                  dumpSymbolNameForGlobalValue);
-
-  sortAndPrintSymbolList();
-}
-
 template <class ELFT>
-static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
+static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
+                                basic_symbol_iterator I) {
   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
 
+  // OK, this is ELF
+  symbol_iterator SymI(I);
+
   DataRefImpl Symb = I->getRawDataRefImpl();
   const Elf_Sym *ESym = Obj.getSymbol(Symb);
   const ELFFile<ELFT> &EF = *Obj.getELFFile();
@@ -339,7 +488,7 @@ static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
 
   if (ESym->getType() == ELF::STT_SECTION) {
     StringRef Name;
-    if (error(I->getName(Name)))
+    if (error(SymI->getName(Name)))
       return '?';
     return StringSwitch<char>(Name)
         .StartsWith(".debug", 'N')
@@ -351,10 +500,14 @@ static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
 }
 
 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
-  const coff_symbol *Symb = Obj.getCOFFSymbol(I);
+  const coff_symbol *Symb = Obj.getCOFFSymbol(*I);
+  // OK, this is COFF.
+  symbol_iterator SymI(I);
+
   StringRef Name;
-  if (error(I->getName(Name)))
+  if (error(SymI->getName(Name)))
     return '?';
+
   char Ret = StringSwitch<char>(Name)
                  .StartsWith(".debug", 'N')
                  .StartsWith(".sxdata", 'N')
@@ -364,11 +517,11 @@ static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
     return Ret;
 
   uint32_t Characteristics = 0;
-  if (Symb->SectionNumber > 0) {
-    section_iterator SecI = Obj.end_sections();
-    if (error(I->getSection(SecI)))
+  if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
+    section_iterator SecI = Obj.section_end();
+    if (error(SymI->getSection(SecI)))
       return '?';
-    const coff_section *Section = Obj.getCOFFSection(SecI);
+    const coff_section *Section = Obj.getCOFFSection(*SecI);
     Characteristics = Section->Characteristics;
   }
 
@@ -390,8 +543,7 @@ static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
       return 'i';
 
     // Check for section symbol.
-    else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
-             Symb->Value == 0)
+    else if (Symb->isSectionDefinition())
       return 's';
   }
 
@@ -407,15 +559,17 @@ static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
   return STE.n_type;
 }
 
-static char getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I) {
+static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
   DataRefImpl Symb = I->getRawDataRefImpl();
   uint8_t NType = getNType(Obj, Symb);
 
   switch (NType & MachO::N_TYPE) {
   case MachO::N_ABS:
     return 's';
+  case MachO::N_INDR:
+    return 'i';
   case MachO::N_SECT: {
-    section_iterator Sec = Obj.end_sections();
+    section_iterator Sec = Obj.section_end();
     Obj.getSymbolSection(Symb, Sec);
     DataRefImpl Ref = Sec->getRawDataRefImpl();
     StringRef SectionName;
@@ -423,6 +577,10 @@ static char getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I) {
     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
     if (SegmentName == "__TEXT" && SectionName == "__text")
       return 't';
+    else if (SegmentName == "__DATA" && SectionName == "__data")
+      return 'd';
+    else if (SegmentName == "__DATA" && SectionName == "__bss")
+      return 'b';
     else
       return 's';
   }
@@ -431,6 +589,19 @@ static char getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I) {
   return '?';
 }
 
+static char getSymbolNMTypeChar(const GlobalValue &GV) {
+  if (GV.getType()->getElementType()->isFunctionTy())
+    return 't';
+  // FIXME: should we print 'b'? At the IR level we cannot be sure if this
+  // will be in bss or not, but we could approximate.
+  return 'd';
+}
+
+static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
+  const GlobalValue &GV = Obj.getSymbolGV(I->getRawDataRefImpl());
+  return getSymbolNMTypeChar(GV);
+}
+
 template <class ELFT>
 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
@@ -441,7 +612,7 @@ static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
   return ESym->getType() == ELF::STT_OBJECT;
 }
 
-static bool isObject(ObjectFile *Obj, symbol_iterator I) {
+static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
     return isObject(*ELF, I);
   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
@@ -453,7 +624,7 @@ static bool isObject(ObjectFile *Obj, symbol_iterator I) {
   return false;
 }
 
-static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
+static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
   uint32_t Symflags = I->getFlags();
   if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
     char Ret = isObject(Obj, I) ? 'v' : 'w';
@@ -471,6 +642,8 @@ static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
   char Ret = '?';
   if (Symflags & object::SymbolRef::SF_Absolute)
     Ret = 'a';
+  else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
+    Ret = getSymbolNMTypeChar(*IR, I);
   else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
     Ret = getSymbolNMTypeChar(*COFF, I);
   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
@@ -490,87 +663,72 @@ static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
   return Ret;
 }
 
-static void getDynamicSymbolIterators(ObjectFile *Obj, symbol_iterator &Begin,
-                                      symbol_iterator &End) {
-  if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) {
-    Begin = ELF->begin_dynamic_symbols();
-    End = ELF->end_dynamic_symbols();
-    return;
-  }
-  if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) {
-    Begin = ELF->begin_dynamic_symbols();
-    End = ELF->end_dynamic_symbols();
-    return;
-  }
-  if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) {
-    Begin = ELF->begin_dynamic_symbols();
-    End = ELF->end_dynamic_symbols();
-    return;
-  }
-  ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
-  Begin = ELF->begin_dynamic_symbols();
-  End = ELF->end_dynamic_symbols();
-  return;
-}
-
-static void dumpSymbolNamesFromObject(ObjectFile *Obj) {
-  symbol_iterator IBegin = Obj->begin_symbols();
-  symbol_iterator IEnd = Obj->end_symbols();
+static void dumpSymbolNamesFromObject(SymbolicFile *Obj) {
+  basic_symbol_iterator IBegin = Obj->symbol_begin();
+  basic_symbol_iterator IEnd = Obj->symbol_end();
   if (DynamicSyms) {
     if (!Obj->isELF()) {
       error("File format has no dynamic symbol table", Obj->getFileName());
       return;
     }
-    getDynamicSymbolIterators(Obj, IBegin, IEnd);
+    std::pair<symbol_iterator, symbol_iterator> IDyn =
+        getELFDynamicSymbolIterators(Obj);
+    IBegin = IDyn.first;
+    IEnd = IDyn.second;
   }
-  for (symbol_iterator I = IBegin; I != IEnd; ++I) {
+  std::string NameBuffer;
+  raw_string_ostream OS(NameBuffer);
+  for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
     uint32_t SymFlags = I->getFlags();
     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
       continue;
+    if (WithoutAliases) {
+      if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
+        const GlobalValue &GV = IR->getSymbolGV(I->getRawDataRefImpl());
+        if(isa<GlobalAlias>(GV))
+          continue;
+      }
+    }
     NMSymbol S;
     S.Size = UnknownAddressOrSize;
     S.Address = UnknownAddressOrSize;
-    if (PrintSize || SizeSort) {
-      if (error(I->getSize(S.Size)))
+    if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
+      symbol_iterator SymI = I;
+      if (error(SymI->getSize(S.Size)))
         break;
     }
-    if (PrintAddress)
-      if (error(I->getAddress(S.Address)))
+    if (PrintAddress && isa<ObjectFile>(Obj))
+      if (error(symbol_iterator(I)->getAddress(S.Address)))
         break;
     S.TypeChar = getNMTypeChar(Obj, I);
-    if (error(I->getName(S.Name)))
+    if (error(I->printName(OS)))
       break;
+    OS << '\0';
+    S.Symb = I->getRawDataRefImpl();
     SymbolList.push_back(S);
   }
 
+  OS.flush();
+  const char *P = NameBuffer.c_str();
+  for (unsigned I = 0; I < SymbolList.size(); ++I) {
+    SymbolList[I].Name = P;
+    P += strlen(P) + 1;
+  }
+
   CurrentFilename = Obj->getFileName();
-  sortAndPrintSymbolList();
+  sortAndPrintSymbolList(Obj);
 }
 
 static void dumpSymbolNamesFromFile(std::string &Filename) {
-  OwningPtr<MemoryBuffer> Buffer;
+  std::unique_ptr<MemoryBuffer> Buffer;
   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
     return;
 
-  sys::fs::file_magic Magic = sys::fs::identify_magic(Buffer->getBuffer());
-
   LLVMContext &Context = getGlobalContext();
-  if (Magic == sys::fs::file_magic::bitcode) {
-    ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buffer.get(), Context);
-    if (error(ModuleOrErr.getError(), Filename)) {
-      return;
-    } else {
-      Module *Result = ModuleOrErr.get();
-      dumpSymbolNamesFromModule(Result);
-      delete Result;
-    }
-    return;
-  }
-
-  ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.take(), Magic);
+  ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.release(), &Context);
   if (error(BinaryOrErr.getError(), Filename))
     return;
-  OwningPtr<Binary> Bin(BinaryOrErr.get());
+  std::unique_ptr<Binary> Bin(BinaryOrErr.get());
 
   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
     if (ArchiveMap) {
@@ -579,16 +737,14 @@ static void dumpSymbolNamesFromFile(std::string &Filename) {
       if (I != E) {
         outs() << "Archive map\n";
         for (; I != E; ++I) {
-          Archive::child_iterator C;
-          StringRef SymName;
-          StringRef FileName;
-          if (error(I->getMember(C)))
-            return;
-          if (error(I->getName(SymName)))
+          ErrorOr<Archive::child_iterator> C = I->getMember();
+          if (error(C.getError()))
             return;
-          if (error(C->getName(FileName)))
+          ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
+          if (error(FileNameOrErr.getError()))
             return;
-          outs() << SymName << " in " << FileName << "\n";
+          StringRef SymName = I->getName();
+          outs() << SymName << " in " << FileNameOrErr.get() << "\n";
         }
         outs() << "\n";
       }
@@ -596,42 +752,58 @@ static void dumpSymbolNamesFromFile(std::string &Filename) {
 
     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
          I != E; ++I) {
-      OwningPtr<Binary> Child;
-      if (I->getAsBinary(Child)) {
-        // Try opening it as a bitcode file.
-        OwningPtr<MemoryBuffer> Buff;
-        if (error(I->getMemoryBuffer(Buff)))
-          return;
-
-        ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buff.get(), Context);
-        if (ModuleOrErr) {
-          Module *Result = ModuleOrErr.get();
-          dumpSymbolNamesFromModule(Result);
-          delete Result;
-        }
+      ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
+      if (ChildOrErr.getError())
         continue;
-      }
-      if (ObjectFile *O = dyn_cast<ObjectFile>(Child.get())) {
-        outs() << O->getFileName() << ":\n";
+      if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
+        if (isa<MachOObjectFile>(O)) {
+          outs() << Filename << "(" << O->getFileName() << ")";
+        } else
+          outs() << O->getFileName();
+        outs() << ":\n";
         dumpSymbolNamesFromObject(O);
       }
     }
     return;
   }
-  if (MachOUniversalBinary *UB =
-          dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
+  if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
+    bool moreThanOneArch = UB->getNumberOfObjects() > 1;
     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
                                                E = UB->end_objects();
          I != E; ++I) {
-      OwningPtr<ObjectFile> Obj;
+      std::unique_ptr<ObjectFile> Obj;
+      std::unique_ptr<Archive> A;
       if (!I->getAsObjectFile(Obj)) {
-        outs() << Obj->getFileName() << ":\n";
+        outs() << Obj->getFileName();
+        if (isa<MachOObjectFile>(Obj.get()) && moreThanOneArch)
+          outs() << " (for architecture " << I->getArchTypeName() << ")";
+        outs() << ":\n";
         dumpSymbolNamesFromObject(Obj.get());
       }
+      else if (!I->getAsArchive(A)) {
+        for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
+             AI != AE; ++AI) {
+          ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
+              AI->getAsBinary(&Context);
+          if (ChildOrErr.getError())
+            continue;
+          if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
+            outs() << A->getFileName();
+            if (isa<MachOObjectFile>(O)) {
+              outs() << "(" << O->getFileName() << ")";
+              if (moreThanOneArch)
+                outs() << " (for architecture " << I->getArchTypeName() << ")";
+            } else
+              outs() << ":" << O->getFileName();
+            outs() << ":\n";
+            dumpSymbolNamesFromObject(O);
+          }
+        }
+      }
     }
     return;
   }
-  if (ObjectFile *O = dyn_cast<ObjectFile>(Bin.get())) {
+  if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
     dumpSymbolNamesFromObject(O);
     return;
   }