Modernize getELFDynamicSymbolIterators.
[oota-llvm.git] / tools / llvm-nm / llvm-nm.cpp
1 //===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that works like traditional Unix "nm", that is, it
11 // prints out the names of symbols in a bitcode or object file, along with some
12 // information about each symbol.
13 //
14 // This "nm" supports many of the features of GNU "nm", including its different
15 // output formats.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Object/MachOUniversal.h"
29 #include "llvm/Object/ObjectFile.h"
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <algorithm>
42 #include <cctype>
43 #include <cerrno>
44 #include <cstring>
45 #include <system_error>
46 #include <vector>
47 using namespace llvm;
48 using namespace object;
49
50 namespace {
51 enum OutputFormatTy { bsd, sysv, posix, darwin };
52 cl::opt<OutputFormatTy> OutputFormat(
53     "format", cl::desc("Specify output format"),
54     cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
55                clEnumVal(posix, "POSIX.2 format"),
56                clEnumVal(darwin, "Darwin -m format"), clEnumValEnd),
57     cl::init(bsd));
58 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
59                         cl::aliasopt(OutputFormat));
60
61 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
62                                      cl::ZeroOrMore);
63
64 cl::opt<bool> UndefinedOnly("undefined-only",
65                             cl::desc("Show only undefined symbols"));
66 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
67                          cl::aliasopt(UndefinedOnly));
68
69 cl::opt<bool> DynamicSyms("dynamic",
70                           cl::desc("Display the dynamic symbols instead "
71                                    "of normal symbols."));
72 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
73                        cl::aliasopt(DynamicSyms));
74
75 cl::opt<bool> DefinedOnly("defined-only",
76                           cl::desc("Show only defined symbols"));
77 cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"),
78                        cl::aliasopt(DefinedOnly));
79
80 cl::opt<bool> ExternalOnly("extern-only",
81                            cl::desc("Show only external symbols"));
82 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
83                         cl::aliasopt(ExternalOnly));
84
85 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
86 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
87 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"));
88
89 static cl::list<std::string>
90     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
91               cl::ZeroOrMore);
92 bool ArchAll = false;
93
94 cl::opt<bool> PrintFileName(
95     "print-file-name",
96     cl::desc("Precede each symbol with the object file it came from"));
97
98 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
99                          cl::aliasopt(PrintFileName));
100 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
101                          cl::aliasopt(PrintFileName));
102
103 cl::opt<bool> DebugSyms("debug-syms",
104                         cl::desc("Show all symbols, even debugger only"));
105 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
106                      cl::aliasopt(DebugSyms));
107
108 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
109 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
110                        cl::aliasopt(NumericSort));
111 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
112                        cl::aliasopt(NumericSort));
113
114 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
115 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort));
116
117 cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order"));
118 cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"),
119                        cl::aliasopt(ReverseSort));
120
121 cl::opt<bool> PrintSize("print-size",
122                         cl::desc("Show symbol size instead of address"));
123 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
124                      cl::aliasopt(PrintSize));
125
126 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
127
128 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
129                              cl::desc("Exclude aliases from output"));
130
131 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
132 cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"),
133                       cl::aliasopt(ArchiveMap));
134
135 cl::opt<bool> JustSymbolName("just-symbol-name",
136                              cl::desc("Print just the symbol's name"));
137 cl::alias JustSymbolNames("j", cl::desc("Alias for --just-symbol-name"),
138                           cl::aliasopt(JustSymbolName));
139
140 // FIXME: This option takes exactly two strings and should be allowed anywhere
141 // on the command line.  Such that "llvm-nm -s __TEXT __text foo.o" would work.
142 // But that does not as the CommandLine Library does not have a way to make
143 // this work.  For now the "-s __TEXT __text" has to be last on the command
144 // line.
145 cl::list<std::string> SegSect("s", cl::Positional, cl::ZeroOrMore,
146                               cl::desc("Dump only symbols from this segment "
147                                        "and section name, Mach-O only"));
148
149 cl::opt<bool> FormatMachOasHex("x", cl::desc("Print symbol entry in hex, "
150                                              "Mach-O only"));
151
152 cl::opt<bool> NoLLVMBitcode("no-llvm-bc",
153                             cl::desc("Disable LLVM bitcode reader"));
154
155 bool PrintAddress = true;
156
157 bool MultipleFiles = false;
158
159 bool HadError = false;
160
161 std::string ToolName;
162 }
163
164 static void error(Twine Message, Twine Path = Twine()) {
165   HadError = true;
166   errs() << ToolName << ": " << Path << ": " << Message << ".\n";
167 }
168
169 static bool error(std::error_code EC, Twine Path = Twine()) {
170   if (EC) {
171     error(EC.message(), Path);
172     return true;
173   }
174   return false;
175 }
176
177 namespace {
178 struct NMSymbol {
179   uint64_t Address;
180   uint64_t Size;
181   char TypeChar;
182   StringRef Name;
183   DataRefImpl Symb;
184 };
185 }
186
187 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
188   if (!ReverseSort) {
189     if (A.Address < B.Address)
190       return true;
191     if (A.Address == B.Address && A.Name < B.Name)
192       return true;
193     if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
194       return true;
195     return false;
196   }
197
198   if (A.Address > B.Address)
199     return true;
200   if (A.Address == B.Address && A.Name > B.Name)
201     return true;
202   if (A.Address == B.Address && A.Name == B.Name && A.Size > B.Size)
203     return true;
204   return false;
205 }
206
207 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
208   if (!ReverseSort) {
209     if (A.Size < B.Size)
210       return true;
211     if (A.Size == B.Size && A.Name < B.Name)
212       return true;
213     if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
214       return true;
215     return false;
216   }
217
218   if (A.Size > B.Size)
219     return true;
220   if (A.Size == B.Size && A.Name > B.Name)
221     return true;
222   if (A.Size == B.Size && A.Name == B.Name && A.Address > B.Address)
223     return true;
224   return false;
225 }
226
227 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
228   if (!ReverseSort) {
229     if (A.Name < B.Name)
230       return true;
231     if (A.Name == B.Name && A.Size < B.Size)
232       return true;
233     if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
234       return true;
235     return false;
236   }
237   if (A.Name > B.Name)
238     return true;
239   if (A.Name == B.Name && A.Size > B.Size)
240     return true;
241   if (A.Name == B.Name && A.Size == B.Size && A.Address > B.Address)
242     return true;
243   return false;
244 }
245
246 static char isSymbolList64Bit(SymbolicFile &Obj) {
247   if (isa<IRObjectFile>(Obj))
248     return false;
249   if (isa<COFFObjectFile>(Obj))
250     return false;
251   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
252     return MachO->is64Bit();
253   if (isa<ELF32LEObjectFile>(Obj))
254     return false;
255   if (isa<ELF64LEObjectFile>(Obj))
256     return true;
257   if (isa<ELF32BEObjectFile>(Obj))
258     return false;
259   if (isa<ELF64BEObjectFile>(Obj))
260     return true;
261   return false;
262 }
263
264 static StringRef CurrentFilename;
265 typedef std::vector<NMSymbol> SymbolListT;
266 static SymbolListT SymbolList;
267
268 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
269 // the OutputFormat is darwin or we are printing Mach-O symbols in hex.  For
270 // the darwin format it produces the same output as darwin's nm(1) -m output
271 // and when printing Mach-O symbols in hex it produces the same output as
272 // darwin's nm(1) -x format.
273 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
274                               char *SymbolAddrStr, const char *printBlanks) {
275   MachO::mach_header H;
276   MachO::mach_header_64 H_64;
277   uint32_t Filetype, Flags;
278   MachO::nlist_64 STE_64;
279   MachO::nlist STE;
280   uint8_t NType;
281   uint8_t NSect;
282   uint16_t NDesc;
283   uint32_t NStrx;
284   uint64_t NValue;
285   if (MachO->is64Bit()) {
286     H_64 = MachO->MachOObjectFile::getHeader64();
287     Filetype = H_64.filetype;
288     Flags = H_64.flags;
289     STE_64 = MachO->getSymbol64TableEntry(I->Symb);
290     NType = STE_64.n_type;
291     NSect = STE_64.n_sect;
292     NDesc = STE_64.n_desc;
293     NStrx = STE_64.n_strx;
294     NValue = STE_64.n_value;
295   } else {
296     H = MachO->MachOObjectFile::getHeader();
297     Filetype = H.filetype;
298     Flags = H.flags;
299     STE = MachO->getSymbolTableEntry(I->Symb);
300     NType = STE.n_type;
301     NSect = STE.n_sect;
302     NDesc = STE.n_desc;
303     NStrx = STE.n_strx;
304     NValue = STE.n_value;
305   }
306
307   // If we are printing Mach-O symbols in hex do that and return.
308   if (FormatMachOasHex) {
309     char Str[18] = "";
310     const char *printFormat;
311     if (MachO->is64Bit())
312       printFormat = "%016" PRIx64;
313     else
314       printFormat = "%08" PRIx64;
315     format(printFormat, NValue).print(Str, sizeof(Str));
316     outs() << Str << ' ';
317     format("%02x", NType).print(Str, sizeof(Str));
318     outs() << Str << ' ';
319     format("%02x", NSect).print(Str, sizeof(Str));
320     outs() << Str << ' ';
321     format("%04x", NDesc).print(Str, sizeof(Str));
322     outs() << Str << ' ';
323     format("%08x", NStrx).print(Str, sizeof(Str));
324     outs() << Str << ' ';
325     outs() << I->Name << "\n";
326     return;
327   }
328
329   if (PrintAddress) {
330     if ((NType & MachO::N_TYPE) == MachO::N_INDR)
331       strcpy(SymbolAddrStr, printBlanks);
332     outs() << SymbolAddrStr << ' ';
333   }
334
335   switch (NType & MachO::N_TYPE) {
336   case MachO::N_UNDF:
337     if (NValue != 0) {
338       outs() << "(common) ";
339       if (MachO::GET_COMM_ALIGN(NDesc) != 0)
340         outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
341     } else {
342       if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
343         outs() << "(prebound ";
344       else
345         outs() << "(";
346       if ((NDesc & MachO::REFERENCE_TYPE) ==
347           MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
348         outs() << "undefined [lazy bound]) ";
349       else if ((NDesc & MachO::REFERENCE_TYPE) ==
350                MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
351         outs() << "undefined [private lazy bound]) ";
352       else if ((NDesc & MachO::REFERENCE_TYPE) ==
353                MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
354         outs() << "undefined [private]) ";
355       else
356         outs() << "undefined) ";
357     }
358     break;
359   case MachO::N_ABS:
360     outs() << "(absolute) ";
361     break;
362   case MachO::N_INDR:
363     outs() << "(indirect) ";
364     break;
365   case MachO::N_SECT: {
366     section_iterator Sec = MachO->section_end();
367     MachO->getSymbolSection(I->Symb, Sec);
368     DataRefImpl Ref = Sec->getRawDataRefImpl();
369     StringRef SectionName;
370     MachO->getSectionName(Ref, SectionName);
371     StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
372     outs() << "(" << SegmentName << "," << SectionName << ") ";
373     break;
374   }
375   default:
376     outs() << "(?) ";
377     break;
378   }
379
380   if (NType & MachO::N_EXT) {
381     if (NDesc & MachO::REFERENCED_DYNAMICALLY)
382       outs() << "[referenced dynamically] ";
383     if (NType & MachO::N_PEXT) {
384       if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
385         outs() << "weak private external ";
386       else
387         outs() << "private external ";
388     } else {
389       if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
390           (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
391         if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
392             (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
393           outs() << "weak external automatically hidden ";
394         else
395           outs() << "weak external ";
396       } else
397         outs() << "external ";
398     }
399   } else {
400     if (NType & MachO::N_PEXT)
401       outs() << "non-external (was a private external) ";
402     else
403       outs() << "non-external ";
404   }
405
406   if (Filetype == MachO::MH_OBJECT &&
407       (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
408     outs() << "[no dead strip] ";
409
410   if (Filetype == MachO::MH_OBJECT &&
411       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
412       (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
413     outs() << "[symbol resolver] ";
414
415   if (Filetype == MachO::MH_OBJECT &&
416       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
417       (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
418     outs() << "[alt entry] ";
419
420   if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
421     outs() << "[Thumb] ";
422
423   if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
424     outs() << I->Name << " (for ";
425     StringRef IndirectName;
426     if (MachO->getIndirectName(I->Symb, IndirectName))
427       outs() << "?)";
428     else
429       outs() << IndirectName << ")";
430   } else
431     outs() << I->Name;
432
433   if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
434       (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
435        (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
436     uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
437     if (LibraryOrdinal != 0) {
438       if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
439         outs() << " (from executable)";
440       else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
441         outs() << " (dynamically looked up)";
442       else {
443         StringRef LibraryName;
444         if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
445           outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
446         else
447           outs() << " (from " << LibraryName << ")";
448       }
449     }
450   }
451
452   outs() << "\n";
453 }
454
455 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
456 struct DarwinStabName {
457   uint8_t NType;
458   const char *Name;
459 };
460 static const struct DarwinStabName DarwinStabNames[] = {
461     {MachO::N_GSYM, "GSYM"},
462     {MachO::N_FNAME, "FNAME"},
463     {MachO::N_FUN, "FUN"},
464     {MachO::N_STSYM, "STSYM"},
465     {MachO::N_LCSYM, "LCSYM"},
466     {MachO::N_BNSYM, "BNSYM"},
467     {MachO::N_PC, "PC"},
468     {MachO::N_AST, "AST"},
469     {MachO::N_OPT, "OPT"},
470     {MachO::N_RSYM, "RSYM"},
471     {MachO::N_SLINE, "SLINE"},
472     {MachO::N_ENSYM, "ENSYM"},
473     {MachO::N_SSYM, "SSYM"},
474     {MachO::N_SO, "SO"},
475     {MachO::N_OSO, "OSO"},
476     {MachO::N_LSYM, "LSYM"},
477     {MachO::N_BINCL, "BINCL"},
478     {MachO::N_SOL, "SOL"},
479     {MachO::N_PARAMS, "PARAM"},
480     {MachO::N_VERSION, "VERS"},
481     {MachO::N_OLEVEL, "OLEV"},
482     {MachO::N_PSYM, "PSYM"},
483     {MachO::N_EINCL, "EINCL"},
484     {MachO::N_ENTRY, "ENTRY"},
485     {MachO::N_LBRAC, "LBRAC"},
486     {MachO::N_EXCL, "EXCL"},
487     {MachO::N_RBRAC, "RBRAC"},
488     {MachO::N_BCOMM, "BCOMM"},
489     {MachO::N_ECOMM, "ECOMM"},
490     {MachO::N_ECOML, "ECOML"},
491     {MachO::N_LENG, "LENG"},
492     {0, 0}};
493 static const char *getDarwinStabString(uint8_t NType) {
494   for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
495     if (DarwinStabNames[i].NType == NType)
496       return DarwinStabNames[i].Name;
497   }
498   return 0;
499 }
500
501 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
502 // a stab n_type value in a Mach-O file.
503 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
504   MachO::nlist_64 STE_64;
505   MachO::nlist STE;
506   uint8_t NType;
507   uint8_t NSect;
508   uint16_t NDesc;
509   if (MachO->is64Bit()) {
510     STE_64 = MachO->getSymbol64TableEntry(I->Symb);
511     NType = STE_64.n_type;
512     NSect = STE_64.n_sect;
513     NDesc = STE_64.n_desc;
514   } else {
515     STE = MachO->getSymbolTableEntry(I->Symb);
516     NType = STE.n_type;
517     NSect = STE.n_sect;
518     NDesc = STE.n_desc;
519   }
520
521   char Str[18] = "";
522   format("%02x", NSect).print(Str, sizeof(Str));
523   outs() << ' ' << Str << ' ';
524   format("%04x", NDesc).print(Str, sizeof(Str));
525   outs() << Str << ' ';
526   if (const char *stabString = getDarwinStabString(NType))
527     format("%5.5s", stabString).print(Str, sizeof(Str));
528   else
529     format("   %02x", NType).print(Str, sizeof(Str));
530   outs() << Str;
531 }
532
533 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
534                                    std::string ArchiveName,
535                                    std::string ArchitectureName) {
536   if (!NoSort) {
537     if (NumericSort)
538       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
539     else if (SizeSort)
540       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
541     else
542       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
543   }
544
545   if (!PrintFileName) {
546     if (OutputFormat == posix && MultipleFiles && printName) {
547       outs() << '\n' << CurrentFilename << ":\n";
548     } else if (OutputFormat == bsd && MultipleFiles && printName) {
549       outs() << "\n" << CurrentFilename << ":\n";
550     } else if (OutputFormat == sysv) {
551       outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
552              << "Name                  Value   Class        Type"
553              << "         Size   Line  Section\n";
554     }
555   }
556
557   const char *printBlanks, *printFormat;
558   if (isSymbolList64Bit(Obj)) {
559     printBlanks = "                ";
560     printFormat = "%016" PRIx64;
561   } else {
562     printBlanks = "        ";
563     printFormat = "%08" PRIx64;
564   }
565
566   for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
567        I != E; ++I) {
568     if ((I->TypeChar != 'U') && UndefinedOnly)
569       continue;
570     if ((I->TypeChar == 'U') && DefinedOnly)
571       continue;
572     if (SizeSort && !PrintAddress)
573       continue;
574     if (PrintFileName) {
575       if (!ArchitectureName.empty())
576         outs() << "(for architecture " << ArchitectureName << "):";
577       if (!ArchiveName.empty())
578         outs() << ArchiveName << ":";
579       outs() << CurrentFilename << ": ";
580     }
581     if (JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj))) {
582       outs() << I->Name << "\n";
583       continue;
584     }
585
586     char SymbolAddrStr[18] = "";
587     char SymbolSizeStr[18] = "";
588
589     if (OutputFormat == sysv || I->Address == UnknownAddress)
590       strcpy(SymbolAddrStr, printBlanks);
591     if (OutputFormat == sysv)
592       strcpy(SymbolSizeStr, printBlanks);
593
594     if (I->Address != UnknownAddress)
595       format(printFormat, I->Address)
596           .print(SymbolAddrStr, sizeof(SymbolAddrStr));
597     format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
598
599     // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
600     // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
601     // nm(1) -m output or hex, else if OutputFormat is darwin or we are
602     // printing Mach-O symbols in hex and not a Mach-O object fall back to
603     // OutputFormat bsd (see below).
604     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
605     if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
606       darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
607     } else if (OutputFormat == posix) {
608       outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
609              << SymbolSizeStr << "\n";
610     } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
611       if (PrintAddress)
612         outs() << SymbolAddrStr << ' ';
613       if (PrintSize) {
614         outs() << SymbolSizeStr;
615         outs() << ' ';
616       }
617       outs() << I->TypeChar;
618       if (I->TypeChar == '-' && MachO)
619         darwinPrintStab(MachO, I);
620       outs() << " " << I->Name << "\n";
621     } else if (OutputFormat == sysv) {
622       std::string PaddedName(I->Name);
623       while (PaddedName.length() < 20)
624         PaddedName += " ";
625       outs() << PaddedName << "|" << SymbolAddrStr << "|   " << I->TypeChar
626              << "  |                  |" << SymbolSizeStr << "|     |\n";
627     }
628   }
629
630   SymbolList.clear();
631 }
632
633 template <class ELFT>
634 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
635                                 basic_symbol_iterator I) {
636   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
637   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
638
639   // OK, this is ELF
640   symbol_iterator SymI(I);
641
642   DataRefImpl Symb = I->getRawDataRefImpl();
643   const Elf_Sym *ESym = Obj.getSymbol(Symb);
644   const ELFFile<ELFT> &EF = *Obj.getELFFile();
645   const Elf_Shdr *ESec = EF.getSection(ESym);
646
647   if (ESec) {
648     switch (ESec->sh_type) {
649     case ELF::SHT_PROGBITS:
650     case ELF::SHT_DYNAMIC:
651       switch (ESec->sh_flags) {
652       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
653         return 't';
654       case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
655       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
656         return 'd';
657       case ELF::SHF_ALLOC:
658       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
659       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
660         return 'r';
661       }
662       break;
663     case ELF::SHT_NOBITS:
664       return 'b';
665     }
666   }
667
668   if (ESym->getType() == ELF::STT_SECTION) {
669     StringRef Name;
670     if (error(SymI->getName(Name)))
671       return '?';
672     return StringSwitch<char>(Name)
673         .StartsWith(".debug", 'N')
674         .StartsWith(".note", 'n')
675         .Default('?');
676   }
677
678   return '?';
679 }
680
681 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
682   COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
683   // OK, this is COFF.
684   symbol_iterator SymI(I);
685
686   StringRef Name;
687   if (error(SymI->getName(Name)))
688     return '?';
689
690   char Ret = StringSwitch<char>(Name)
691                  .StartsWith(".debug", 'N')
692                  .StartsWith(".sxdata", 'N')
693                  .Default('?');
694
695   if (Ret != '?')
696     return Ret;
697
698   uint32_t Characteristics = 0;
699   if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
700     section_iterator SecI = Obj.section_end();
701     if (error(SymI->getSection(SecI)))
702       return '?';
703     const coff_section *Section = Obj.getCOFFSection(*SecI);
704     Characteristics = Section->Characteristics;
705   }
706
707   switch (Symb.getSectionNumber()) {
708   case COFF::IMAGE_SYM_DEBUG:
709     return 'n';
710   default:
711     // Check section type.
712     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
713       return 't';
714     if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
715       return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
716     if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
717       return 'b';
718     if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
719       return 'i';
720     // Check for section symbol.
721     if (Symb.isSectionDefinition())
722       return 's';
723   }
724
725   return '?';
726 }
727
728 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
729   if (Obj.is64Bit()) {
730     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
731     return STE.n_type;
732   }
733   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
734   return STE.n_type;
735 }
736
737 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
738   DataRefImpl Symb = I->getRawDataRefImpl();
739   uint8_t NType = getNType(Obj, Symb);
740
741   if (NType & MachO::N_STAB)
742     return '-';
743
744   switch (NType & MachO::N_TYPE) {
745   case MachO::N_ABS:
746     return 's';
747   case MachO::N_INDR:
748     return 'i';
749   case MachO::N_SECT: {
750     section_iterator Sec = Obj.section_end();
751     Obj.getSymbolSection(Symb, Sec);
752     DataRefImpl Ref = Sec->getRawDataRefImpl();
753     StringRef SectionName;
754     Obj.getSectionName(Ref, SectionName);
755     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
756     if (SegmentName == "__TEXT" && SectionName == "__text")
757       return 't';
758     else if (SegmentName == "__DATA" && SectionName == "__data")
759       return 'd';
760     else if (SegmentName == "__DATA" && SectionName == "__bss")
761       return 'b';
762     else
763       return 's';
764   }
765   }
766
767   return '?';
768 }
769
770 static char getSymbolNMTypeChar(const GlobalValue &GV) {
771   if (GV.getType()->getElementType()->isFunctionTy())
772     return 't';
773   // FIXME: should we print 'b'? At the IR level we cannot be sure if this
774   // will be in bss or not, but we could approximate.
775   return 'd';
776 }
777
778 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
779   const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
780   if (!GV)
781     return 't';
782   return getSymbolNMTypeChar(*GV);
783 }
784
785 template <class ELFT>
786 static bool isELFObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
787   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
788
789   DataRefImpl Symb = I->getRawDataRefImpl();
790   const Elf_Sym *ESym = Obj.getSymbol(Symb);
791
792   return ESym->getType() == ELF::STT_OBJECT;
793 }
794
795 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
796   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(&Obj))
797     return isELFObject(*ELF, I);
798   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(&Obj))
799     return isELFObject(*ELF, I);
800   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(&Obj))
801     return isELFObject(*ELF, I);
802   if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(&Obj))
803     return isELFObject(*ELF, I);
804   return false;
805 }
806
807 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
808   uint32_t Symflags = I->getFlags();
809   if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
810     char Ret = isObject(Obj, I) ? 'v' : 'w';
811     if (!(Symflags & object::SymbolRef::SF_Undefined))
812       Ret = toupper(Ret);
813     return Ret;
814   }
815
816   if (Symflags & object::SymbolRef::SF_Undefined)
817     return 'U';
818
819   if (Symflags & object::SymbolRef::SF_Common)
820     return 'C';
821
822   char Ret = '?';
823   if (Symflags & object::SymbolRef::SF_Absolute)
824     Ret = 'a';
825   else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
826     Ret = getSymbolNMTypeChar(*IR, I);
827   else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
828     Ret = getSymbolNMTypeChar(*COFF, I);
829   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
830     Ret = getSymbolNMTypeChar(*MachO, I);
831   else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(&Obj))
832     Ret = getSymbolNMTypeChar(*ELF, I);
833   else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(&Obj))
834     Ret = getSymbolNMTypeChar(*ELF, I);
835   else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(&Obj))
836     Ret = getSymbolNMTypeChar(*ELF, I);
837   else
838     Ret = getSymbolNMTypeChar(cast<ELF64BEObjectFile>(Obj), I);
839
840   if (Symflags & object::SymbolRef::SF_Global)
841     Ret = toupper(Ret);
842
843   return Ret;
844 }
845
846 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
847 // option to dump only those symbols from that section in a Mach-O file.
848 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
849 // to get the section number for that named section from the command line
850 // arguments. It returns the section number for that section in the Mach-O
851 // file or zero it is not present.
852 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
853   unsigned Nsect = 1;
854   for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
855        I != E; ++I) {
856     DataRefImpl Ref = I->getRawDataRefImpl();
857     StringRef SectionName;
858     Obj->getSectionName(Ref, SectionName);
859     StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
860     if (SegmentName == SegSect[0] && SectionName == SegSect[1])
861       return Nsect;
862     Nsect++;
863   }
864   return 0;
865 }
866
867 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
868 // option to dump only those symbols from that section in a Mach-O file.
869 // It is called once for each symbol in a Mach-O file from
870 // dumpSymbolNamesFromObject() and returns the section number for that symbol
871 // if it is in a section, else it returns 0.
872 static unsigned getNsectInMachO(MachOObjectFile &Obj, basic_symbol_iterator I) {
873   DataRefImpl Symb = I->getRawDataRefImpl();
874   if (Obj.is64Bit()) {
875     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
876     if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
877       return STE.n_sect;
878     return 0;
879   }
880   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
881   if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
882     return STE.n_sect;
883   return 0;
884 }
885
886 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
887                                       std::string ArchiveName = std::string(),
888                                       std::string ArchitectureName =
889                                         std::string()) {
890   basic_symbol_iterator IBegin = Obj.symbol_begin();
891   basic_symbol_iterator IEnd = Obj.symbol_end();
892   if (DynamicSyms) {
893     const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
894     if (!E) {
895       error("File format has no dynamic symbol table", Obj.getFileName());
896       return;
897     }
898     auto IDyn = E->getDynamicSymbolIterators();
899     IBegin = IDyn.begin();
900     IEnd = IDyn.end();
901   }
902   std::string NameBuffer;
903   raw_string_ostream OS(NameBuffer);
904   // If a "-s segname sectname" option was specified and this is a Mach-O
905   // file get the section number for that section in this object file.
906   unsigned int Nsect = 0;
907   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
908   if (SegSect.size() != 0 && MachO) {
909     Nsect = getNsectForSegSect(MachO);
910     // If this section is not in the object file no symbols are printed.
911     if (Nsect == 0)
912       return;
913   }
914   for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
915     uint32_t SymFlags = I->getFlags();
916     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
917       continue;
918     if (WithoutAliases) {
919       if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) {
920         const GlobalValue *GV = IR->getSymbolGV(I->getRawDataRefImpl());
921         if (GV && isa<GlobalAlias>(GV))
922           continue;
923       }
924     }
925     // If a "-s segname sectname" option was specified and this is a Mach-O
926     // file and this section appears in this file, Nsect will be non-zero then
927     // see if this symbol is a symbol from that section and if not skip it.
928     if (Nsect && Nsect != getNsectInMachO(*MachO, I))
929       continue;
930     NMSymbol S;
931     S.Size = 0;
932     S.Address = UnknownAddress;
933     if (PrintSize) {
934       if (auto *E = dyn_cast<ELFObjectFileBase>(&Obj)) {
935         symbol_iterator SymI = I;
936         S.Size = E->getSymbolSize(*SymI);
937       }
938     }
939     if (PrintAddress && isa<ObjectFile>(Obj))
940       if (error(symbol_iterator(I)->getAddress(S.Address)))
941         break;
942     S.TypeChar = getNMTypeChar(Obj, I);
943     if (error(I->printName(OS)))
944       break;
945     OS << '\0';
946     S.Symb = I->getRawDataRefImpl();
947     SymbolList.push_back(S);
948   }
949
950   OS.flush();
951   const char *P = NameBuffer.c_str();
952   for (unsigned I = 0; I < SymbolList.size(); ++I) {
953     SymbolList[I].Name = P;
954     P += strlen(P) + 1;
955   }
956
957   CurrentFilename = Obj.getFileName();
958   sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
959 }
960
961 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
962 // and if it is and there is a list of architecture flags is specified then
963 // check to make sure this Mach-O file is one of those architectures or all
964 // architectures was specificed.  If not then an error is generated and this
965 // routine returns false.  Else it returns true.
966 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
967   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
968
969   if (!MachO || ArchAll || ArchFlags.size() == 0)
970     return true;
971
972   MachO::mach_header H;
973   MachO::mach_header_64 H_64;
974   Triple T;
975   if (MachO->is64Bit()) {
976     H_64 = MachO->MachOObjectFile::getHeader64();
977     T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
978   } else {
979     H = MachO->MachOObjectFile::getHeader();
980     T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
981   }
982   if (std::none_of(
983           ArchFlags.begin(), ArchFlags.end(),
984           [&](const std::string &Name) { return Name == T.getArchName(); })) {
985     error("No architecture specified", Filename);
986     return false;
987   }
988   return true;
989 }
990
991 static void dumpSymbolNamesFromFile(std::string &Filename) {
992   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
993       MemoryBuffer::getFileOrSTDIN(Filename);
994   if (error(BufferOrErr.getError(), Filename))
995     return;
996
997   LLVMContext &Context = getGlobalContext();
998   ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
999       BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
1000   if (error(BinaryOrErr.getError(), Filename))
1001     return;
1002   Binary &Bin = *BinaryOrErr.get();
1003
1004   if (Archive *A = dyn_cast<Archive>(&Bin)) {
1005     if (ArchiveMap) {
1006       Archive::symbol_iterator I = A->symbol_begin();
1007       Archive::symbol_iterator E = A->symbol_end();
1008       if (I != E) {
1009         outs() << "Archive map\n";
1010         for (; I != E; ++I) {
1011           ErrorOr<Archive::child_iterator> C = I->getMember();
1012           if (error(C.getError()))
1013             return;
1014           ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
1015           if (error(FileNameOrErr.getError()))
1016             return;
1017           StringRef SymName = I->getName();
1018           outs() << SymName << " in " << FileNameOrErr.get() << "\n";
1019         }
1020         outs() << "\n";
1021       }
1022     }
1023
1024     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1025          I != E; ++I) {
1026       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
1027       if (ChildOrErr.getError())
1028         continue;
1029       if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1030         if (!checkMachOAndArchFlags(O, Filename))
1031           return;
1032         if (!PrintFileName) {
1033           outs() << "\n";
1034           if (isa<MachOObjectFile>(O)) {
1035             outs() << Filename << "(" << O->getFileName() << ")";
1036           } else
1037             outs() << O->getFileName();
1038           outs() << ":\n";
1039         }
1040         dumpSymbolNamesFromObject(*O, false, Filename);
1041       }
1042     }
1043     return;
1044   }
1045   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1046     // If we have a list of architecture flags specified dump only those.
1047     if (!ArchAll && ArchFlags.size() != 0) {
1048       // Look for a slice in the universal binary that matches each ArchFlag.
1049       bool ArchFound;
1050       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1051         ArchFound = false;
1052         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1053                                                    E = UB->end_objects();
1054              I != E; ++I) {
1055           if (ArchFlags[i] == I->getArchTypeName()) {
1056             ArchFound = true;
1057             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1058                 I->getAsObjectFile();
1059             std::string ArchiveName;
1060             std::string ArchitectureName;
1061             ArchiveName.clear();
1062             ArchitectureName.clear();
1063             if (ObjOrErr) {
1064               ObjectFile &Obj = *ObjOrErr.get();
1065               if (ArchFlags.size() > 1) {
1066                 if (PrintFileName)
1067                   ArchitectureName = I->getArchTypeName();
1068                 else
1069                   outs() << "\n" << Obj.getFileName() << " (for architecture "
1070                          << I->getArchTypeName() << ")"
1071                          << ":\n";
1072               }
1073               dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1074                                         ArchitectureName);
1075             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1076                            I->getAsArchive()) {
1077               std::unique_ptr<Archive> &A = *AOrErr;
1078               for (Archive::child_iterator AI = A->child_begin(),
1079                                            AE = A->child_end();
1080                    AI != AE; ++AI) {
1081                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1082                     AI->getAsBinary(&Context);
1083                 if (ChildOrErr.getError())
1084                   continue;
1085                 if (SymbolicFile *O =
1086                         dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1087                   if (PrintFileName) {
1088                     ArchiveName = A->getFileName();
1089                     if (ArchFlags.size() > 1)
1090                       ArchitectureName = I->getArchTypeName();
1091                   } else {
1092                     outs() << "\n" << A->getFileName();
1093                     outs() << "(" << O->getFileName() << ")";
1094                     if (ArchFlags.size() > 1) {
1095                       outs() << " (for architecture " << I->getArchTypeName()
1096                              << ")";
1097                     }
1098                     outs() << ":\n";
1099                   }
1100                   dumpSymbolNamesFromObject(*O, false, ArchiveName,
1101                                             ArchitectureName);
1102                 }
1103               }
1104             }
1105           }
1106         }
1107         if (!ArchFound) {
1108           error(ArchFlags[i],
1109                 "file: " + Filename + " does not contain architecture");
1110           return;
1111         }
1112       }
1113       return;
1114     }
1115     // No architecture flags were specified so if this contains a slice that
1116     // matches the host architecture dump only that.
1117     if (!ArchAll) {
1118       StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1119       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1120                                                  E = UB->end_objects();
1121            I != E; ++I) {
1122         if (HostArchName == I->getArchTypeName()) {
1123           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1124           std::string ArchiveName;
1125           ArchiveName.clear();
1126           if (ObjOrErr) {
1127             ObjectFile &Obj = *ObjOrErr.get();
1128             dumpSymbolNamesFromObject(Obj, false);
1129           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1130                          I->getAsArchive()) {
1131             std::unique_ptr<Archive> &A = *AOrErr;
1132             for (Archive::child_iterator AI = A->child_begin(),
1133                                          AE = A->child_end();
1134                  AI != AE; ++AI) {
1135               ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1136                   AI->getAsBinary(&Context);
1137               if (ChildOrErr.getError())
1138                 continue;
1139               if (SymbolicFile *O =
1140                       dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1141                 if (PrintFileName)
1142                   ArchiveName = A->getFileName();
1143                 else
1144                   outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1145                          << ")"
1146                          << ":\n";
1147                 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1148               }
1149             }
1150           }
1151           return;
1152         }
1153       }
1154     }
1155     // Either all architectures have been specified or none have been specified
1156     // and this does not contain the host architecture so dump all the slices.
1157     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1158     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1159                                                E = UB->end_objects();
1160          I != E; ++I) {
1161       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1162       std::string ArchiveName;
1163       std::string ArchitectureName;
1164       ArchiveName.clear();
1165       ArchitectureName.clear();
1166       if (ObjOrErr) {
1167         ObjectFile &Obj = *ObjOrErr.get();
1168         if (PrintFileName) {
1169           if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1170             ArchitectureName = I->getArchTypeName();
1171         } else {
1172           if (moreThanOneArch)
1173             outs() << "\n";
1174           outs() << Obj.getFileName();
1175           if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1176             outs() << " (for architecture " << I->getArchTypeName() << ")";
1177           outs() << ":\n";
1178         }
1179         dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1180       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1181         std::unique_ptr<Archive> &A = *AOrErr;
1182         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1183              AI != AE; ++AI) {
1184           ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1185               AI->getAsBinary(&Context);
1186           if (ChildOrErr.getError())
1187             continue;
1188           if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1189             if (PrintFileName) {
1190               ArchiveName = A->getFileName();
1191               if (isa<MachOObjectFile>(O) && moreThanOneArch)
1192                 ArchitectureName = I->getArchTypeName();
1193             } else {
1194               outs() << "\n" << A->getFileName();
1195               if (isa<MachOObjectFile>(O)) {
1196                 outs() << "(" << O->getFileName() << ")";
1197                 if (moreThanOneArch)
1198                   outs() << " (for architecture " << I->getArchTypeName()
1199                          << ")";
1200               } else
1201                 outs() << ":" << O->getFileName();
1202               outs() << ":\n";
1203             }
1204             dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
1205           }
1206         }
1207       }
1208     }
1209     return;
1210   }
1211   if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
1212     if (!checkMachOAndArchFlags(O, Filename))
1213       return;
1214     dumpSymbolNamesFromObject(*O, true);
1215     return;
1216   }
1217   error("unrecognizable file type", Filename);
1218   return;
1219 }
1220
1221 int main(int argc, char **argv) {
1222   // Print a stack trace if we signal out.
1223   sys::PrintStackTraceOnErrorSignal();
1224   PrettyStackTraceProgram X(argc, argv);
1225
1226   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1227   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1228
1229   // llvm-nm only reads binary files.
1230   if (error(sys::ChangeStdinToBinary()))
1231     return 1;
1232
1233   llvm::InitializeAllTargetInfos();
1234   llvm::InitializeAllTargetMCs();
1235   llvm::InitializeAllAsmParsers();
1236
1237   ToolName = argv[0];
1238   if (BSDFormat)
1239     OutputFormat = bsd;
1240   if (POSIXFormat)
1241     OutputFormat = posix;
1242   if (DarwinFormat)
1243     OutputFormat = darwin;
1244
1245   // The relative order of these is important. If you pass --size-sort it should
1246   // only print out the size. However, if you pass -S --size-sort, it should
1247   // print out both the size and address.
1248   if (SizeSort && !PrintSize)
1249     PrintAddress = false;
1250   if (OutputFormat == sysv || SizeSort)
1251     PrintSize = true;
1252
1253   switch (InputFilenames.size()) {
1254   case 0:
1255     InputFilenames.push_back("a.out");
1256   case 1:
1257     break;
1258   default:
1259     MultipleFiles = true;
1260   }
1261
1262   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1263     if (ArchFlags[i] == "all") {
1264       ArchAll = true;
1265     } else {
1266       if (!MachOObjectFile::isValidArch(ArchFlags[i]))
1267         error("Unknown architecture named '" + ArchFlags[i] + "'",
1268               "for the -arch option");
1269     }
1270   }
1271
1272   if (SegSect.size() != 0 && SegSect.size() != 2)
1273     error("bad number of arguments (must be two arguments)",
1274           "for the -s option");
1275
1276   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1277                 dumpSymbolNamesFromFile);
1278
1279   if (HadError)
1280     return 1;
1281
1282   return 0;
1283 }