This removes the eating of the error in Archive::Child::getSize() when the characters
[oota-llvm.git] / tools / llvm-size / llvm-size.cpp
1 //===-- llvm-size.cpp - Print the size of each object section -------------===//
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 "size",
11 // that is, it prints out the size of each section, and the total size of all
12 // sections.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Object/MachOUniversal.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <string>
32 #include <system_error>
33 using namespace llvm;
34 using namespace object;
35
36 enum OutputFormatTy { berkeley, sysv, darwin };
37 static cl::opt<OutputFormatTy>
38 OutputFormat("format", cl::desc("Specify output format"),
39              cl::values(clEnumVal(sysv, "System V format"),
40                         clEnumVal(berkeley, "Berkeley format"),
41                         clEnumVal(darwin, "Darwin -m format"), clEnumValEnd),
42              cl::init(berkeley));
43
44 static cl::opt<OutputFormatTy> OutputFormatShort(
45     cl::desc("Specify output format"),
46     cl::values(clEnumValN(sysv, "A", "System V format"),
47                clEnumValN(berkeley, "B", "Berkeley format"),
48                clEnumValN(darwin, "m", "Darwin -m format"), clEnumValEnd),
49     cl::init(berkeley));
50
51 static bool berkeleyHeaderPrinted = false;
52 static bool moreThanOneFile = false;
53
54 cl::opt<bool>
55 DarwinLongFormat("l", cl::desc("When format is darwin, use long format "
56                                "to include addresses and offsets."));
57
58 static cl::list<std::string>
59 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
60           cl::ZeroOrMore);
61 bool ArchAll = false;
62
63 enum RadixTy { octal = 8, decimal = 10, hexadecimal = 16 };
64 static cl::opt<unsigned int>
65 Radix("-radix", cl::desc("Print size in radix. Only 8, 10, and 16 are valid"),
66       cl::init(decimal));
67
68 static cl::opt<RadixTy>
69 RadixShort(cl::desc("Print size in radix:"),
70            cl::values(clEnumValN(octal, "o", "Print size in octal"),
71                       clEnumValN(decimal, "d", "Print size in decimal"),
72                       clEnumValN(hexadecimal, "x", "Print size in hexadecimal"),
73                       clEnumValEnd),
74            cl::init(decimal));
75
76 static cl::list<std::string>
77 InputFilenames(cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
78
79 static std::string ToolName;
80
81 ///  @brief If ec is not success, print the error and return true.
82 static bool error(std::error_code ec) {
83   if (!ec)
84     return false;
85
86   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
87   outs().flush();
88   return true;
89 }
90
91 /// @brief Get the length of the string that represents @p num in Radix
92 ///        including the leading 0x or 0 for hexadecimal and octal respectively.
93 static size_t getNumLengthAsString(uint64_t num) {
94   APInt conv(64, num);
95   SmallString<32> result;
96   conv.toString(result, Radix, false, true);
97   return result.size();
98 }
99
100 /// @brief Return the printing format for the Radix.
101 static const char *getRadixFmt(void) {
102   switch (Radix) {
103   case octal:
104     return PRIo64;
105   case decimal:
106     return PRIu64;
107   case hexadecimal:
108     return PRIx64;
109   }
110   return nullptr;
111 }
112
113 /// @brief Print the size of each Mach-O segment and section in @p MachO.
114 ///
115 /// This is when used when @c OutputFormat is darwin and produces the same
116 /// output as darwin's size(1) -m output.
117 static void PrintDarwinSectionSizes(MachOObjectFile *MachO) {
118   std::string fmtbuf;
119   raw_string_ostream fmt(fmtbuf);
120   const char *radix_fmt = getRadixFmt();
121   if (Radix == hexadecimal)
122     fmt << "0x";
123   fmt << "%" << radix_fmt;
124
125   uint32_t Filetype = MachO->getHeader().filetype;
126
127   uint64_t total = 0;
128   for (const auto &Load : MachO->load_commands()) {
129     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
130       MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
131       outs() << "Segment " << Seg.segname << ": "
132              << format(fmt.str().c_str(), Seg.vmsize);
133       if (DarwinLongFormat)
134         outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff "
135                << Seg.fileoff << ")";
136       outs() << "\n";
137       total += Seg.vmsize;
138       uint64_t sec_total = 0;
139       for (unsigned J = 0; J < Seg.nsects; ++J) {
140         MachO::section_64 Sec = MachO->getSection64(Load, J);
141         if (Filetype == MachO::MH_OBJECT)
142           outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
143                  << format("%.16s", &Sec.sectname) << "): ";
144         else
145           outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
146         outs() << format(fmt.str().c_str(), Sec.size);
147         if (DarwinLongFormat)
148           outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset "
149                  << Sec.offset << ")";
150         outs() << "\n";
151         sec_total += Sec.size;
152       }
153       if (Seg.nsects != 0)
154         outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
155     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
156       MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
157       outs() << "Segment " << Seg.segname << ": "
158              << format(fmt.str().c_str(), Seg.vmsize);
159       if (DarwinLongFormat)
160         outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff "
161                << Seg.fileoff << ")";
162       outs() << "\n";
163       total += Seg.vmsize;
164       uint64_t sec_total = 0;
165       for (unsigned J = 0; J < Seg.nsects; ++J) {
166         MachO::section Sec = MachO->getSection(Load, J);
167         if (Filetype == MachO::MH_OBJECT)
168           outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
169                  << format("%.16s", &Sec.sectname) << "): ";
170         else
171           outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
172         outs() << format(fmt.str().c_str(), Sec.size);
173         if (DarwinLongFormat)
174           outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset "
175                  << Sec.offset << ")";
176         outs() << "\n";
177         sec_total += Sec.size;
178       }
179       if (Seg.nsects != 0)
180         outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
181     }
182   }
183   outs() << "total " << format(fmt.str().c_str(), total) << "\n";
184 }
185
186 /// @brief Print the summary sizes of the standard Mach-O segments in @p MachO.
187 ///
188 /// This is when used when @c OutputFormat is berkeley with a Mach-O file and
189 /// produces the same output as darwin's size(1) default output.
190 static void PrintDarwinSegmentSizes(MachOObjectFile *MachO) {
191   uint64_t total_text = 0;
192   uint64_t total_data = 0;
193   uint64_t total_objc = 0;
194   uint64_t total_others = 0;
195   for (const auto &Load : MachO->load_commands()) {
196     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
197       MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
198       if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
199         for (unsigned J = 0; J < Seg.nsects; ++J) {
200           MachO::section_64 Sec = MachO->getSection64(Load, J);
201           StringRef SegmentName = StringRef(Sec.segname);
202           if (SegmentName == "__TEXT")
203             total_text += Sec.size;
204           else if (SegmentName == "__DATA")
205             total_data += Sec.size;
206           else if (SegmentName == "__OBJC")
207             total_objc += Sec.size;
208           else
209             total_others += Sec.size;
210         }
211       } else {
212         StringRef SegmentName = StringRef(Seg.segname);
213         if (SegmentName == "__TEXT")
214           total_text += Seg.vmsize;
215         else if (SegmentName == "__DATA")
216           total_data += Seg.vmsize;
217         else if (SegmentName == "__OBJC")
218           total_objc += Seg.vmsize;
219         else
220           total_others += Seg.vmsize;
221       }
222     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
223       MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
224       if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
225         for (unsigned J = 0; J < Seg.nsects; ++J) {
226           MachO::section Sec = MachO->getSection(Load, J);
227           StringRef SegmentName = StringRef(Sec.segname);
228           if (SegmentName == "__TEXT")
229             total_text += Sec.size;
230           else if (SegmentName == "__DATA")
231             total_data += Sec.size;
232           else if (SegmentName == "__OBJC")
233             total_objc += Sec.size;
234           else
235             total_others += Sec.size;
236         }
237       } else {
238         StringRef SegmentName = StringRef(Seg.segname);
239         if (SegmentName == "__TEXT")
240           total_text += Seg.vmsize;
241         else if (SegmentName == "__DATA")
242           total_data += Seg.vmsize;
243         else if (SegmentName == "__OBJC")
244           total_objc += Seg.vmsize;
245         else
246           total_others += Seg.vmsize;
247       }
248     }
249   }
250   uint64_t total = total_text + total_data + total_objc + total_others;
251
252   if (!berkeleyHeaderPrinted) {
253     outs() << "__TEXT\t__DATA\t__OBJC\tothers\tdec\thex\n";
254     berkeleyHeaderPrinted = true;
255   }
256   outs() << total_text << "\t" << total_data << "\t" << total_objc << "\t"
257          << total_others << "\t" << total << "\t" << format("%" PRIx64, total)
258          << "\t";
259 }
260
261 /// @brief Print the size of each section in @p Obj.
262 ///
263 /// The format used is determined by @c OutputFormat and @c Radix.
264 static void PrintObjectSectionSizes(ObjectFile *Obj) {
265   uint64_t total = 0;
266   std::string fmtbuf;
267   raw_string_ostream fmt(fmtbuf);
268   const char *radix_fmt = getRadixFmt();
269
270   // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
271   // size(1) -m output, else if OutputFormat is darwin and not a Mach-O object
272   // let it fall through to OutputFormat berkeley.
273   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
274   if (OutputFormat == darwin && MachO)
275     PrintDarwinSectionSizes(MachO);
276   // If we have a MachOObjectFile and the OutputFormat is berkeley print as
277   // darwin's default berkeley format for Mach-O files.
278   else if (MachO && OutputFormat == berkeley)
279     PrintDarwinSegmentSizes(MachO);
280   else if (OutputFormat == sysv) {
281     // Run two passes over all sections. The first gets the lengths needed for
282     // formatting the output. The second actually does the output.
283     std::size_t max_name_len = strlen("section");
284     std::size_t max_size_len = strlen("size");
285     std::size_t max_addr_len = strlen("addr");
286     for (const SectionRef &Section : Obj->sections()) {
287       uint64_t size = Section.getSize();
288       total += size;
289
290       StringRef name;
291       if (error(Section.getName(name)))
292         return;
293       uint64_t addr = Section.getAddress();
294       max_name_len = std::max(max_name_len, name.size());
295       max_size_len = std::max(max_size_len, getNumLengthAsString(size));
296       max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr));
297     }
298
299     // Add extra padding.
300     max_name_len += 2;
301     max_size_len += 2;
302     max_addr_len += 2;
303
304     // Setup header format.
305     fmt << "%-" << max_name_len << "s "
306         << "%" << max_size_len << "s "
307         << "%" << max_addr_len << "s\n";
308
309     // Print header
310     outs() << format(fmt.str().c_str(), static_cast<const char *>("section"),
311                      static_cast<const char *>("size"),
312                      static_cast<const char *>("addr"));
313     fmtbuf.clear();
314
315     // Setup per section format.
316     fmt << "%-" << max_name_len << "s "
317         << "%#" << max_size_len << radix_fmt << " "
318         << "%#" << max_addr_len << radix_fmt << "\n";
319
320     // Print each section.
321     for (const SectionRef &Section : Obj->sections()) {
322       StringRef name;
323       if (error(Section.getName(name)))
324         return;
325       uint64_t size = Section.getSize();
326       uint64_t addr = Section.getAddress();
327       std::string namestr = name;
328
329       outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr);
330     }
331
332     // Print total.
333     fmtbuf.clear();
334     fmt << "%-" << max_name_len << "s "
335         << "%#" << max_size_len << radix_fmt << "\n";
336     outs() << format(fmt.str().c_str(), static_cast<const char *>("Total"),
337                      total);
338   } else {
339     // The Berkeley format does not display individual section sizes. It
340     // displays the cumulative size for each section type.
341     uint64_t total_text = 0;
342     uint64_t total_data = 0;
343     uint64_t total_bss = 0;
344
345     // Make one pass over the section table to calculate sizes.
346     for (const SectionRef &Section : Obj->sections()) {
347       uint64_t size = Section.getSize();
348       bool isText = Section.isText();
349       bool isData = Section.isData();
350       bool isBSS = Section.isBSS();
351       if (isText)
352         total_text += size;
353       else if (isData)
354         total_data += size;
355       else if (isBSS)
356         total_bss += size;
357     }
358
359     total = total_text + total_data + total_bss;
360
361     if (!berkeleyHeaderPrinted) {
362       outs() << "   text    data     bss     "
363              << (Radix == octal ? "oct" : "dec") << "     hex filename\n";
364       berkeleyHeaderPrinted = true;
365     }
366
367     // Print result.
368     fmt << "%#7" << radix_fmt << " "
369         << "%#7" << radix_fmt << " "
370         << "%#7" << radix_fmt << " ";
371     outs() << format(fmt.str().c_str(), total_text, total_data, total_bss);
372     fmtbuf.clear();
373     fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << " "
374         << "%7" PRIx64 " ";
375     outs() << format(fmt.str().c_str(), total, total);
376   }
377 }
378
379 /// @brief Checks to see if the @p o ObjectFile is a Mach-O file and if it is
380 ///        and there is a list of architecture flags specified then check to
381 ///        make sure this Mach-O file is one of those architectures or all
382 ///        architectures was specificed.  If not then an error is generated and
383 ///        this routine returns false.  Else it returns true.
384 static bool checkMachOAndArchFlags(ObjectFile *o, StringRef file) {
385   if (isa<MachOObjectFile>(o) && !ArchAll && ArchFlags.size() != 0) {
386     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
387     bool ArchFound = false;
388     MachO::mach_header H;
389     MachO::mach_header_64 H_64;
390     Triple T;
391     if (MachO->is64Bit()) {
392       H_64 = MachO->MachOObjectFile::getHeader64();
393       T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
394     } else {
395       H = MachO->MachOObjectFile::getHeader();
396       T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
397     }
398     unsigned i;
399     for (i = 0; i < ArchFlags.size(); ++i) {
400       if (ArchFlags[i] == T.getArchName())
401         ArchFound = true;
402       break;
403     }
404     if (!ArchFound) {
405       errs() << ToolName << ": file: " << file
406              << " does not contain architecture: " << ArchFlags[i] << ".\n";
407       return false;
408     }
409   }
410   return true;
411 }
412
413 /// @brief Print the section sizes for @p file. If @p file is an archive, print
414 ///        the section sizes for each archive member.
415 static void PrintFileSectionSizes(StringRef file) {
416
417   // Attempt to open the binary.
418   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
419   if (std::error_code EC = BinaryOrErr.getError()) {
420     errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
421     return;
422   }
423   Binary &Bin = *BinaryOrErr.get().getBinary();
424
425   if (Archive *a = dyn_cast<Archive>(&Bin)) {
426     // This is an archive. Iterate over each member and display its sizes.
427     for (object::Archive::child_iterator i = a->child_begin(),
428                                          e = a->child_end();
429          i != e; ++i) {
430       if (i->getError()) {
431         errs() << ToolName << ": " << file << ": " << i->getError().message()
432                << ".\n";
433         break;
434       }
435       auto &c = i->get();
436       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = c.getAsBinary();
437       if (std::error_code EC = ChildOrErr.getError()) {
438         errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
439         continue;
440       }
441       if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
442         MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
443         if (!checkMachOAndArchFlags(o, file))
444           return;
445         if (OutputFormat == sysv)
446           outs() << o->getFileName() << "   (ex " << a->getFileName() << "):\n";
447         else if (MachO && OutputFormat == darwin)
448           outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
449         PrintObjectSectionSizes(o);
450         if (OutputFormat == berkeley) {
451           if (MachO)
452             outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
453           else
454             outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
455         }
456       }
457     }
458   } else if (MachOUniversalBinary *UB =
459                  dyn_cast<MachOUniversalBinary>(&Bin)) {
460     // If we have a list of architecture flags specified dump only those.
461     if (!ArchAll && ArchFlags.size() != 0) {
462       // Look for a slice in the universal binary that matches each ArchFlag.
463       bool ArchFound;
464       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
465         ArchFound = false;
466         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
467                                                    E = UB->end_objects();
468              I != E; ++I) {
469           if (ArchFlags[i] == I->getArchTypeName()) {
470             ArchFound = true;
471             ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
472             if (UO) {
473               if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
474                 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
475                 if (OutputFormat == sysv)
476                   outs() << o->getFileName() << "  :\n";
477                 else if (MachO && OutputFormat == darwin) {
478                   if (moreThanOneFile || ArchFlags.size() > 1)
479                     outs() << o->getFileName() << " (for architecture "
480                            << I->getArchTypeName() << "): \n";
481                 }
482                 PrintObjectSectionSizes(o);
483                 if (OutputFormat == berkeley) {
484                   if (!MachO || moreThanOneFile || ArchFlags.size() > 1)
485                     outs() << o->getFileName() << " (for architecture "
486                            << I->getArchTypeName() << ")";
487                   outs() << "\n";
488                 }
489               }
490             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
491                            I->getAsArchive()) {
492               std::unique_ptr<Archive> &UA = *AOrErr;
493               // This is an archive. Iterate over each member and display its
494               // sizes.
495               for (object::Archive::child_iterator i = UA->child_begin(),
496                                                    e = UA->child_end();
497                    i != e; ++i) {
498                 if (std::error_code EC = i->getError()) {
499                   errs() << ToolName << ": " << file << ": " << EC.message()
500                          << ".\n";
501                   break;
502                 }
503                 auto &c = i->get();
504                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = c.getAsBinary();
505                 if (std::error_code EC = ChildOrErr.getError()) {
506                   errs() << ToolName << ": " << file << ": " << EC.message()
507                          << ".\n";
508                   continue;
509                 }
510                 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
511                   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
512                   if (OutputFormat == sysv)
513                     outs() << o->getFileName() << "   (ex " << UA->getFileName()
514                            << "):\n";
515                   else if (MachO && OutputFormat == darwin)
516                     outs() << UA->getFileName() << "(" << o->getFileName()
517                            << ")"
518                            << " (for architecture " << I->getArchTypeName()
519                            << "):\n";
520                   PrintObjectSectionSizes(o);
521                   if (OutputFormat == berkeley) {
522                     if (MachO) {
523                       outs() << UA->getFileName() << "(" << o->getFileName()
524                              << ")";
525                       if (ArchFlags.size() > 1)
526                         outs() << " (for architecture " << I->getArchTypeName()
527                                << ")";
528                       outs() << "\n";
529                     } else
530                       outs() << o->getFileName() << " (ex " << UA->getFileName()
531                              << ")\n";
532                   }
533                 }
534               }
535             }
536           }
537         }
538         if (!ArchFound) {
539           errs() << ToolName << ": file: " << file
540                  << " does not contain architecture" << ArchFlags[i] << ".\n";
541           return;
542         }
543       }
544       return;
545     }
546     // No architecture flags were specified so if this contains a slice that
547     // matches the host architecture dump only that.
548     if (!ArchAll) {
549       StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
550       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
551                                                  E = UB->end_objects();
552            I != E; ++I) {
553         if (HostArchName == I->getArchTypeName()) {
554           ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
555           if (UO) {
556             if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
557               MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
558               if (OutputFormat == sysv)
559                 outs() << o->getFileName() << "  :\n";
560               else if (MachO && OutputFormat == darwin) {
561                 if (moreThanOneFile)
562                   outs() << o->getFileName() << " (for architecture "
563                          << I->getArchTypeName() << "):\n";
564               }
565               PrintObjectSectionSizes(o);
566               if (OutputFormat == berkeley) {
567                 if (!MachO || moreThanOneFile)
568                   outs() << o->getFileName() << " (for architecture "
569                          << I->getArchTypeName() << ")";
570                 outs() << "\n";
571               }
572             }
573           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
574                          I->getAsArchive()) {
575             std::unique_ptr<Archive> &UA = *AOrErr;
576             // This is an archive. Iterate over each member and display its
577             // sizes.
578             for (object::Archive::child_iterator i = UA->child_begin(),
579                                                  e = UA->child_end();
580                  i != e; ++i) {
581               if (std::error_code EC = i->getError()) {
582                 errs() << ToolName << ": " << file << ": " << EC.message()
583                        << ".\n";
584                 break;
585               }
586               auto &c = i->get();
587               ErrorOr<std::unique_ptr<Binary>> ChildOrErr = c.getAsBinary();
588               if (std::error_code EC = ChildOrErr.getError()) {
589                 errs() << ToolName << ": " << file << ": " << EC.message()
590                        << ".\n";
591                 continue;
592               }
593               if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
594                 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
595                 if (OutputFormat == sysv)
596                   outs() << o->getFileName() << "   (ex " << UA->getFileName()
597                          << "):\n";
598                 else if (MachO && OutputFormat == darwin)
599                   outs() << UA->getFileName() << "(" << o->getFileName() << ")"
600                          << " (for architecture " << I->getArchTypeName()
601                          << "):\n";
602                 PrintObjectSectionSizes(o);
603                 if (OutputFormat == berkeley) {
604                   if (MachO)
605                     outs() << UA->getFileName() << "(" << o->getFileName()
606                            << ")\n";
607                   else
608                     outs() << o->getFileName() << " (ex " << UA->getFileName()
609                            << ")\n";
610                 }
611               }
612             }
613           }
614           return;
615         }
616       }
617     }
618     // Either all architectures have been specified or none have been specified
619     // and this does not contain the host architecture so dump all the slices.
620     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
621     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
622                                                E = UB->end_objects();
623          I != E; ++I) {
624       ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
625       if (UO) {
626         if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
627           MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
628           if (OutputFormat == sysv)
629             outs() << o->getFileName() << "  :\n";
630           else if (MachO && OutputFormat == darwin) {
631             if (moreThanOneFile || moreThanOneArch)
632               outs() << o->getFileName() << " (for architecture "
633                      << I->getArchTypeName() << "):";
634             outs() << "\n";
635           }
636           PrintObjectSectionSizes(o);
637           if (OutputFormat == berkeley) {
638             if (!MachO || moreThanOneFile || moreThanOneArch)
639               outs() << o->getFileName() << " (for architecture "
640                      << I->getArchTypeName() << ")";
641             outs() << "\n";
642           }
643         }
644       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
645                          I->getAsArchive()) {
646         std::unique_ptr<Archive> &UA = *AOrErr;
647         // This is an archive. Iterate over each member and display its sizes.
648         for (object::Archive::child_iterator i = UA->child_begin(),
649                                              e = UA->child_end();
650              i != e; ++i) {
651           if (std::error_code EC = i->getError()) {
652             errs() << ToolName << ": " << file << ": " << EC.message()
653                    << ".\n";
654             break;
655           }
656           auto &c = i->get();
657           ErrorOr<std::unique_ptr<Binary>> ChildOrErr = c.getAsBinary();
658           if (std::error_code EC = ChildOrErr.getError()) {
659             errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
660             continue;
661           }
662           if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
663             MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
664             if (OutputFormat == sysv)
665               outs() << o->getFileName() << "   (ex " << UA->getFileName()
666                      << "):\n";
667             else if (MachO && OutputFormat == darwin)
668               outs() << UA->getFileName() << "(" << o->getFileName() << ")"
669                      << " (for architecture " << I->getArchTypeName() << "):\n";
670             PrintObjectSectionSizes(o);
671             if (OutputFormat == berkeley) {
672               if (MachO)
673                 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
674                        << " (for architecture " << I->getArchTypeName()
675                        << ")\n";
676               else
677                 outs() << o->getFileName() << " (ex " << UA->getFileName()
678                        << ")\n";
679             }
680           }
681         }
682       }
683     }
684   } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) {
685     if (!checkMachOAndArchFlags(o, file))
686       return;
687     if (OutputFormat == sysv)
688       outs() << o->getFileName() << "  :\n";
689     PrintObjectSectionSizes(o);
690     if (OutputFormat == berkeley) {
691       MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
692       if (!MachO || moreThanOneFile)
693         outs() << o->getFileName();
694       outs() << "\n";
695     }
696   } else {
697     errs() << ToolName << ": " << file << ": "
698            << "Unrecognized file type.\n";
699   }
700   // System V adds an extra newline at the end of each file.
701   if (OutputFormat == sysv)
702     outs() << "\n";
703 }
704
705 int main(int argc, char **argv) {
706   // Print a stack trace if we signal out.
707   sys::PrintStackTraceOnErrorSignal();
708   PrettyStackTraceProgram X(argc, argv);
709
710   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
711   cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
712
713   ToolName = argv[0];
714   if (OutputFormatShort.getNumOccurrences())
715     OutputFormat = static_cast<OutputFormatTy>(OutputFormatShort);
716   if (RadixShort.getNumOccurrences())
717     Radix = RadixShort;
718
719   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
720     if (ArchFlags[i] == "all") {
721       ArchAll = true;
722     } else {
723       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
724         outs() << ToolName << ": for the -arch option: Unknown architecture "
725                << "named '" << ArchFlags[i] << "'";
726         return 1;
727       }
728     }
729   }
730
731   if (InputFilenames.size() == 0)
732     InputFilenames.push_back("a.out");
733
734   moreThanOneFile = InputFilenames.size() > 1;
735   std::for_each(InputFilenames.begin(), InputFilenames.end(),
736                 PrintFileSectionSizes);
737
738   return 0;
739 }