de2b0450523465421fef87f6cceca8751c74f0ac
[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       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
431       if (std::error_code EC = ChildOrErr.getError()) {
432         errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
433         continue;
434       }
435       if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
436         MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
437         if (!checkMachOAndArchFlags(o, file))
438           return;
439         if (OutputFormat == sysv)
440           outs() << o->getFileName() << "   (ex " << a->getFileName() << "):\n";
441         else if (MachO && OutputFormat == darwin)
442           outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
443         PrintObjectSectionSizes(o);
444         if (OutputFormat == berkeley) {
445           if (MachO)
446             outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
447           else
448             outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
449         }
450       }
451     }
452   } else if (MachOUniversalBinary *UB =
453                  dyn_cast<MachOUniversalBinary>(&Bin)) {
454     // If we have a list of architecture flags specified dump only those.
455     if (!ArchAll && ArchFlags.size() != 0) {
456       // Look for a slice in the universal binary that matches each ArchFlag.
457       bool ArchFound;
458       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
459         ArchFound = false;
460         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
461                                                    E = UB->end_objects();
462              I != E; ++I) {
463           if (ArchFlags[i] == I->getArchTypeName()) {
464             ArchFound = true;
465             ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
466             if (UO) {
467               if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
468                 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
469                 if (OutputFormat == sysv)
470                   outs() << o->getFileName() << "  :\n";
471                 else if (MachO && OutputFormat == darwin) {
472                   if (moreThanOneFile || ArchFlags.size() > 1)
473                     outs() << o->getFileName() << " (for architecture "
474                            << I->getArchTypeName() << "): \n";
475                 }
476                 PrintObjectSectionSizes(o);
477                 if (OutputFormat == berkeley) {
478                   if (!MachO || moreThanOneFile || ArchFlags.size() > 1)
479                     outs() << o->getFileName() << " (for architecture "
480                            << I->getArchTypeName() << ")";
481                   outs() << "\n";
482                 }
483               }
484             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
485                            I->getAsArchive()) {
486               std::unique_ptr<Archive> &UA = *AOrErr;
487               // This is an archive. Iterate over each member and display its
488               // sizes.
489               for (object::Archive::child_iterator i = UA->child_begin(),
490                                                    e = UA->child_end();
491                    i != e; ++i) {
492                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
493                 if (std::error_code EC = ChildOrErr.getError()) {
494                   errs() << ToolName << ": " << file << ": " << EC.message()
495                          << ".\n";
496                   continue;
497                 }
498                 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
499                   MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
500                   if (OutputFormat == sysv)
501                     outs() << o->getFileName() << "   (ex " << UA->getFileName()
502                            << "):\n";
503                   else if (MachO && OutputFormat == darwin)
504                     outs() << UA->getFileName() << "(" << o->getFileName()
505                            << ")"
506                            << " (for architecture " << I->getArchTypeName()
507                            << "):\n";
508                   PrintObjectSectionSizes(o);
509                   if (OutputFormat == berkeley) {
510                     if (MachO) {
511                       outs() << UA->getFileName() << "(" << o->getFileName()
512                              << ")";
513                       if (ArchFlags.size() > 1)
514                         outs() << " (for architecture " << I->getArchTypeName()
515                                << ")";
516                       outs() << "\n";
517                     } else
518                       outs() << o->getFileName() << " (ex " << UA->getFileName()
519                              << ")\n";
520                   }
521                 }
522               }
523             }
524           }
525         }
526         if (!ArchFound) {
527           errs() << ToolName << ": file: " << file
528                  << " does not contain architecture" << ArchFlags[i] << ".\n";
529           return;
530         }
531       }
532       return;
533     }
534     // No architecture flags were specified so if this contains a slice that
535     // matches the host architecture dump only that.
536     if (!ArchAll) {
537       StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
538       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
539                                                  E = UB->end_objects();
540            I != E; ++I) {
541         if (HostArchName == I->getArchTypeName()) {
542           ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
543           if (UO) {
544             if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
545               MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
546               if (OutputFormat == sysv)
547                 outs() << o->getFileName() << "  :\n";
548               else if (MachO && OutputFormat == darwin) {
549                 if (moreThanOneFile)
550                   outs() << o->getFileName() << " (for architecture "
551                          << I->getArchTypeName() << "):\n";
552               }
553               PrintObjectSectionSizes(o);
554               if (OutputFormat == berkeley) {
555                 if (!MachO || moreThanOneFile)
556                   outs() << o->getFileName() << " (for architecture "
557                          << I->getArchTypeName() << ")";
558                 outs() << "\n";
559               }
560             }
561           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
562                          I->getAsArchive()) {
563             std::unique_ptr<Archive> &UA = *AOrErr;
564             // This is an archive. Iterate over each member and display its
565             // sizes.
566             for (object::Archive::child_iterator i = UA->child_begin(),
567                                                  e = UA->child_end();
568                  i != e; ++i) {
569               ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
570               if (std::error_code EC = ChildOrErr.getError()) {
571                 errs() << ToolName << ": " << file << ": " << EC.message()
572                        << ".\n";
573                 continue;
574               }
575               if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
576                 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
577                 if (OutputFormat == sysv)
578                   outs() << o->getFileName() << "   (ex " << UA->getFileName()
579                          << "):\n";
580                 else if (MachO && OutputFormat == darwin)
581                   outs() << UA->getFileName() << "(" << o->getFileName() << ")"
582                          << " (for architecture " << I->getArchTypeName()
583                          << "):\n";
584                 PrintObjectSectionSizes(o);
585                 if (OutputFormat == berkeley) {
586                   if (MachO)
587                     outs() << UA->getFileName() << "(" << o->getFileName()
588                            << ")\n";
589                   else
590                     outs() << o->getFileName() << " (ex " << UA->getFileName()
591                            << ")\n";
592                 }
593               }
594             }
595           }
596           return;
597         }
598       }
599     }
600     // Either all architectures have been specified or none have been specified
601     // and this does not contain the host architecture so dump all the slices.
602     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
603     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
604                                                E = UB->end_objects();
605          I != E; ++I) {
606       ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
607       if (UO) {
608         if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
609           MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
610           if (OutputFormat == sysv)
611             outs() << o->getFileName() << "  :\n";
612           else if (MachO && OutputFormat == darwin) {
613             if (moreThanOneFile || moreThanOneArch)
614               outs() << o->getFileName() << " (for architecture "
615                      << I->getArchTypeName() << "):";
616             outs() << "\n";
617           }
618           PrintObjectSectionSizes(o);
619           if (OutputFormat == berkeley) {
620             if (!MachO || moreThanOneFile || moreThanOneArch)
621               outs() << o->getFileName() << " (for architecture "
622                      << I->getArchTypeName() << ")";
623             outs() << "\n";
624           }
625         }
626       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
627                          I->getAsArchive()) {
628         std::unique_ptr<Archive> &UA = *AOrErr;
629         // This is an archive. Iterate over each member and display its sizes.
630         for (object::Archive::child_iterator i = UA->child_begin(),
631                                              e = UA->child_end();
632              i != e; ++i) {
633           ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
634           if (std::error_code EC = ChildOrErr.getError()) {
635             errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
636             continue;
637           }
638           if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
639             MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
640             if (OutputFormat == sysv)
641               outs() << o->getFileName() << "   (ex " << UA->getFileName()
642                      << "):\n";
643             else if (MachO && OutputFormat == darwin)
644               outs() << UA->getFileName() << "(" << o->getFileName() << ")"
645                      << " (for architecture " << I->getArchTypeName() << "):\n";
646             PrintObjectSectionSizes(o);
647             if (OutputFormat == berkeley) {
648               if (MachO)
649                 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
650                        << " (for architecture " << I->getArchTypeName()
651                        << ")\n";
652               else
653                 outs() << o->getFileName() << " (ex " << UA->getFileName()
654                        << ")\n";
655             }
656           }
657         }
658       }
659     }
660   } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) {
661     if (!checkMachOAndArchFlags(o, file))
662       return;
663     if (OutputFormat == sysv)
664       outs() << o->getFileName() << "  :\n";
665     PrintObjectSectionSizes(o);
666     if (OutputFormat == berkeley) {
667       MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
668       if (!MachO || moreThanOneFile)
669         outs() << o->getFileName();
670       outs() << "\n";
671     }
672   } else {
673     errs() << ToolName << ": " << file << ": "
674            << "Unrecognized file type.\n";
675   }
676   // System V adds an extra newline at the end of each file.
677   if (OutputFormat == sysv)
678     outs() << "\n";
679 }
680
681 int main(int argc, char **argv) {
682   // Print a stack trace if we signal out.
683   sys::PrintStackTraceOnErrorSignal();
684   PrettyStackTraceProgram X(argc, argv);
685
686   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
687   cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
688
689   ToolName = argv[0];
690   if (OutputFormatShort.getNumOccurrences())
691     OutputFormat = static_cast<OutputFormatTy>(OutputFormatShort);
692   if (RadixShort.getNumOccurrences())
693     Radix = RadixShort;
694
695   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
696     if (ArchFlags[i] == "all") {
697       ArchAll = true;
698     } else {
699       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
700         outs() << ToolName << ": for the -arch option: Unknown architecture "
701                << "named '" << ArchFlags[i] << "'";
702         return 1;
703       }
704     }
705   }
706
707   if (InputFilenames.size() == 0)
708     InputFilenames.push_back("a.out");
709
710   moreThanOneFile = InputFilenames.size() > 1;
711   std::for_each(InputFilenames.begin(), InputFilenames.end(),
712                 PrintFileSectionSizes);
713
714   return 0;
715 }