6105a0f8e5319909615e36b629388f724c1d7631
[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 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
634                                 basic_symbol_iterator I) {
635   // OK, this is ELF
636   elf_symbol_iterator SymI(I);
637
638   elf_section_iterator SecI = Obj.section_end();
639   if (error(SymI->getSection(SecI)))
640     return '?';
641
642   if (SecI != Obj.section_end()) {
643     switch (SecI->getType()) {
644     case ELF::SHT_PROGBITS:
645     case ELF::SHT_DYNAMIC:
646       switch (SecI->getFlags()) {
647       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
648         return 't';
649       case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
650       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
651         return 'd';
652       case ELF::SHF_ALLOC:
653       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
654       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
655         return 'r';
656       }
657       break;
658     case ELF::SHT_NOBITS:
659       return 'b';
660     }
661   }
662
663   if (SymI->getELFType() == ELF::STT_SECTION) {
664     StringRef Name;
665     if (error(SymI->getName(Name)))
666       return '?';
667     return StringSwitch<char>(Name)
668         .StartsWith(".debug", 'N')
669         .StartsWith(".note", 'n')
670         .Default('?');
671   }
672
673   return 'n';
674 }
675
676 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
677   COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
678   // OK, this is COFF.
679   symbol_iterator SymI(I);
680
681   StringRef Name;
682   if (error(SymI->getName(Name)))
683     return '?';
684
685   char Ret = StringSwitch<char>(Name)
686                  .StartsWith(".debug", 'N')
687                  .StartsWith(".sxdata", 'N')
688                  .Default('?');
689
690   if (Ret != '?')
691     return Ret;
692
693   uint32_t Characteristics = 0;
694   if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
695     section_iterator SecI = Obj.section_end();
696     if (error(SymI->getSection(SecI)))
697       return '?';
698     const coff_section *Section = Obj.getCOFFSection(*SecI);
699     Characteristics = Section->Characteristics;
700   }
701
702   switch (Symb.getSectionNumber()) {
703   case COFF::IMAGE_SYM_DEBUG:
704     return 'n';
705   default:
706     // Check section type.
707     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
708       return 't';
709     if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
710       return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
711     if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
712       return 'b';
713     if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
714       return 'i';
715     // Check for section symbol.
716     if (Symb.isSectionDefinition())
717       return 's';
718   }
719
720   return '?';
721 }
722
723 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
724   if (Obj.is64Bit()) {
725     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
726     return STE.n_type;
727   }
728   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
729   return STE.n_type;
730 }
731
732 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
733   DataRefImpl Symb = I->getRawDataRefImpl();
734   uint8_t NType = getNType(Obj, Symb);
735
736   if (NType & MachO::N_STAB)
737     return '-';
738
739   switch (NType & MachO::N_TYPE) {
740   case MachO::N_ABS:
741     return 's';
742   case MachO::N_INDR:
743     return 'i';
744   case MachO::N_SECT: {
745     section_iterator Sec = Obj.section_end();
746     Obj.getSymbolSection(Symb, Sec);
747     DataRefImpl Ref = Sec->getRawDataRefImpl();
748     StringRef SectionName;
749     Obj.getSectionName(Ref, SectionName);
750     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
751     if (SegmentName == "__TEXT" && SectionName == "__text")
752       return 't';
753     else if (SegmentName == "__DATA" && SectionName == "__data")
754       return 'd';
755     else if (SegmentName == "__DATA" && SectionName == "__bss")
756       return 'b';
757     else
758       return 's';
759   }
760   }
761
762   return '?';
763 }
764
765 static char getSymbolNMTypeChar(const GlobalValue &GV) {
766   if (GV.getType()->getElementType()->isFunctionTy())
767     return 't';
768   // FIXME: should we print 'b'? At the IR level we cannot be sure if this
769   // will be in bss or not, but we could approximate.
770   return 'd';
771 }
772
773 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
774   const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
775   if (!GV)
776     return 't';
777   return getSymbolNMTypeChar(*GV);
778 }
779
780 template <class ELFT>
781 static bool isELFObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
782   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
783
784   DataRefImpl Symb = I->getRawDataRefImpl();
785   const Elf_Sym *ESym = Obj.getSymbol(Symb);
786
787   return ESym->getType() == ELF::STT_OBJECT;
788 }
789
790 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
791   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(&Obj))
792     return isELFObject(*ELF, I);
793   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(&Obj))
794     return isELFObject(*ELF, I);
795   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(&Obj))
796     return isELFObject(*ELF, I);
797   if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(&Obj))
798     return isELFObject(*ELF, I);
799   return false;
800 }
801
802 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
803   uint32_t Symflags = I->getFlags();
804   if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
805     char Ret = isObject(Obj, I) ? 'v' : 'w';
806     if (!(Symflags & object::SymbolRef::SF_Undefined))
807       Ret = toupper(Ret);
808     return Ret;
809   }
810
811   if (Symflags & object::SymbolRef::SF_Undefined)
812     return 'U';
813
814   if (Symflags & object::SymbolRef::SF_Common)
815     return 'C';
816
817   char Ret = '?';
818   if (Symflags & object::SymbolRef::SF_Absolute)
819     Ret = 'a';
820   else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
821     Ret = getSymbolNMTypeChar(*IR, I);
822   else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
823     Ret = getSymbolNMTypeChar(*COFF, I);
824   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
825     Ret = getSymbolNMTypeChar(*MachO, I);
826   else
827     Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I);
828
829   if (Symflags & object::SymbolRef::SF_Global)
830     Ret = toupper(Ret);
831
832   return Ret;
833 }
834
835 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
836 // option to dump only those symbols from that section in a Mach-O file.
837 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
838 // to get the section number for that named section from the command line
839 // arguments. It returns the section number for that section in the Mach-O
840 // file or zero it is not present.
841 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
842   unsigned Nsect = 1;
843   for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
844        I != E; ++I) {
845     DataRefImpl Ref = I->getRawDataRefImpl();
846     StringRef SectionName;
847     Obj->getSectionName(Ref, SectionName);
848     StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
849     if (SegmentName == SegSect[0] && SectionName == SegSect[1])
850       return Nsect;
851     Nsect++;
852   }
853   return 0;
854 }
855
856 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
857 // option to dump only those symbols from that section in a Mach-O file.
858 // It is called once for each symbol in a Mach-O file from
859 // dumpSymbolNamesFromObject() and returns the section number for that symbol
860 // if it is in a section, else it returns 0.
861 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
862   DataRefImpl Symb = Sym.getRawDataRefImpl();
863   if (Obj.is64Bit()) {
864     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
865     if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
866       return STE.n_sect;
867     return 0;
868   }
869   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
870   if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
871     return STE.n_sect;
872   return 0;
873 }
874
875 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
876                                       std::string ArchiveName = std::string(),
877                                       std::string ArchitectureName =
878                                         std::string()) {
879   auto Symbols = Obj.symbols();
880   if (DynamicSyms) {
881     const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
882     if (!E) {
883       error("File format has no dynamic symbol table", Obj.getFileName());
884       return;
885     }
886     auto DynSymbols = E->getDynamicSymbolIterators();
887     Symbols =
888         make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end());
889   }
890   std::string NameBuffer;
891   raw_string_ostream OS(NameBuffer);
892   // If a "-s segname sectname" option was specified and this is a Mach-O
893   // file get the section number for that section in this object file.
894   unsigned int Nsect = 0;
895   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
896   if (SegSect.size() != 0 && MachO) {
897     Nsect = getNsectForSegSect(MachO);
898     // If this section is not in the object file no symbols are printed.
899     if (Nsect == 0)
900       return;
901   }
902   for (BasicSymbolRef Sym : Symbols) {
903     uint32_t SymFlags = Sym.getFlags();
904     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
905       continue;
906     if (WithoutAliases) {
907       if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) {
908         const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl());
909         if (GV && isa<GlobalAlias>(GV))
910           continue;
911       }
912     }
913     // If a "-s segname sectname" option was specified and this is a Mach-O
914     // file and this section appears in this file, Nsect will be non-zero then
915     // see if this symbol is a symbol from that section and if not skip it.
916     if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
917       continue;
918     NMSymbol S;
919     S.Size = 0;
920     S.Address = UnknownAddress;
921     if (PrintSize) {
922       if (isa<ELFObjectFileBase>(&Obj))
923         S.Size = ELFSymbolRef(Sym).getSize();
924     }
925     if (PrintAddress && isa<ObjectFile>(Obj)) {
926       if (error(SymbolRef(Sym).getAddress(S.Address)))
927         break;
928     }
929     S.TypeChar = getNMTypeChar(Obj, Sym);
930     if (error(Sym.printName(OS)))
931       break;
932     OS << '\0';
933     S.Symb = Sym.getRawDataRefImpl();
934     SymbolList.push_back(S);
935   }
936
937   OS.flush();
938   const char *P = NameBuffer.c_str();
939   for (unsigned I = 0; I < SymbolList.size(); ++I) {
940     SymbolList[I].Name = P;
941     P += strlen(P) + 1;
942   }
943
944   CurrentFilename = Obj.getFileName();
945   sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
946 }
947
948 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
949 // and if it is and there is a list of architecture flags is specified then
950 // check to make sure this Mach-O file is one of those architectures or all
951 // architectures was specificed.  If not then an error is generated and this
952 // routine returns false.  Else it returns true.
953 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
954   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
955
956   if (!MachO || ArchAll || ArchFlags.size() == 0)
957     return true;
958
959   MachO::mach_header H;
960   MachO::mach_header_64 H_64;
961   Triple T;
962   if (MachO->is64Bit()) {
963     H_64 = MachO->MachOObjectFile::getHeader64();
964     T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
965   } else {
966     H = MachO->MachOObjectFile::getHeader();
967     T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
968   }
969   if (std::none_of(
970           ArchFlags.begin(), ArchFlags.end(),
971           [&](const std::string &Name) { return Name == T.getArchName(); })) {
972     error("No architecture specified", Filename);
973     return false;
974   }
975   return true;
976 }
977
978 static void dumpSymbolNamesFromFile(std::string &Filename) {
979   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
980       MemoryBuffer::getFileOrSTDIN(Filename);
981   if (error(BufferOrErr.getError(), Filename))
982     return;
983
984   LLVMContext &Context = getGlobalContext();
985   ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
986       BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
987   if (error(BinaryOrErr.getError(), Filename))
988     return;
989   Binary &Bin = *BinaryOrErr.get();
990
991   if (Archive *A = dyn_cast<Archive>(&Bin)) {
992     if (ArchiveMap) {
993       Archive::symbol_iterator I = A->symbol_begin();
994       Archive::symbol_iterator E = A->symbol_end();
995       if (I != E) {
996         outs() << "Archive map\n";
997         for (; I != E; ++I) {
998           ErrorOr<Archive::child_iterator> C = I->getMember();
999           if (error(C.getError()))
1000             return;
1001           ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
1002           if (error(FileNameOrErr.getError()))
1003             return;
1004           StringRef SymName = I->getName();
1005           outs() << SymName << " in " << FileNameOrErr.get() << "\n";
1006         }
1007         outs() << "\n";
1008       }
1009     }
1010
1011     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1012          I != E; ++I) {
1013       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
1014       if (ChildOrErr.getError())
1015         continue;
1016       if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1017         if (!checkMachOAndArchFlags(O, Filename))
1018           return;
1019         if (!PrintFileName) {
1020           outs() << "\n";
1021           if (isa<MachOObjectFile>(O)) {
1022             outs() << Filename << "(" << O->getFileName() << ")";
1023           } else
1024             outs() << O->getFileName();
1025           outs() << ":\n";
1026         }
1027         dumpSymbolNamesFromObject(*O, false, Filename);
1028       }
1029     }
1030     return;
1031   }
1032   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1033     // If we have a list of architecture flags specified dump only those.
1034     if (!ArchAll && ArchFlags.size() != 0) {
1035       // Look for a slice in the universal binary that matches each ArchFlag.
1036       bool ArchFound;
1037       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1038         ArchFound = false;
1039         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1040                                                    E = UB->end_objects();
1041              I != E; ++I) {
1042           if (ArchFlags[i] == I->getArchTypeName()) {
1043             ArchFound = true;
1044             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1045                 I->getAsObjectFile();
1046             std::string ArchiveName;
1047             std::string ArchitectureName;
1048             ArchiveName.clear();
1049             ArchitectureName.clear();
1050             if (ObjOrErr) {
1051               ObjectFile &Obj = *ObjOrErr.get();
1052               if (ArchFlags.size() > 1) {
1053                 if (PrintFileName)
1054                   ArchitectureName = I->getArchTypeName();
1055                 else
1056                   outs() << "\n" << Obj.getFileName() << " (for architecture "
1057                          << I->getArchTypeName() << ")"
1058                          << ":\n";
1059               }
1060               dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1061                                         ArchitectureName);
1062             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1063                            I->getAsArchive()) {
1064               std::unique_ptr<Archive> &A = *AOrErr;
1065               for (Archive::child_iterator AI = A->child_begin(),
1066                                            AE = A->child_end();
1067                    AI != AE; ++AI) {
1068                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1069                     AI->getAsBinary(&Context);
1070                 if (ChildOrErr.getError())
1071                   continue;
1072                 if (SymbolicFile *O =
1073                         dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1074                   if (PrintFileName) {
1075                     ArchiveName = A->getFileName();
1076                     if (ArchFlags.size() > 1)
1077                       ArchitectureName = I->getArchTypeName();
1078                   } else {
1079                     outs() << "\n" << A->getFileName();
1080                     outs() << "(" << O->getFileName() << ")";
1081                     if (ArchFlags.size() > 1) {
1082                       outs() << " (for architecture " << I->getArchTypeName()
1083                              << ")";
1084                     }
1085                     outs() << ":\n";
1086                   }
1087                   dumpSymbolNamesFromObject(*O, false, ArchiveName,
1088                                             ArchitectureName);
1089                 }
1090               }
1091             }
1092           }
1093         }
1094         if (!ArchFound) {
1095           error(ArchFlags[i],
1096                 "file: " + Filename + " does not contain architecture");
1097           return;
1098         }
1099       }
1100       return;
1101     }
1102     // No architecture flags were specified so if this contains a slice that
1103     // matches the host architecture dump only that.
1104     if (!ArchAll) {
1105       StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1106       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1107                                                  E = UB->end_objects();
1108            I != E; ++I) {
1109         if (HostArchName == I->getArchTypeName()) {
1110           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1111           std::string ArchiveName;
1112           ArchiveName.clear();
1113           if (ObjOrErr) {
1114             ObjectFile &Obj = *ObjOrErr.get();
1115             dumpSymbolNamesFromObject(Obj, false);
1116           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1117                          I->getAsArchive()) {
1118             std::unique_ptr<Archive> &A = *AOrErr;
1119             for (Archive::child_iterator AI = A->child_begin(),
1120                                          AE = A->child_end();
1121                  AI != AE; ++AI) {
1122               ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1123                   AI->getAsBinary(&Context);
1124               if (ChildOrErr.getError())
1125                 continue;
1126               if (SymbolicFile *O =
1127                       dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1128                 if (PrintFileName)
1129                   ArchiveName = A->getFileName();
1130                 else
1131                   outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1132                          << ")"
1133                          << ":\n";
1134                 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1135               }
1136             }
1137           }
1138           return;
1139         }
1140       }
1141     }
1142     // Either all architectures have been specified or none have been specified
1143     // and this does not contain the host architecture so dump all the slices.
1144     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1145     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1146                                                E = UB->end_objects();
1147          I != E; ++I) {
1148       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1149       std::string ArchiveName;
1150       std::string ArchitectureName;
1151       ArchiveName.clear();
1152       ArchitectureName.clear();
1153       if (ObjOrErr) {
1154         ObjectFile &Obj = *ObjOrErr.get();
1155         if (PrintFileName) {
1156           if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1157             ArchitectureName = I->getArchTypeName();
1158         } else {
1159           if (moreThanOneArch)
1160             outs() << "\n";
1161           outs() << Obj.getFileName();
1162           if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1163             outs() << " (for architecture " << I->getArchTypeName() << ")";
1164           outs() << ":\n";
1165         }
1166         dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1167       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1168         std::unique_ptr<Archive> &A = *AOrErr;
1169         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1170              AI != AE; ++AI) {
1171           ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1172               AI->getAsBinary(&Context);
1173           if (ChildOrErr.getError())
1174             continue;
1175           if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1176             if (PrintFileName) {
1177               ArchiveName = A->getFileName();
1178               if (isa<MachOObjectFile>(O) && moreThanOneArch)
1179                 ArchitectureName = I->getArchTypeName();
1180             } else {
1181               outs() << "\n" << A->getFileName();
1182               if (isa<MachOObjectFile>(O)) {
1183                 outs() << "(" << O->getFileName() << ")";
1184                 if (moreThanOneArch)
1185                   outs() << " (for architecture " << I->getArchTypeName()
1186                          << ")";
1187               } else
1188                 outs() << ":" << O->getFileName();
1189               outs() << ":\n";
1190             }
1191             dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
1192           }
1193         }
1194       }
1195     }
1196     return;
1197   }
1198   if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
1199     if (!checkMachOAndArchFlags(O, Filename))
1200       return;
1201     dumpSymbolNamesFromObject(*O, true);
1202     return;
1203   }
1204   error("unrecognizable file type", Filename);
1205   return;
1206 }
1207
1208 int main(int argc, char **argv) {
1209   // Print a stack trace if we signal out.
1210   sys::PrintStackTraceOnErrorSignal();
1211   PrettyStackTraceProgram X(argc, argv);
1212
1213   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1214   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1215
1216   // llvm-nm only reads binary files.
1217   if (error(sys::ChangeStdinToBinary()))
1218     return 1;
1219
1220   llvm::InitializeAllTargetInfos();
1221   llvm::InitializeAllTargetMCs();
1222   llvm::InitializeAllAsmParsers();
1223
1224   ToolName = argv[0];
1225   if (BSDFormat)
1226     OutputFormat = bsd;
1227   if (POSIXFormat)
1228     OutputFormat = posix;
1229   if (DarwinFormat)
1230     OutputFormat = darwin;
1231
1232   // The relative order of these is important. If you pass --size-sort it should
1233   // only print out the size. However, if you pass -S --size-sort, it should
1234   // print out both the size and address.
1235   if (SizeSort && !PrintSize)
1236     PrintAddress = false;
1237   if (OutputFormat == sysv || SizeSort)
1238     PrintSize = true;
1239
1240   switch (InputFilenames.size()) {
1241   case 0:
1242     InputFilenames.push_back("a.out");
1243   case 1:
1244     break;
1245   default:
1246     MultipleFiles = true;
1247   }
1248
1249   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1250     if (ArchFlags[i] == "all") {
1251       ArchAll = true;
1252     } else {
1253       if (!MachOObjectFile::isValidArch(ArchFlags[i]))
1254         error("Unknown architecture named '" + ArchFlags[i] + "'",
1255               "for the -arch option");
1256     }
1257   }
1258
1259   if (SegSect.size() != 0 && SegSect.size() != 2)
1260     error("bad number of arguments (must be two arguments)",
1261           "for the -s option");
1262
1263   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1264                 dumpSymbolNamesFromFile);
1265
1266   if (HadError)
1267     return 1;
1268
1269   return 0;
1270 }