OSDN Git Service

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