1//===-- llvm-size.cpp - Print the size of each object section ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that works like traditional Unix "size",
10// that is, it prints out the size of each section, and the total size of all
11// sections.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/Object/Archive.h"
17#include "llvm/Object/ELFObjectFile.h"
18#include "llvm/Object/MachO.h"
19#include "llvm/Object/MachOUniversal.h"
20#include "llvm/Object/ObjectFile.h"
21#include "llvm/Option/Arg.h"
22#include "llvm/Option/ArgList.h"
23#include "llvm/Option/Option.h"
24#include "llvm/Support/Casting.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Driver.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/WithColor.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31#include <string>
32
33using namespace llvm;
34using namespace object;
35
36namespace {
37using namespace llvm::opt; // for HelpHidden in Opts.inc
38enum ID {
39 OPT_INVALID = 0, // This is not an option ID.
40#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
41#include "Opts.inc"
42#undef OPTION
43};
44
45#define OPTTABLE_CODE
46#include "Opts.inc"
47
48class SizeOptTable : public opt::OptTable {
49public:
50 SizeOptTable() : OptTable(optionTables()) { setGroupedShortOptions(true); }
51};
52
53enum OutputFormatTy { berkeley, sysv, darwin };
54enum RadixTy { octal = 8, decimal = 10, hexadecimal = 16 };
55} // namespace
56
57static bool ArchAll = false;
58static std::vector<StringRef> ArchFlags;
59static bool ELFCommons;
60static OutputFormatTy OutputFormat;
61static bool DarwinLongFormat;
62static RadixTy Radix = RadixTy::decimal;
63static bool TotalSizes;
64static bool HasMachOFiles = false;
65static bool ExcludePageZero = false;
66
67static std::vector<std::string> InputFilenames;
68
69static std::string ToolName;
70
71// States
72static bool HadError = false;
73static bool BerkeleyHeaderPrinted = false;
74static bool MoreThanOneFile = false;
75static uint64_t TotalObjectText = 0;
76static uint64_t TotalObjectData = 0;
77static uint64_t TotalObjectBss = 0;
78static uint64_t TotalObjectTotal = 0;
79
80// Darwin-specific totals
81static uint64_t TotalObjectObjc = 0;
82static uint64_t TotalObjectOthers = 0;
83
84static void error(const Twine &Message, StringRef File = "") {
85 HadError = true;
86 if (File.empty())
87 WithColor::error(OS&: errs(), Prefix: ToolName) << Message << '\n';
88 else
89 WithColor::error(OS&: errs(), Prefix: ToolName)
90 << "'" << File << "': " << Message << '\n';
91}
92
93// This version of error() prints the archive name and member name, for example:
94// "libx.a(foo.o)" after the ToolName before the error message. It sets
95// HadError but returns allowing the code to move on to other archive members.
96static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
97 StringRef ArchitectureName = StringRef()) {
98 HadError = true;
99 WithColor::error(OS&: errs(), Prefix: ToolName) << "'" << FileName << "'";
100
101 Expected<StringRef> NameOrErr = C.getName();
102 // TODO: if we have a error getting the name then it would be nice to print
103 // the index of which archive member this is and or its offset in the
104 // archive instead of "???" as the name.
105 if (!NameOrErr) {
106 consumeError(Err: NameOrErr.takeError());
107 errs() << "(" << "???" << ")";
108 } else
109 errs() << "(" << NameOrErr.get() << ")";
110
111 if (!ArchitectureName.empty())
112 errs() << " (for architecture " << ArchitectureName << ") ";
113
114 std::string Buf;
115 raw_string_ostream OS(Buf);
116 logAllUnhandledErrors(E: std::move(E), OS);
117 errs() << ": " << Buf << "\n";
118}
119
120// This version of error() prints the file name and which architecture slice it // is from, for example: "foo.o (for architecture i386)" after the ToolName
121// before the error message. It sets HadError but returns allowing the code to
122// move on to other architecture slices.
123static void error(llvm::Error E, StringRef FileName,
124 StringRef ArchitectureName = StringRef()) {
125 HadError = true;
126 WithColor::error(OS&: errs(), Prefix: ToolName) << "'" << FileName << "'";
127
128 if (!ArchitectureName.empty())
129 errs() << " (for architecture " << ArchitectureName << ") ";
130
131 std::string Buf;
132 raw_string_ostream OS(Buf);
133 logAllUnhandledErrors(E: std::move(E), OS);
134 errs() << ": " << Buf << "\n";
135}
136
137/// Get the length of the string that represents @p num in Radix including the
138/// leading 0x or 0 for hexadecimal and octal respectively.
139static size_t getNumLengthAsString(uint64_t num) {
140 APInt conv(64, num);
141 SmallString<32> result;
142 conv.toString(Str&: result, Radix, Signed: false, formatAsCLiteral: true);
143 return result.size();
144}
145
146/// Return the printing format for the Radix.
147static const char *getRadixFmt() {
148 switch (Radix) {
149 case octal:
150 return PRIo64;
151 case decimal:
152 return PRIu64;
153 case hexadecimal:
154 return PRIx64;
155 }
156 return nullptr;
157}
158
159/// Remove unneeded ELF sections from calculation
160static bool considerForSize(ObjectFile *Obj, SectionRef Section) {
161 if (!Obj->isELF())
162 return true;
163 switch (static_cast<ELFSectionRef>(Section).getType()) {
164 case ELF::SHT_NULL:
165 case ELF::SHT_SYMTAB:
166 return false;
167 case ELF::SHT_STRTAB:
168 case ELF::SHT_REL:
169 case ELF::SHT_RELA:
170 return static_cast<ELFSectionRef>(Section).getFlags() & ELF::SHF_ALLOC;
171 }
172 return true;
173}
174
175/// Total size of all ELF common symbols
176static Expected<uint64_t> getCommonSize(ObjectFile *Obj) {
177 uint64_t TotalCommons = 0;
178 for (auto &Sym : Obj->symbols()) {
179 Expected<uint32_t> SymFlagsOrErr =
180 Obj->getSymbolFlags(Symb: Sym.getRawDataRefImpl());
181 if (!SymFlagsOrErr)
182 return SymFlagsOrErr.takeError();
183 if (*SymFlagsOrErr & SymbolRef::SF_Common)
184 TotalCommons += Obj->getCommonSymbolSize(Symb: Sym.getRawDataRefImpl());
185 }
186 return TotalCommons;
187}
188
189/// Print the size of each Mach-O segment and section in @p MachO.
190///
191/// This is when used when @c OutputFormat is darwin and produces the same
192/// output as darwin's size(1) -m output.
193static void printDarwinSectionSizes(MachOObjectFile *MachO) {
194 std::string fmtbuf;
195 raw_string_ostream fmt(fmtbuf);
196 const char *radix_fmt = getRadixFmt();
197 if (Radix == hexadecimal)
198 fmt << "0x";
199 fmt << "%" << radix_fmt;
200
201 uint32_t Filetype = MachO->getHeader().filetype;
202
203 uint64_t total = 0;
204 for (const auto &Load : MachO->load_commands()) {
205 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
206 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(L: Load);
207 outs() << "Segment " << Seg.segname << ": "
208 << format(Fmt: fmtbuf.c_str(), Vals: Seg.vmsize);
209 if (DarwinLongFormat)
210 outs() << " (vmaddr 0x" << format(Fmt: "%" PRIx64, Vals: Seg.vmaddr) << " fileoff "
211 << Seg.fileoff << ")";
212 outs() << "\n";
213 total += Seg.vmsize;
214 uint64_t sec_total = 0;
215 for (unsigned J = 0; J < Seg.nsects; ++J) {
216 MachO::section_64 Sec = MachO->getSection64(L: Load, Index: J);
217 if (Filetype == MachO::MH_OBJECT)
218 outs() << "\tSection (" << format(Fmt: "%.16s", Vals: &Sec.segname) << ", "
219 << format(Fmt: "%.16s", Vals: &Sec.sectname) << "): ";
220 else
221 outs() << "\tSection " << format(Fmt: "%.16s", Vals: &Sec.sectname) << ": ";
222 outs() << format(Fmt: fmtbuf.c_str(), Vals: Sec.size);
223 if (DarwinLongFormat)
224 outs() << " (addr 0x" << format(Fmt: "%" PRIx64, Vals: Sec.addr) << " offset "
225 << Sec.offset << ")";
226 outs() << "\n";
227 sec_total += Sec.size;
228 }
229 if (Seg.nsects != 0)
230 outs() << "\ttotal " << format(Fmt: fmtbuf.c_str(), Vals: sec_total) << "\n";
231 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
232 MachO::segment_command Seg = MachO->getSegmentLoadCommand(L: Load);
233 uint64_t Seg_vmsize = Seg.vmsize;
234 outs() << "Segment " << Seg.segname << ": "
235 << format(Fmt: fmtbuf.c_str(), Vals: Seg_vmsize);
236 if (DarwinLongFormat)
237 outs() << " (vmaddr 0x" << format(Fmt: "%" PRIx32, Vals: Seg.vmaddr) << " fileoff "
238 << Seg.fileoff << ")";
239 outs() << "\n";
240 total += Seg.vmsize;
241 uint64_t sec_total = 0;
242 for (unsigned J = 0; J < Seg.nsects; ++J) {
243 MachO::section Sec = MachO->getSection(L: Load, Index: J);
244 if (Filetype == MachO::MH_OBJECT)
245 outs() << "\tSection (" << format(Fmt: "%.16s", Vals: &Sec.segname) << ", "
246 << format(Fmt: "%.16s", Vals: &Sec.sectname) << "): ";
247 else
248 outs() << "\tSection " << format(Fmt: "%.16s", Vals: &Sec.sectname) << ": ";
249 uint64_t Sec_size = Sec.size;
250 outs() << format(Fmt: fmtbuf.c_str(), Vals: Sec_size);
251 if (DarwinLongFormat)
252 outs() << " (addr 0x" << format(Fmt: "%" PRIx32, Vals: Sec.addr) << " offset "
253 << Sec.offset << ")";
254 outs() << "\n";
255 sec_total += Sec.size;
256 }
257 if (Seg.nsects != 0)
258 outs() << "\ttotal " << format(Fmt: fmtbuf.c_str(), Vals: sec_total) << "\n";
259 }
260 }
261 outs() << "total " << format(Fmt: fmtbuf.c_str(), Vals: total) << "\n";
262}
263
264/// Print the summary sizes of the standard Mach-O segments in @p MachO.
265///
266/// This is when used when @c OutputFormat is berkeley with a Mach-O file and
267/// produces the same output as darwin's size(1) default output.
268static void printDarwinSegmentSizes(MachOObjectFile *MachO) {
269 uint64_t total_text = 0;
270 uint64_t total_data = 0;
271 uint64_t total_objc = 0;
272 uint64_t total_others = 0;
273 HasMachOFiles = true;
274 for (const auto &Load : MachO->load_commands()) {
275 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
276 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(L: Load);
277 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
278 for (unsigned J = 0; J < Seg.nsects; ++J) {
279 MachO::section_64 Sec = MachO->getSection64(L: Load, Index: J);
280 StringRef SegmentName = StringRef(Sec.segname);
281 if (SegmentName == "__TEXT")
282 total_text += Sec.size;
283 else if (SegmentName == "__DATA")
284 total_data += Sec.size;
285 else if (SegmentName == "__OBJC")
286 total_objc += Sec.size;
287 else
288 total_others += Sec.size;
289 }
290 } else {
291 StringRef SegmentName = StringRef(Seg.segname);
292 if (SegmentName == "__TEXT")
293 total_text += Seg.vmsize;
294 else if (SegmentName == "__DATA")
295 total_data += Seg.vmsize;
296 else if (SegmentName == "__OBJC")
297 total_objc += Seg.vmsize;
298 else if (!ExcludePageZero || SegmentName != "__PAGEZERO")
299 total_others += Seg.vmsize;
300 }
301 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
302 MachO::segment_command Seg = MachO->getSegmentLoadCommand(L: Load);
303 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
304 for (unsigned J = 0; J < Seg.nsects; ++J) {
305 MachO::section Sec = MachO->getSection(L: Load, Index: J);
306 StringRef SegmentName = StringRef(Sec.segname);
307 if (SegmentName == "__TEXT")
308 total_text += Sec.size;
309 else if (SegmentName == "__DATA")
310 total_data += Sec.size;
311 else if (SegmentName == "__OBJC")
312 total_objc += Sec.size;
313 else
314 total_others += Sec.size;
315 }
316 } else {
317 StringRef SegmentName = StringRef(Seg.segname);
318 if (SegmentName == "__TEXT")
319 total_text += Seg.vmsize;
320 else if (SegmentName == "__DATA")
321 total_data += Seg.vmsize;
322 else if (SegmentName == "__OBJC")
323 total_objc += Seg.vmsize;
324 else if (!ExcludePageZero || SegmentName != "__PAGEZERO")
325 total_others += Seg.vmsize;
326 }
327 }
328 }
329 uint64_t total = total_text + total_data + total_objc + total_others;
330
331 if (TotalSizes) {
332 TotalObjectText += total_text;
333 TotalObjectData += total_data;
334 TotalObjectObjc += total_objc;
335 TotalObjectOthers += total_others;
336 TotalObjectTotal += total;
337 }
338
339 if (!BerkeleyHeaderPrinted) {
340 outs() << "__TEXT\t__DATA\t__OBJC\tothers\tdec\thex\n";
341 BerkeleyHeaderPrinted = true;
342 }
343 outs() << total_text << "\t" << total_data << "\t" << total_objc << "\t"
344 << total_others << "\t" << total << "\t" << format(Fmt: "%" PRIx64, Vals: total)
345 << "\t";
346}
347
348/// Print the size of each section in @p Obj.
349///
350/// The format used is determined by @c OutputFormat and @c Radix.
351static void printObjectSectionSizes(ObjectFile *Obj) {
352 uint64_t total = 0;
353 std::string fmtbuf;
354 raw_string_ostream fmt(fmtbuf);
355 const char *radix_fmt = getRadixFmt();
356
357 // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
358 // size(1) -m output, else if OutputFormat is darwin and not a Mach-O object
359 // let it fall through to OutputFormat berkeley.
360 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: Obj);
361 if (OutputFormat == darwin && MachO)
362 printDarwinSectionSizes(MachO);
363 // If we have a MachOObjectFile and the OutputFormat is berkeley print as
364 // darwin's default berkeley format for Mach-O files.
365 else if (MachO && OutputFormat == berkeley)
366 printDarwinSegmentSizes(MachO);
367 else if (OutputFormat == sysv) {
368 // Run two passes over all sections. The first gets the lengths needed for
369 // formatting the output. The second actually does the output.
370 std::size_t max_name_len = strlen(s: "section");
371 std::size_t max_size_len = strlen(s: "size");
372 std::size_t max_addr_len = strlen(s: "addr");
373 for (const SectionRef &Section : Obj->sections()) {
374 if (!considerForSize(Obj, Section))
375 continue;
376 uint64_t size = Section.getSize();
377 total += size;
378
379 Expected<StringRef> name_or_err = Section.getName();
380 if (!name_or_err) {
381 error(E: name_or_err.takeError(), FileName: Obj->getFileName());
382 return;
383 }
384
385 uint64_t addr = Section.getAddress();
386 max_name_len = std::max(a: max_name_len, b: name_or_err->size());
387 max_size_len = std::max(a: max_size_len, b: getNumLengthAsString(num: size));
388 max_addr_len = std::max(a: max_addr_len, b: getNumLengthAsString(num: addr));
389 }
390
391 // Add extra padding.
392 max_name_len += 2;
393 max_size_len += 2;
394 max_addr_len += 2;
395
396 // Setup header format.
397 fmt << "%-" << max_name_len << "s "
398 << "%" << max_size_len << "s "
399 << "%" << max_addr_len << "s\n";
400
401 // Print header
402 outs() << format(Fmt: fmtbuf.c_str(), Vals: static_cast<const char *>("section"),
403 Vals: static_cast<const char *>("size"),
404 Vals: static_cast<const char *>("addr"));
405 fmtbuf.clear();
406
407 // Setup per section format.
408 fmt << "%-" << max_name_len << "s "
409 << "%#" << max_size_len << radix_fmt << " "
410 << "%#" << max_addr_len << radix_fmt << "\n";
411
412 // Print each section.
413 for (const SectionRef &Section : Obj->sections()) {
414 if (!considerForSize(Obj, Section))
415 continue;
416
417 Expected<StringRef> name_or_err = Section.getName();
418 if (!name_or_err) {
419 error(E: name_or_err.takeError(), FileName: Obj->getFileName());
420 return;
421 }
422
423 uint64_t size = Section.getSize();
424 uint64_t addr = Section.getAddress();
425 outs() << format(Fmt: fmtbuf.c_str(), Vals: name_or_err->str().c_str(), Vals: size, Vals: addr);
426 }
427
428 if (ELFCommons) {
429 if (Expected<uint64_t> CommonSizeOrErr = getCommonSize(Obj)) {
430 total += *CommonSizeOrErr;
431 outs() << format(Fmt: fmtbuf.c_str(), Vals: std::string("*COM*").c_str(),
432 Vals: *CommonSizeOrErr, Vals: static_cast<uint64_t>(0));
433 } else {
434 error(E: CommonSizeOrErr.takeError(), FileName: Obj->getFileName());
435 return;
436 }
437 }
438
439 // Print total.
440 fmtbuf.clear();
441 fmt << "%-" << max_name_len << "s "
442 << "%#" << max_size_len << radix_fmt << "\n";
443 outs() << format(Fmt: fmtbuf.c_str(), Vals: static_cast<const char *>("Total"), Vals: total)
444 << "\n\n";
445 } else {
446 // The Berkeley format does not display individual section sizes. It
447 // displays the cumulative size for each section type.
448 uint64_t total_text = 0;
449 uint64_t total_data = 0;
450 uint64_t total_bss = 0;
451
452 // Make one pass over the section table to calculate sizes.
453 for (const SectionRef &Section : Obj->sections()) {
454 uint64_t size = Section.getSize();
455 bool isText = Section.isBerkeleyText();
456 bool isData = Section.isBerkeleyData();
457 bool isBSS = Section.isBSS();
458 if (isText)
459 total_text += size;
460 else if (isData)
461 total_data += size;
462 else if (isBSS)
463 total_bss += size;
464 }
465
466 if (ELFCommons) {
467 if (Expected<uint64_t> CommonSizeOrErr = getCommonSize(Obj))
468 total_bss += *CommonSizeOrErr;
469 else {
470 error(E: CommonSizeOrErr.takeError(), FileName: Obj->getFileName());
471 return;
472 }
473 }
474
475 total = total_text + total_data + total_bss;
476
477 if (TotalSizes) {
478 TotalObjectText += total_text;
479 TotalObjectData += total_data;
480 TotalObjectBss += total_bss;
481 TotalObjectTotal += total;
482 }
483
484 if (!BerkeleyHeaderPrinted) {
485 outs() << " text\t"
486 " data\t"
487 " bss\t"
488 " "
489 << (Radix == octal ? "oct" : "dec")
490 << "\t"
491 " hex\t"
492 "filename\n";
493 BerkeleyHeaderPrinted = true;
494 }
495
496 // Print result.
497 fmt << "%#7" << radix_fmt << "\t"
498 << "%#7" << radix_fmt << "\t"
499 << "%#7" << radix_fmt << "\t";
500 outs() << format(Fmt: fmtbuf.c_str(), Vals: total_text, Vals: total_data, Vals: total_bss);
501 fmtbuf.clear();
502 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
503 << "%7" PRIx64 "\t";
504 outs() << format(Fmt: fmtbuf.c_str(), Vals: total, Vals: total);
505 }
506}
507
508/// Checks to see if the @p O ObjectFile is a Mach-O file and if it is and there
509/// is a list of architecture flags specified then check to make sure this
510/// Mach-O file is one of those architectures or all architectures was
511/// specificed. If not then an error is generated and this routine returns
512/// false. Else it returns true.
513static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
514 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
515
516 if (!MachO || ArchAll || ArchFlags.empty())
517 return true;
518
519 MachO::mach_header H;
520 MachO::mach_header_64 H_64;
521 Triple T;
522 if (MachO->is64Bit()) {
523 H_64 = MachO->MachOObjectFile::getHeader64();
524 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype);
525 } else {
526 H = MachO->MachOObjectFile::getHeader();
527 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype);
528 }
529 if (!is_contained(Range&: ArchFlags, Element: T.getArchName())) {
530 error(Message: "no architecture specified", File: Filename);
531 return false;
532 }
533 return true;
534}
535
536/// Print the section sizes for @p file. If @p file is an archive, print the
537/// section sizes for each archive member.
538static void printFileSectionSizes(StringRef file) {
539
540 // Attempt to open the binary.
541 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path: file);
542 if (!BinaryOrErr) {
543 error(E: BinaryOrErr.takeError(), FileName: file);
544 return;
545 }
546 Binary &Bin = *BinaryOrErr.get().getBinary();
547
548 if (Archive *a = dyn_cast<Archive>(Val: &Bin)) {
549 // This is an archive. Iterate over each member and display its sizes.
550 Error Err = Error::success();
551 for (auto &C : a->children(Err)) {
552 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
553 if (!ChildOrErr) {
554 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
555 error(E: std::move(E), FileName: a->getFileName(), C);
556 continue;
557 }
558 if (ObjectFile *o = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
559 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
560 if (!checkMachOAndArchFlags(O: o, Filename: file))
561 return;
562 if (OutputFormat == sysv)
563 outs() << o->getFileName() << " (ex " << a->getFileName() << "):\n";
564 else if (MachO && OutputFormat == darwin)
565 outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
566 printObjectSectionSizes(Obj: o);
567 if (!MachO && OutputFormat == darwin)
568 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
569 if (OutputFormat == berkeley) {
570 if (MachO)
571 outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
572 else
573 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
574 }
575 }
576 }
577 if (Err)
578 error(E: std::move(Err), FileName: a->getFileName());
579 } else if (MachOUniversalBinary *UB =
580 dyn_cast<MachOUniversalBinary>(Val: &Bin)) {
581 // If we have a list of architecture flags specified dump only those.
582 if (!ArchAll && !ArchFlags.empty()) {
583 // Look for a slice in the universal binary that matches each ArchFlag.
584 bool ArchFound;
585 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
586 ArchFound = false;
587 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
588 E = UB->end_objects();
589 I != E; ++I) {
590 if (ArchFlags[i] == I->getArchFlagName()) {
591 ArchFound = true;
592 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
593 if (UO) {
594 ObjectFile *o = &*UO.get();
595 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
596 if (OutputFormat == sysv)
597 outs() << o->getFileName() << " :\n";
598 else if (MachO && OutputFormat == darwin) {
599 if (MoreThanOneFile || ArchFlags.size() > 1)
600 outs() << o->getFileName() << " (for architecture "
601 << I->getArchFlagName() << "): \n";
602 }
603 printObjectSectionSizes(Obj: o);
604 if (OutputFormat == berkeley) {
605 if (!MachO || MoreThanOneFile || ArchFlags.size() > 1)
606 outs() << o->getFileName() << " (for architecture "
607 << I->getArchFlagName() << ")";
608 outs() << "\n";
609 }
610 } else if (auto E = isNotObjectErrorInvalidFileType(
611 Err: UO.takeError())) {
612 error(E: std::move(E), FileName: file, ArchitectureName: ArchFlags.size() > 1 ?
613 StringRef(I->getArchFlagName()) : StringRef());
614 return;
615 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
616 I->getAsArchive()) {
617 std::unique_ptr<Archive> &UA = *AOrErr;
618 // This is an archive. Iterate over each member and display its
619 // sizes.
620 Error Err = Error::success();
621 for (auto &C : UA->children(Err)) {
622 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
623 if (!ChildOrErr) {
624 if (auto E = isNotObjectErrorInvalidFileType(
625 Err: ChildOrErr.takeError()))
626 error(E: std::move(E), FileName: UA->getFileName(), C,
627 ArchitectureName: ArchFlags.size() > 1 ?
628 StringRef(I->getArchFlagName()) : StringRef());
629 continue;
630 }
631 if (ObjectFile *o = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
632 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
633 if (OutputFormat == sysv)
634 outs() << o->getFileName() << " (ex " << UA->getFileName()
635 << "):\n";
636 else if (MachO && OutputFormat == darwin)
637 outs() << UA->getFileName() << "(" << o->getFileName()
638 << ")"
639 << " (for architecture " << I->getArchFlagName()
640 << "):\n";
641 printObjectSectionSizes(Obj: o);
642 if (OutputFormat == berkeley) {
643 if (MachO) {
644 outs() << UA->getFileName() << "(" << o->getFileName()
645 << ")";
646 if (ArchFlags.size() > 1)
647 outs() << " (for architecture " << I->getArchFlagName()
648 << ")";
649 outs() << "\n";
650 } else
651 outs() << o->getFileName() << " (ex " << UA->getFileName()
652 << ")\n";
653 }
654 }
655 }
656 if (Err)
657 error(E: std::move(Err), FileName: UA->getFileName());
658 } else {
659 consumeError(Err: AOrErr.takeError());
660 error(Message: "mach-o universal file for architecture " +
661 StringRef(I->getArchFlagName()) +
662 " is not a mach-o file or an archive file",
663 File: file);
664 }
665 }
666 }
667 if (!ArchFound) {
668 error(Message: "file does not contain architecture " + ArchFlags[i], File: file);
669 return;
670 }
671 }
672 return;
673 }
674 // No architecture flags were specified so if this contains a slice that
675 // matches the host architecture dump only that.
676 if (!ArchAll) {
677 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
678 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
679 E = UB->end_objects();
680 I != E; ++I) {
681 if (HostArchName == I->getArchFlagName()) {
682 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
683 if (UO) {
684 ObjectFile *o = &*UO.get();
685 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
686 if (OutputFormat == sysv)
687 outs() << o->getFileName() << " :\n";
688 else if (MachO && OutputFormat == darwin) {
689 if (MoreThanOneFile)
690 outs() << o->getFileName() << " (for architecture "
691 << I->getArchFlagName() << "):\n";
692 }
693 printObjectSectionSizes(Obj: o);
694 if (OutputFormat == berkeley) {
695 if (!MachO || MoreThanOneFile)
696 outs() << o->getFileName() << " (for architecture "
697 << I->getArchFlagName() << ")";
698 outs() << "\n";
699 }
700 } else if (auto E = isNotObjectErrorInvalidFileType(Err: UO.takeError())) {
701 error(E: std::move(E), FileName: file);
702 return;
703 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
704 I->getAsArchive()) {
705 std::unique_ptr<Archive> &UA = *AOrErr;
706 // This is an archive. Iterate over each member and display its
707 // sizes.
708 Error Err = Error::success();
709 for (auto &C : UA->children(Err)) {
710 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
711 if (!ChildOrErr) {
712 if (auto E = isNotObjectErrorInvalidFileType(
713 Err: ChildOrErr.takeError()))
714 error(E: std::move(E), FileName: UA->getFileName(), C);
715 continue;
716 }
717 if (ObjectFile *o = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
718 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
719 if (OutputFormat == sysv)
720 outs() << o->getFileName() << " (ex " << UA->getFileName()
721 << "):\n";
722 else if (MachO && OutputFormat == darwin)
723 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
724 << " (for architecture " << I->getArchFlagName()
725 << "):\n";
726 printObjectSectionSizes(Obj: o);
727 if (OutputFormat == berkeley) {
728 if (MachO)
729 outs() << UA->getFileName() << "(" << o->getFileName()
730 << ")\n";
731 else
732 outs() << o->getFileName() << " (ex " << UA->getFileName()
733 << ")\n";
734 }
735 }
736 }
737 if (Err)
738 error(E: std::move(Err), FileName: UA->getFileName());
739 } else {
740 consumeError(Err: AOrErr.takeError());
741 error(Message: "mach-o universal file for architecture " +
742 StringRef(I->getArchFlagName()) +
743 " is not a mach-o file or an archive file",
744 File: file);
745 }
746 return;
747 }
748 }
749 }
750 // Either all architectures have been specified or none have been specified
751 // and this does not contain the host architecture so dump all the slices.
752 bool MoreThanOneArch = UB->getNumberOfObjects() > 1;
753 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
754 E = UB->end_objects();
755 I != E; ++I) {
756 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
757 if (UO) {
758 ObjectFile *o = &*UO.get();
759 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
760 if (OutputFormat == sysv)
761 outs() << o->getFileName() << " :\n";
762 else if (MachO && OutputFormat == darwin) {
763 if (MoreThanOneFile || MoreThanOneArch)
764 outs() << o->getFileName() << " (for architecture "
765 << I->getArchFlagName() << "):";
766 outs() << "\n";
767 }
768 printObjectSectionSizes(Obj: o);
769 if (OutputFormat == berkeley) {
770 if (!MachO || MoreThanOneFile || MoreThanOneArch)
771 outs() << o->getFileName() << " (for architecture "
772 << I->getArchFlagName() << ")";
773 outs() << "\n";
774 }
775 } else if (auto E = isNotObjectErrorInvalidFileType(Err: UO.takeError())) {
776 error(E: std::move(E), FileName: file, ArchitectureName: MoreThanOneArch ?
777 StringRef(I->getArchFlagName()) : StringRef());
778 return;
779 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
780 I->getAsArchive()) {
781 std::unique_ptr<Archive> &UA = *AOrErr;
782 // This is an archive. Iterate over each member and display its sizes.
783 Error Err = Error::success();
784 for (auto &C : UA->children(Err)) {
785 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
786 if (!ChildOrErr) {
787 if (auto E = isNotObjectErrorInvalidFileType(
788 Err: ChildOrErr.takeError()))
789 error(E: std::move(E), FileName: UA->getFileName(), C, ArchitectureName: MoreThanOneArch ?
790 StringRef(I->getArchFlagName()) : StringRef());
791 continue;
792 }
793 if (ObjectFile *o = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
794 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
795 if (OutputFormat == sysv)
796 outs() << o->getFileName() << " (ex " << UA->getFileName()
797 << "):\n";
798 else if (MachO && OutputFormat == darwin)
799 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
800 << " (for architecture " << I->getArchFlagName() << "):\n";
801 printObjectSectionSizes(Obj: o);
802 if (OutputFormat == berkeley) {
803 if (MachO)
804 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
805 << " (for architecture " << I->getArchFlagName()
806 << ")\n";
807 else
808 outs() << o->getFileName() << " (ex " << UA->getFileName()
809 << ")\n";
810 }
811 }
812 }
813 if (Err)
814 error(E: std::move(Err), FileName: UA->getFileName());
815 } else {
816 consumeError(Err: AOrErr.takeError());
817 error(Message: "mach-o universal file for architecture " +
818 StringRef(I->getArchFlagName()) +
819 " is not a mach-o file or an archive file",
820 File: file);
821 }
822 }
823 } else if (ObjectFile *o = dyn_cast<ObjectFile>(Val: &Bin)) {
824 if (!checkMachOAndArchFlags(O: o, Filename: file))
825 return;
826 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o);
827 if (OutputFormat == sysv)
828 outs() << o->getFileName() << " :\n";
829 else if (MachO && OutputFormat == darwin && MoreThanOneFile)
830 outs() << o->getFileName() << ":\n";
831 printObjectSectionSizes(Obj: o);
832 if (!MachO && OutputFormat == darwin)
833 outs() << o->getFileName() << "\n";
834 if (OutputFormat == berkeley) {
835 if (!MachO || MoreThanOneFile)
836 outs() << o->getFileName();
837 outs() << "\n";
838 }
839 } else {
840 error(Message: "unsupported file type", File: file);
841 }
842}
843
844static void printBerkeleyTotals() {
845 std::string fmtbuf;
846 raw_string_ostream fmt(fmtbuf);
847 const char *radix_fmt = getRadixFmt();
848
849 if (HasMachOFiles) {
850 // Darwin format totals: __TEXT __DATA __OBJC others dec hex
851 outs() << TotalObjectText << "\t" << TotalObjectData << "\t"
852 << TotalObjectObjc << "\t" << TotalObjectOthers << "\t"
853 << TotalObjectTotal << "\t" << format(Fmt: "%" PRIx64, Vals: TotalObjectTotal)
854 << "\t(TOTALS)\n";
855 } else {
856 fmt << "%#7" << radix_fmt << "\t"
857 << "%#7" << radix_fmt << "\t"
858 << "%#7" << radix_fmt << "\t";
859 outs() << format(Fmt: fmtbuf.c_str(), Vals: TotalObjectText, Vals: TotalObjectData,
860 Vals: TotalObjectBss);
861 fmtbuf.clear();
862 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
863 << "%7" PRIx64 "\t";
864 outs() << format(Fmt: fmtbuf.c_str(), Vals: TotalObjectTotal, Vals: TotalObjectTotal)
865 << "(TOTALS)\n";
866 }
867}
868
869int llvm_size_main(int argc, char **argv, const llvm::ToolContext &) {
870 BumpPtrAllocator A;
871 StringSaver Saver(A);
872 SizeOptTable Tbl;
873 ToolName = argv[0];
874 opt::InputArgList Args =
875 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
876 error(Message: Msg);
877 exit(status: 1);
878 });
879 if (Args.hasArg(Ids: OPT_help)) {
880 Tbl.printHelp(
881 OS&: outs(),
882 Usage: (Twine(ToolName) + " [options] <input object files>").str().c_str(),
883 Title: "LLVM object size dumper");
884 // TODO Replace this with OptTable API once it adds extrahelp support.
885 outs() << "\nPass @FILE as argument to read options from FILE.\n";
886 return 0;
887 }
888 if (Args.hasArg(Ids: OPT_version)) {
889 outs() << ToolName << '\n';
890 cl::PrintVersionMessage();
891 return 0;
892 }
893
894 ELFCommons = Args.hasArg(Ids: OPT_common);
895 DarwinLongFormat = Args.hasArg(Ids: OPT_l);
896 ExcludePageZero = Args.hasArg(Ids: OPT_exclude_pagezero);
897 TotalSizes = Args.hasArg(Ids: OPT_totals);
898 StringRef V = Args.getLastArgValue(Id: OPT_format_EQ, Default: "berkeley");
899 if (V == "berkeley")
900 OutputFormat = berkeley;
901 else if (V == "darwin")
902 OutputFormat = darwin;
903 else if (V == "sysv")
904 OutputFormat = sysv;
905 else
906 error(Message: "--format value should be one of: 'berkeley', 'darwin', 'sysv'");
907 V = Args.getLastArgValue(Id: OPT_radix_EQ, Default: "10");
908 if (V == "8")
909 Radix = RadixTy::octal;
910 else if (V == "10")
911 Radix = RadixTy::decimal;
912 else if (V == "16")
913 Radix = RadixTy::hexadecimal;
914 else
915 error(Message: "--radix value should be one of: 8, 10, 16 ");
916
917 for (const auto *A : Args.filtered(Ids: OPT_arch_EQ)) {
918 SmallVector<StringRef, 2> Values;
919 llvm::SplitString(Source: A->getValue(), OutFragments&: Values, Delimiters: ",");
920 for (StringRef V : Values) {
921 if (V == "all")
922 ArchAll = true;
923 else if (MachOObjectFile::isValidArch(ArchFlag: V))
924 ArchFlags.push_back(x: V);
925 else {
926 outs() << ToolName << ": for the -arch option: Unknown architecture "
927 << "named '" << V << "'";
928 return 1;
929 }
930 }
931 }
932
933 InputFilenames = Args.getAllArgValues(Id: OPT_INPUT);
934 if (InputFilenames.empty())
935 InputFilenames.push_back(x: "a.out");
936
937 MoreThanOneFile = InputFilenames.size() > 1;
938 llvm::for_each(Range&: InputFilenames, F: printFileSectionSizes);
939 if (OutputFormat == berkeley && TotalSizes)
940 printBerkeleyTotals();
941
942 if (HadError)
943 return 1;
944 return 0;
945}
946