Correct the ownership passing semantics of object::createBinary and make them explici...
[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/raw_ostream.h"
40 #include "llvm/Support/TargetSelect.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 bool PrintAddress = true;
153
154 bool MultipleFiles = false;
155
156 bool HadError = false;
157
158 std::string ToolName;
159 }
160
161 static void error(Twine Message, Twine Path = Twine()) {
162   HadError = true;
163   errs() << ToolName << ": " << Path << ": " << Message << ".\n";
164 }
165
166 static bool error(std::error_code EC, Twine Path = Twine()) {
167   if (EC) {
168     error(EC.message(), Path);
169     return true;
170   }
171   return false;
172 }
173
174 namespace {
175 struct NMSymbol {
176   uint64_t Address;
177   uint64_t Size;
178   char TypeChar;
179   StringRef Name;
180   DataRefImpl Symb;
181 };
182 }
183
184 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
185   if (!ReverseSort) {
186     if (A.Address < B.Address)
187       return true;
188     else if (A.Address == B.Address && A.Name < B.Name)
189       return true;
190     else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
191       return true;
192     else
193       return false;
194   } else {
195     if (A.Address > B.Address)
196       return true;
197     else if (A.Address == B.Address && A.Name > B.Name)
198       return true;
199     else if (A.Address == B.Address && A.Name == B.Name && A.Size > B.Size)
200       return true;
201     else
202       return false;
203   }
204 }
205
206 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
207   if (!ReverseSort) {
208     if (A.Size < B.Size)
209       return true;
210     else if (A.Size == B.Size && A.Name < B.Name)
211       return true;
212     else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
213       return true;
214     else
215       return false;
216   } else {
217     if (A.Size > B.Size)
218       return true;
219     else if (A.Size == B.Size && A.Name > B.Name)
220       return true;
221     else if (A.Size == B.Size && A.Name == B.Name && A.Address > B.Address)
222       return true;
223     else
224       return false;
225   }
226 }
227
228 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
229   if (!ReverseSort) {
230     if (A.Name < B.Name)
231       return true;
232     else if (A.Name == B.Name && A.Size < B.Size)
233       return true;
234     else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
235       return true;
236     else
237       return false;
238   } else {
239     if (A.Name > B.Name)
240       return true;
241     else if (A.Name == B.Name && A.Size > B.Size)
242       return true;
243     else if (A.Name == B.Name && A.Size == B.Size && A.Address > B.Address)
244       return true;
245     else
246       return false;
247   }
248 }
249
250 static char isSymbolList64Bit(SymbolicFile *Obj) {
251   if (isa<IRObjectFile>(Obj))
252     return false;
253   else if (isa<COFFObjectFile>(Obj))
254     return false;
255   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
256     return MachO->is64Bit();
257   else if (isa<ELF32LEObjectFile>(Obj))
258     return false;
259   else if (isa<ELF64LEObjectFile>(Obj))
260     return true;
261   else if (isa<ELF32BEObjectFile>(Obj))
262     return false;
263   else if (isa<ELF64BEObjectFile>(Obj))
264     return true;
265   else
266     return false;
267 }
268
269 static StringRef CurrentFilename;
270 typedef std::vector<NMSymbol> SymbolListT;
271 static SymbolListT SymbolList;
272
273 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
274 // the OutputFormat is darwin or we are printing Mach-O symbols in hex.  For
275 // the darwin format it produces the same output as darwin's nm(1) -m output
276 // and when printing Mach-O symbols in hex it produces the same output as
277 // darwin's nm(1) -x format.
278 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
279                               char *SymbolAddrStr, const char *printBlanks) {
280   MachO::mach_header H;
281   MachO::mach_header_64 H_64;
282   uint32_t Filetype, Flags;
283   MachO::nlist_64 STE_64;
284   MachO::nlist STE;
285   uint8_t NType;
286   uint8_t NSect;
287   uint16_t NDesc;
288   uint32_t NStrx;
289   uint64_t NValue;
290   if (MachO->is64Bit()) {
291     H_64 = MachO->MachOObjectFile::getHeader64();
292     Filetype = H_64.filetype;
293     Flags = H_64.flags;
294     STE_64 = MachO->getSymbol64TableEntry(I->Symb);
295     NType = STE_64.n_type;
296     NSect = STE_64.n_sect;
297     NDesc = STE_64.n_desc;
298     NStrx = STE_64.n_strx;
299     NValue = STE_64.n_value;
300   } else {
301     H = MachO->MachOObjectFile::getHeader();
302     Filetype = H.filetype;
303     Flags = H.flags;
304     STE = MachO->getSymbolTableEntry(I->Symb);
305     NType = STE.n_type;
306     NSect = STE.n_sect;
307     NDesc = STE.n_desc;
308     NStrx = STE.n_strx;
309     NValue = STE.n_value;
310   }
311
312   // If we are printing Mach-O symbols in hex do that and return.
313   if (FormatMachOasHex) {
314     char Str[18] = "";
315     const char *printFormat;
316     if (MachO->is64Bit())
317       printFormat = "%016" PRIx64;
318     else
319       printFormat = "%08" PRIx64;
320     format(printFormat, NValue).print(Str, sizeof(Str));
321     outs() << Str << ' ';
322     format("%02x", NType).print(Str, sizeof(Str));
323     outs() << Str << ' ';
324     format("%02x", NSect).print(Str, sizeof(Str));
325     outs() << Str << ' ';
326     format("%04x", NDesc).print(Str, sizeof(Str));
327     outs() << Str << ' ';
328     format("%08x", NStrx).print(Str, sizeof(Str));
329     outs() << Str << ' ';
330     outs() << I->Name << "\n";
331     return;
332   }
333
334   if (PrintAddress) {
335     if ((NType & MachO::N_TYPE) == MachO::N_INDR)
336       strcpy(SymbolAddrStr, printBlanks);
337     outs() << SymbolAddrStr << ' ';
338   }
339
340   switch (NType & MachO::N_TYPE) {
341   case MachO::N_UNDF:
342     if (NValue != 0) {
343       outs() << "(common) ";
344       if (MachO::GET_COMM_ALIGN(NDesc) != 0)
345         outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
346     } else {
347       if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
348         outs() << "(prebound ";
349       else
350         outs() << "(";
351       if ((NDesc & MachO::REFERENCE_TYPE) ==
352           MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
353         outs() << "undefined [lazy bound]) ";
354       else if ((NDesc & MachO::REFERENCE_TYPE) ==
355                MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
356         outs() << "undefined [private lazy bound]) ";
357       else if ((NDesc & MachO::REFERENCE_TYPE) ==
358                MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
359         outs() << "undefined [private]) ";
360       else
361         outs() << "undefined) ";
362     }
363     break;
364   case MachO::N_ABS:
365     outs() << "(absolute) ";
366     break;
367   case MachO::N_INDR:
368     outs() << "(indirect) ";
369     break;
370   case MachO::N_SECT: {
371     section_iterator Sec = MachO->section_end();
372     MachO->getSymbolSection(I->Symb, Sec);
373     DataRefImpl Ref = Sec->getRawDataRefImpl();
374     StringRef SectionName;
375     MachO->getSectionName(Ref, SectionName);
376     StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
377     outs() << "(" << SegmentName << "," << SectionName << ") ";
378     break;
379   }
380   default:
381     outs() << "(?) ";
382     break;
383   }
384
385   if (NType & MachO::N_EXT) {
386     if (NDesc & MachO::REFERENCED_DYNAMICALLY)
387       outs() << "[referenced dynamically] ";
388     if (NType & MachO::N_PEXT) {
389       if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
390         outs() << "weak private external ";
391       else
392         outs() << "private external ";
393     } else {
394       if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
395           (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
396         if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
397             (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
398           outs() << "weak external automatically hidden ";
399         else
400           outs() << "weak external ";
401       } else
402         outs() << "external ";
403     }
404   } else {
405     if (NType & MachO::N_PEXT)
406       outs() << "non-external (was a private external) ";
407     else
408       outs() << "non-external ";
409   }
410
411   if (Filetype == MachO::MH_OBJECT &&
412       (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
413     outs() << "[no dead strip] ";
414
415   if (Filetype == MachO::MH_OBJECT &&
416       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
417       (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
418     outs() << "[symbol resolver] ";
419
420   if (Filetype == MachO::MH_OBJECT &&
421       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
422       (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
423     outs() << "[alt entry] ";
424
425   if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
426     outs() << "[Thumb] ";
427
428   if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
429     outs() << I->Name << " (for ";
430     StringRef IndirectName;
431     if (MachO->getIndirectName(I->Symb, IndirectName))
432       outs() << "?)";
433     else
434       outs() << IndirectName << ")";
435   } else
436     outs() << I->Name;
437
438   if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
439       (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
440        (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
441     uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
442     if (LibraryOrdinal != 0) {
443       if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
444         outs() << " (from executable)";
445       else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
446         outs() << " (dynamically looked up)";
447       else {
448         StringRef LibraryName;
449         if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
450           outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
451         else
452           outs() << " (from " << LibraryName << ")";
453       }
454     }
455   }
456
457   outs() << "\n";
458 }
459
460 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
461 struct DarwinStabName {
462   uint8_t NType;
463   const char *Name;
464 };
465 static const struct DarwinStabName DarwinStabNames[] = {
466     {MachO::N_GSYM, "GSYM"},
467     {MachO::N_FNAME, "FNAME"},
468     {MachO::N_FUN, "FUN"},
469     {MachO::N_STSYM, "STSYM"},
470     {MachO::N_LCSYM, "LCSYM"},
471     {MachO::N_BNSYM, "BNSYM"},
472     {MachO::N_PC, "PC"},
473     {MachO::N_AST, "AST"},
474     {MachO::N_OPT, "OPT"},
475     {MachO::N_RSYM, "RSYM"},
476     {MachO::N_SLINE, "SLINE"},
477     {MachO::N_ENSYM, "ENSYM"},
478     {MachO::N_SSYM, "SSYM"},
479     {MachO::N_SO, "SO"},
480     {MachO::N_OSO, "OSO"},
481     {MachO::N_LSYM, "LSYM"},
482     {MachO::N_BINCL, "BINCL"},
483     {MachO::N_SOL, "SOL"},
484     {MachO::N_PARAMS, "PARAM"},
485     {MachO::N_VERSION, "VERS"},
486     {MachO::N_OLEVEL, "OLEV"},
487     {MachO::N_PSYM, "PSYM"},
488     {MachO::N_EINCL, "EINCL"},
489     {MachO::N_ENTRY, "ENTRY"},
490     {MachO::N_LBRAC, "LBRAC"},
491     {MachO::N_EXCL, "EXCL"},
492     {MachO::N_RBRAC, "RBRAC"},
493     {MachO::N_BCOMM, "BCOMM"},
494     {MachO::N_ECOMM, "ECOMM"},
495     {MachO::N_ECOML, "ECOML"},
496     {MachO::N_LENG, "LENG"},
497     {0, 0}};
498 static const char *getDarwinStabString(uint8_t NType) {
499   for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
500     if (DarwinStabNames[i].NType == NType)
501       return DarwinStabNames[i].Name;
502   }
503   return 0;
504 }
505
506 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
507 // a stab n_type value in a Mach-O file.
508 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
509   MachO::nlist_64 STE_64;
510   MachO::nlist STE;
511   uint8_t NType;
512   uint8_t NSect;
513   uint16_t NDesc;
514   if (MachO->is64Bit()) {
515     STE_64 = MachO->getSymbol64TableEntry(I->Symb);
516     NType = STE_64.n_type;
517     NSect = STE_64.n_sect;
518     NDesc = STE_64.n_desc;
519   } else {
520     STE = MachO->getSymbolTableEntry(I->Symb);
521     NType = STE.n_type;
522     NSect = STE.n_sect;
523     NDesc = STE.n_desc;
524   }
525
526   char Str[18] = "";
527   format("%02x", NSect).print(Str, sizeof(Str));
528   outs() << ' ' << Str << ' ';
529   format("%04x", NDesc).print(Str, sizeof(Str));
530   outs() << Str << ' ';
531   if (const char *stabString = getDarwinStabString(NType))
532     format("%5.5s", stabString).print(Str, sizeof(Str));
533   else
534     format("   %02x", NType).print(Str, sizeof(Str));
535   outs() << Str;
536 }
537
538 static void sortAndPrintSymbolList(SymbolicFile *Obj, bool printName) {
539   if (!NoSort) {
540     if (NumericSort)
541       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
542     else if (SizeSort)
543       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
544     else
545       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
546   }
547
548   if (OutputFormat == posix && MultipleFiles && printName) {
549     outs() << '\n' << CurrentFilename << ":\n";
550   } else if (OutputFormat == bsd && MultipleFiles && printName) {
551     outs() << "\n" << CurrentFilename << ":\n";
552   } else if (OutputFormat == sysv) {
553     outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
554            << "Name                  Value   Class        Type"
555            << "         Size   Line  Section\n";
556   }
557
558   const char *printBlanks, *printFormat;
559   if (isSymbolList64Bit(Obj)) {
560     printBlanks = "                ";
561     printFormat = "%016" PRIx64;
562   } else {
563     printBlanks = "        ";
564     printFormat = "%08" PRIx64;
565   }
566
567   for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
568        I != E; ++I) {
569     if ((I->TypeChar != 'U') && UndefinedOnly)
570       continue;
571     if ((I->TypeChar == 'U') && DefinedOnly)
572       continue;
573     if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
574       continue;
575     if (JustSymbolName) {
576       outs() << I->Name << "\n";
577       continue;
578     }
579
580     char SymbolAddrStr[18] = "";
581     char SymbolSizeStr[18] = "";
582
583     if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
584       strcpy(SymbolAddrStr, printBlanks);
585     if (OutputFormat == sysv)
586       strcpy(SymbolSizeStr, printBlanks);
587
588     if (I->Address != UnknownAddressOrSize)
589       format(printFormat, I->Address)
590           .print(SymbolAddrStr, sizeof(SymbolAddrStr));
591     if (I->Size != UnknownAddressOrSize)
592       format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
593
594     // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
595     // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
596     // nm(1) -m output or hex, else if OutputFormat is darwin or we are
597     // printing Mach-O symbols in hex and not a Mach-O object fall back to
598     // OutputFormat bsd (see below).
599     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
600     if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
601       darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
602     } else if (OutputFormat == posix) {
603       outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
604              << SymbolSizeStr << "\n";
605     } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
606       if (PrintAddress)
607         outs() << SymbolAddrStr << ' ';
608       if (PrintSize) {
609         outs() << SymbolSizeStr;
610         if (I->Size != UnknownAddressOrSize)
611           outs() << ' ';
612       }
613       outs() << I->TypeChar;
614       if (I->TypeChar == '-' && MachO)
615         darwinPrintStab(MachO, I);
616       outs() << " " << I->Name << "\n";
617     } else if (OutputFormat == sysv) {
618       std::string PaddedName(I->Name);
619       while (PaddedName.length() < 20)
620         PaddedName += " ";
621       outs() << PaddedName << "|" << SymbolAddrStr << "|   " << I->TypeChar
622              << "  |                  |" << SymbolSizeStr << "|     |\n";
623     }
624   }
625
626   SymbolList.clear();
627 }
628
629 template <class ELFT>
630 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
631                                 basic_symbol_iterator I) {
632   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
633   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
634
635   // OK, this is ELF
636   symbol_iterator SymI(I);
637
638   DataRefImpl Symb = I->getRawDataRefImpl();
639   const Elf_Sym *ESym = Obj.getSymbol(Symb);
640   const ELFFile<ELFT> &EF = *Obj.getELFFile();
641   const Elf_Shdr *ESec = EF.getSection(ESym);
642
643   if (ESec) {
644     switch (ESec->sh_type) {
645     case ELF::SHT_PROGBITS:
646     case ELF::SHT_DYNAMIC:
647       switch (ESec->sh_flags) {
648       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
649         return 't';
650       case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
651       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
652         return 'd';
653       case ELF::SHF_ALLOC:
654       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
655       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
656         return 'r';
657       }
658       break;
659     case ELF::SHT_NOBITS:
660       return 'b';
661     }
662   }
663
664   if (ESym->getType() == ELF::STT_SECTION) {
665     StringRef Name;
666     if (error(SymI->getName(Name)))
667       return '?';
668     return StringSwitch<char>(Name)
669         .StartsWith(".debug", 'N')
670         .StartsWith(".note", 'n')
671         .Default('?');
672   }
673
674   return '?';
675 }
676
677 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
678   const coff_symbol *Symb = Obj.getCOFFSymbol(*I);
679   // OK, this is COFF.
680   symbol_iterator SymI(I);
681
682   StringRef Name;
683   if (error(SymI->getName(Name)))
684     return '?';
685
686   char Ret = StringSwitch<char>(Name)
687                  .StartsWith(".debug", 'N')
688                  .StartsWith(".sxdata", 'N')
689                  .Default('?');
690
691   if (Ret != '?')
692     return Ret;
693
694   uint32_t Characteristics = 0;
695   if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
696     section_iterator SecI = Obj.section_end();
697     if (error(SymI->getSection(SecI)))
698       return '?';
699     const coff_section *Section = Obj.getCOFFSection(*SecI);
700     Characteristics = Section->Characteristics;
701   }
702
703   switch (Symb->SectionNumber) {
704   case COFF::IMAGE_SYM_DEBUG:
705     return 'n';
706   default:
707     // Check section type.
708     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
709       return 't';
710     else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
711              ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
712       return 'r';
713     else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
714       return 'd';
715     else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
716       return 'b';
717     else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
718       return 'i';
719
720     // Check for section symbol.
721     else 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 isObject(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 isObject(*ELF, I);
798   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
799     return isObject(*ELF, I);
800   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
801     return isObject(*ELF, I);
802   if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
803     return isObject(*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   basic_symbol_iterator IBegin = Obj->symbol_begin();
888   basic_symbol_iterator IEnd = Obj->symbol_end();
889   if (DynamicSyms) {
890     if (!Obj->isELF()) {
891       error("File format has no dynamic symbol table", Obj->getFileName());
892       return;
893     }
894     std::pair<symbol_iterator, symbol_iterator> IDyn =
895         getELFDynamicSymbolIterators(Obj);
896     IBegin = IDyn.first;
897     IEnd = IDyn.second;
898   }
899   std::string NameBuffer;
900   raw_string_ostream OS(NameBuffer);
901   // If a "-s segname sectname" option was specified and this is a Mach-O
902   // file get the section number for that section in this object file.
903   unsigned int Nsect = 0;
904   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
905   if (SegSect.size() != 0 && MachO) {
906     Nsect = getNsectForSegSect(MachO);
907     // If this section is not in the object file no symbols are printed.
908     if (Nsect == 0)
909       return;
910   }
911   for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
912     uint32_t SymFlags = I->getFlags();
913     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
914       continue;
915     if (WithoutAliases) {
916       if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
917         const GlobalValue *GV = IR->getSymbolGV(I->getRawDataRefImpl());
918         if (GV && isa<GlobalAlias>(GV))
919           continue;
920       }
921     }
922     // If a "-s segname sectname" option was specified and this is a Mach-O
923     // file and this section appears in this file, Nsect will be non-zero then
924     // see if this symbol is a symbol from that section and if not skip it.
925     if (Nsect && Nsect != getNsectInMachO(*MachO, I))
926       continue;
927     NMSymbol S;
928     S.Size = UnknownAddressOrSize;
929     S.Address = UnknownAddressOrSize;
930     if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
931       symbol_iterator SymI = I;
932       if (error(SymI->getSize(S.Size)))
933         break;
934     }
935     if (PrintAddress && isa<ObjectFile>(Obj))
936       if (error(symbol_iterator(I)->getAddress(S.Address)))
937         break;
938     S.TypeChar = getNMTypeChar(Obj, I);
939     if (error(I->printName(OS)))
940       break;
941     OS << '\0';
942     S.Symb = I->getRawDataRefImpl();
943     SymbolList.push_back(S);
944   }
945
946   OS.flush();
947   const char *P = NameBuffer.c_str();
948   for (unsigned I = 0; I < SymbolList.size(); ++I) {
949     SymbolList[I].Name = P;
950     P += strlen(P) + 1;
951   }
952
953   CurrentFilename = Obj->getFileName();
954   sortAndPrintSymbolList(Obj, printName);
955 }
956
957 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
958 // and if it is and there is a list of architecture flags is specified then
959 // check to make sure this Mach-O file is one of those architectures or all
960 // architectures was specificed.  If not then an error is generated and this
961 // routine returns false.  Else it returns true.
962 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
963   if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
964     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
965     bool ArchFound = false;
966     MachO::mach_header H;
967     MachO::mach_header_64 H_64;
968     Triple T;
969     if (MachO->is64Bit()) {
970       H_64 = MachO->MachOObjectFile::getHeader64();
971       T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
972     } else {
973       H = MachO->MachOObjectFile::getHeader();
974       T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
975     }
976     unsigned i;
977     for (i = 0; i < ArchFlags.size(); ++i) {
978       if (ArchFlags[i] == T.getArchName())
979         ArchFound = true;
980       break;
981     }
982     if (!ArchFound) {
983       error(ArchFlags[i],
984             "file: " + Filename + " does not contain architecture");
985       return false;
986     }
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<Binary *> BinaryOrErr =
999       createBinary(std::move(*BufferOrErr), &Context);
1000   if (error(BinaryOrErr.getError(), Filename))
1001     return;
1002   std::unique_ptr<Binary> Bin(BinaryOrErr.get());
1003
1004   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
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         outs() << "\n";
1033         if (isa<MachOObjectFile>(O)) {
1034           outs() << Filename << "(" << O->getFileName() << ")";
1035         } else
1036           outs() << O->getFileName();
1037         outs() << ":\n";
1038         dumpSymbolNamesFromObject(O, false);
1039       }
1040     }
1041     return;
1042   }
1043   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
1044     // If we have a list of architecture flags specified dump only those.
1045     if (!ArchAll && ArchFlags.size() != 0) {
1046       // Look for a slice in the universal binary that matches each ArchFlag.
1047       bool ArchFound;
1048       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1049         ArchFound = false;
1050         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1051                                                    E = UB->end_objects();
1052              I != E; ++I) {
1053           if (ArchFlags[i] == I->getArchTypeName()) {
1054             ArchFound = true;
1055             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1056                 I->getAsObjectFile();
1057             std::unique_ptr<Archive> A;
1058             if (ObjOrErr) {
1059               std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1060               if (ArchFlags.size() > 1) {
1061                 outs() << "\n" << Obj->getFileName() << " (for architecture "
1062                        << I->getArchTypeName() << ")"
1063                        << ":\n";
1064               }
1065               dumpSymbolNamesFromObject(Obj.get(), false);
1066             } else if (!I->getAsArchive(A)) {
1067               for (Archive::child_iterator AI = A->child_begin(),
1068                                            AE = A->child_end();
1069                    AI != AE; ++AI) {
1070                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1071                     AI->getAsBinary(&Context);
1072                 if (ChildOrErr.getError())
1073                   continue;
1074                 if (SymbolicFile *O =
1075                         dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1076                   outs() << "\n" << A->getFileName();
1077                   outs() << "(" << O->getFileName() << ")";
1078                   if (ArchFlags.size() > 1) {
1079                     outs() << " (for architecture " << I->getArchTypeName()
1080                            << ")";
1081                   }
1082                   outs() << ":\n";
1083                   dumpSymbolNamesFromObject(O, false);
1084                 }
1085               }
1086             }
1087           }
1088         }
1089         if (!ArchFound) {
1090           error(ArchFlags[i],
1091                 "file: " + Filename + " does not contain architecture");
1092           return;
1093         }
1094       }
1095       return;
1096     }
1097     // No architecture flags were specified so if this contains a slice that
1098     // matches the host architecture dump only that.
1099     if (!ArchAll) {
1100       StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1101       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1102                                                  E = UB->end_objects();
1103            I != E; ++I) {
1104         if (HostArchName == I->getArchTypeName()) {
1105           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1106           std::unique_ptr<Archive> A;
1107           if (ObjOrErr) {
1108             std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1109             dumpSymbolNamesFromObject(Obj.get(), false);
1110           } else if (!I->getAsArchive(A)) {
1111             for (Archive::child_iterator AI = A->child_begin(),
1112                                          AE = A->child_end();
1113                  AI != AE; ++AI) {
1114               ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1115                   AI->getAsBinary(&Context);
1116               if (ChildOrErr.getError())
1117                 continue;
1118               if (SymbolicFile *O =
1119                       dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1120                 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1121                        << ")"
1122                        << ":\n";
1123                 dumpSymbolNamesFromObject(O, false);
1124               }
1125             }
1126           }
1127           return;
1128         }
1129       }
1130     }
1131     // Either all architectures have been specified or none have been specified
1132     // and this does not contain the host architecture so dump all the slices.
1133     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1134     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1135                                                E = UB->end_objects();
1136          I != E; ++I) {
1137       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1138       std::unique_ptr<Archive> A;
1139       if (ObjOrErr) {
1140         std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1141         if (moreThanOneArch)
1142           outs() << "\n";
1143         outs() << Obj->getFileName();
1144         if (isa<MachOObjectFile>(Obj.get()) && moreThanOneArch)
1145           outs() << " (for architecture " << I->getArchTypeName() << ")";
1146         outs() << ":\n";
1147         dumpSymbolNamesFromObject(Obj.get(), false);
1148       } else if (!I->getAsArchive(A)) {
1149         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1150              AI != AE; ++AI) {
1151           ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1152               AI->getAsBinary(&Context);
1153           if (ChildOrErr.getError())
1154             continue;
1155           if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1156             outs() << "\n" << A->getFileName();
1157             if (isa<MachOObjectFile>(O)) {
1158               outs() << "(" << O->getFileName() << ")";
1159               if (moreThanOneArch)
1160                 outs() << " (for architecture " << I->getArchTypeName() << ")";
1161             } else
1162               outs() << ":" << O->getFileName();
1163             outs() << ":\n";
1164             dumpSymbolNamesFromObject(O, false);
1165           }
1166         }
1167       }
1168     }
1169     return;
1170   }
1171   if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
1172     if (!checkMachOAndArchFlags(O, Filename))
1173       return;
1174     dumpSymbolNamesFromObject(O, true);
1175     return;
1176   }
1177   error("unrecognizable file type", Filename);
1178   return;
1179 }
1180
1181 int main(int argc, char **argv) {
1182   // Print a stack trace if we signal out.
1183   sys::PrintStackTraceOnErrorSignal();
1184   PrettyStackTraceProgram X(argc, argv);
1185
1186   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1187   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1188
1189   // llvm-nm only reads binary files.
1190   if (error(sys::ChangeStdinToBinary()))
1191     return 1;
1192
1193   llvm::InitializeAllTargetInfos();
1194   llvm::InitializeAllTargetMCs();
1195   llvm::InitializeAllAsmParsers();
1196
1197   ToolName = argv[0];
1198   if (BSDFormat)
1199     OutputFormat = bsd;
1200   if (POSIXFormat)
1201     OutputFormat = posix;
1202   if (DarwinFormat)
1203     OutputFormat = darwin;
1204
1205   // The relative order of these is important. If you pass --size-sort it should
1206   // only print out the size. However, if you pass -S --size-sort, it should
1207   // print out both the size and address.
1208   if (SizeSort && !PrintSize)
1209     PrintAddress = false;
1210   if (OutputFormat == sysv || SizeSort)
1211     PrintSize = true;
1212
1213   switch (InputFilenames.size()) {
1214   case 0:
1215     InputFilenames.push_back("a.out");
1216   case 1:
1217     break;
1218   default:
1219     MultipleFiles = true;
1220   }
1221
1222   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1223     if (ArchFlags[i] == "all") {
1224       ArchAll = true;
1225     } else {
1226       Triple T = MachOObjectFile::getArch(ArchFlags[i]);
1227       if (T.getArch() == Triple::UnknownArch)
1228         error("Unknown architecture named '" + ArchFlags[i] + "'",
1229               "for the -arch option");
1230     }
1231   }
1232
1233   if (SegSect.size() != 0 && SegSect.size() != 2)
1234     error("bad number of arguments (must be two arguments)",
1235           "for the -s option");
1236
1237   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1238                 dumpSymbolNamesFromFile);
1239
1240   if (HadError)
1241     return 1;
1242
1243   return 0;
1244 }