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