blob: da56199fe3c2428c9ba2cc94478e8fd655976cb8 [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===-- llvm-size.cpp - Print the size of each object section ---*- C++ -*-===//
Michael J. Spencerc4ad4662011-09-28 20:57:46 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Michael J. Spencerc4ad4662011-09-28 20:57:46 +00006//
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"
Rafael Espindolaa0ff5562016-02-09 21:39:49 +000017#include "llvm/Object/ELFObjectFile.h"
Kevin Enderby246a4602014-06-17 17:54:13 +000018#include "llvm/Object/MachO.h"
Kevin Enderby4b8fc282014-06-18 22:04:40 +000019#include "llvm/Object/MachOUniversal.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/Object/ObjectFile.h"
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000021#include "llvm/Support/Casting.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000025#include "llvm/Support/InitLLVM.h"
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000026#include "llvm/Support/MemoryBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000027#include "llvm/Support/raw_ostream.h"
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000028#include <algorithm>
29#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000030#include <system_error>
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000031
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000032using namespace llvm;
33using namespace object;
34
Serge Gueltondaeeb332019-06-05 10:32:28 +000035cl::OptionCategory SizeCat("llvm-size Options");
36
Kevin Enderby10769742014-07-01 22:26:31 +000037enum OutputFormatTy { berkeley, sysv, darwin };
Michael J. Spencercc5f8d42011-09-29 00:59:18 +000038static cl::opt<OutputFormatTy>
Serge Gueltondaeeb332019-06-05 10:32:28 +000039 OutputFormat("format", cl::desc("Specify output format"),
40 cl::values(clEnumVal(sysv, "System V format"),
41 clEnumVal(berkeley, "Berkeley format"),
42 clEnumVal(darwin, "Darwin -m format")),
43 cl::init(berkeley), cl::cat(SizeCat));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000044
Serge Gueltondaeeb332019-06-05 10:32:28 +000045static cl::opt<OutputFormatTy>
46 OutputFormatShort(cl::desc("Specify output format"),
47 cl::values(clEnumValN(sysv, "A", "System V format"),
48 clEnumValN(berkeley, "B", "Berkeley format"),
49 clEnumValN(darwin, "m", "Darwin -m format")),
50 cl::init(berkeley), cl::cat(SizeCat));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000051
Rafael Espindola1dc30a42016-02-09 21:35:14 +000052static bool BerkeleyHeaderPrinted = false;
53static bool MoreThanOneFile = false;
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +000054static uint64_t TotalObjectText = 0;
55static uint64_t TotalObjectData = 0;
56static uint64_t TotalObjectBss = 0;
57static uint64_t TotalObjectTotal = 0;
Kevin Enderby246a4602014-06-17 17:54:13 +000058
Kevin Enderby10769742014-07-01 22:26:31 +000059cl::opt<bool>
Serge Gueltondaeeb332019-06-05 10:32:28 +000060 DarwinLongFormat("l",
61 cl::desc("When format is darwin, use long format "
62 "to include addresses and offsets."),
63 cl::cat(SizeCat));
Kevin Enderby246a4602014-06-17 17:54:13 +000064
Hemant Kulkarni274457e2016-03-28 16:48:10 +000065cl::opt<bool>
66 ELFCommons("common",
67 cl::desc("Print common symbols in the ELF file. When using "
James Hendersoncd893e52019-09-13 12:00:42 +000068 "Berkeley format, this is added to bss."),
Serge Gueltondaeeb332019-06-05 10:32:28 +000069 cl::init(false), cl::cat(SizeCat));
Hemant Kulkarni274457e2016-03-28 16:48:10 +000070
Kevin Enderbyafef4c92014-07-01 17:19:10 +000071static cl::list<std::string>
Serge Gueltondaeeb332019-06-05 10:32:28 +000072 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
73 cl::ZeroOrMore, cl::cat(SizeCat));
Fangrui Song1e2d5cb2018-06-22 22:20:10 +000074static bool ArchAll = false;
Kevin Enderbyafef4c92014-07-01 17:19:10 +000075
Kevin Enderby10769742014-07-01 22:26:31 +000076enum RadixTy { octal = 8, decimal = 10, hexadecimal = 16 };
James Hendersonb3735ee2018-10-30 11:52:47 +000077static cl::opt<RadixTy> Radix(
78 "radix", cl::desc("Print size in radix"), cl::init(decimal),
79 cl::values(clEnumValN(octal, "8", "Print size in octal"),
80 clEnumValN(decimal, "10", "Print size in decimal"),
Serge Gueltondaeeb332019-06-05 10:32:28 +000081 clEnumValN(hexadecimal, "16", "Print size in hexadecimal")),
82 cl::cat(SizeCat));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000083
Serge Gueltondaeeb332019-06-05 10:32:28 +000084static cl::opt<RadixTy> RadixShort(
85 cl::desc("Print size in radix:"),
86 cl::values(clEnumValN(octal, "o", "Print size in octal"),
87 clEnumValN(decimal, "d", "Print size in decimal"),
88 clEnumValN(hexadecimal, "x", "Print size in hexadecimal")),
89 cl::init(decimal), cl::cat(SizeCat));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +000090
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +000091static cl::opt<bool>
92 TotalSizes("totals",
93 cl::desc("Print totals of all objects - Berkeley format only"),
Serge Gueltondaeeb332019-06-05 10:32:28 +000094 cl::init(false), cl::cat(SizeCat));
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +000095
96static cl::alias TotalSizesShort("t", cl::desc("Short for --totals"),
97 cl::aliasopt(TotalSizes));
98
Michael J. Spencercc5f8d42011-09-29 00:59:18 +000099static cl::list<std::string>
Serge Gueltondaeeb332019-06-05 10:32:28 +0000100 InputFilenames(cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000101
James Henderson9485b262019-06-21 11:49:20 +0000102static cl::extrahelp
103 HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
104
Fangrui Song1e2d5cb2018-06-22 22:20:10 +0000105static bool HadError = false;
Kevin Enderby64f7a992016-05-02 21:41:03 +0000106
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000107static std::string ToolName;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000108
Kevin Enderby42398052016-06-28 23:16:13 +0000109static bool error(Twine Message) {
110 HadError = true;
111 errs() << ToolName << ": " << Message << ".\n";
112 errs().flush();
113 return true;
114}
115
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000116// This version of error() prints the archive name and member name, for example:
117// "libx.a(foo.o)" after the ToolName before the error message. It sets
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000118// HadError but returns allowing the code to move on to other archive members.
Kevin Enderby9acb1092016-05-31 20:35:34 +0000119static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
120 StringRef ArchitectureName = StringRef()) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000121 HadError = true;
122 errs() << ToolName << ": " << FileName;
123
Kevin Enderbyf4586032016-07-29 17:44:13 +0000124 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000125 // TODO: if we have a error getting the name then it would be nice to print
126 // the index of which archive member this is and or its offset in the
127 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000128 if (!NameOrErr) {
129 consumeError(NameOrErr.takeError());
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000130 errs() << "(" << "???" << ")";
Kevin Enderbyf4586032016-07-29 17:44:13 +0000131 } else
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000132 errs() << "(" << NameOrErr.get() << ")";
133
Kevin Enderby9acb1092016-05-31 20:35:34 +0000134 if (!ArchitectureName.empty())
135 errs() << " (for architecture " << ArchitectureName << ") ";
136
137 std::string Buf;
138 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000139 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000140 OS.flush();
141 errs() << " " << Buf << "\n";
142}
143
144// 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
145// before the error message. It sets HadError but returns allowing the code to
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000146// move on to other architecture slices.
Kevin Enderby9acb1092016-05-31 20:35:34 +0000147static void error(llvm::Error E, StringRef FileName,
148 StringRef ArchitectureName = StringRef()) {
149 HadError = true;
150 errs() << ToolName << ": " << FileName;
151
152 if (!ArchitectureName.empty())
153 errs() << " (for architecture " << ArchitectureName << ") ";
154
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000155 std::string Buf;
156 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000157 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000158 OS.flush();
159 errs() << " " << Buf << "\n";
160}
161
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000162/// Get the length of the string that represents @p num in Radix including the
163/// leading 0x or 0 for hexadecimal and octal respectively.
Andrew Trick7dc278d2011-09-29 01:22:31 +0000164static size_t getNumLengthAsString(uint64_t num) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000165 APInt conv(64, num);
166 SmallString<32> result;
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000167 conv.toString(result, Radix, false, true);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000168 return result.size();
169}
170
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000171/// Return the printing format for the Radix.
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000172static const char *getRadixFmt() {
Kevin Enderby246a4602014-06-17 17:54:13 +0000173 switch (Radix) {
174 case octal:
175 return PRIo64;
176 case decimal:
177 return PRIu64;
178 case hexadecimal:
179 return PRIx64;
180 }
181 return nullptr;
182}
183
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000184/// Remove unneeded ELF sections from calculation
185static bool considerForSize(ObjectFile *Obj, SectionRef Section) {
186 if (!Obj->isELF())
187 return true;
188 switch (static_cast<ELFSectionRef>(Section).getType()) {
189 case ELF::SHT_NULL:
190 case ELF::SHT_SYMTAB:
191 case ELF::SHT_STRTAB:
192 case ELF::SHT_REL:
193 case ELF::SHT_RELA:
194 return false;
195 }
196 return true;
197}
198
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000199/// Total size of all ELF common symbols
200static uint64_t getCommonSize(ObjectFile *Obj) {
201 uint64_t TotalCommons = 0;
202 for (auto &Sym : Obj->symbols())
203 if (Obj->getSymbolFlags(Sym.getRawDataRefImpl()) & SymbolRef::SF_Common)
204 TotalCommons += Obj->getCommonSymbolSize(Sym.getRawDataRefImpl());
205 return TotalCommons;
206}
207
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000208/// Print the size of each Mach-O segment and section in @p MachO.
Kevin Enderby246a4602014-06-17 17:54:13 +0000209///
210/// This is when used when @c OutputFormat is darwin and produces the same
211/// output as darwin's size(1) -m output.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000212static void printDarwinSectionSizes(MachOObjectFile *MachO) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000213 std::string fmtbuf;
214 raw_string_ostream fmt(fmtbuf);
215 const char *radix_fmt = getRadixFmt();
216 if (Radix == hexadecimal)
217 fmt << "0x";
218 fmt << "%" << radix_fmt;
219
Kevin Enderby246a4602014-06-17 17:54:13 +0000220 uint32_t Filetype = MachO->getHeader().filetype;
Kevin Enderby246a4602014-06-17 17:54:13 +0000221
222 uint64_t total = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000223 for (const auto &Load : MachO->load_commands()) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000224 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
225 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
226 outs() << "Segment " << Seg.segname << ": "
227 << format(fmt.str().c_str(), Seg.vmsize);
228 if (DarwinLongFormat)
Kevin Enderby10769742014-07-01 22:26:31 +0000229 outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff "
230 << Seg.fileoff << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000231 outs() << "\n";
232 total += Seg.vmsize;
233 uint64_t sec_total = 0;
234 for (unsigned J = 0; J < Seg.nsects; ++J) {
235 MachO::section_64 Sec = MachO->getSection64(Load, J);
236 if (Filetype == MachO::MH_OBJECT)
237 outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
238 << format("%.16s", &Sec.sectname) << "): ";
239 else
240 outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
241 outs() << format(fmt.str().c_str(), Sec.size);
242 if (DarwinLongFormat)
Kevin Enderby10769742014-07-01 22:26:31 +0000243 outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset "
244 << Sec.offset << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000245 outs() << "\n";
246 sec_total += Sec.size;
247 }
248 if (Seg.nsects != 0)
249 outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000250 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000251 MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000252 uint64_t Seg_vmsize = Seg.vmsize;
Kevin Enderby246a4602014-06-17 17:54:13 +0000253 outs() << "Segment " << Seg.segname << ": "
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000254 << format(fmt.str().c_str(), Seg_vmsize);
Kevin Enderby246a4602014-06-17 17:54:13 +0000255 if (DarwinLongFormat)
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000256 outs() << " (vmaddr 0x" << format("%" PRIx32, Seg.vmaddr) << " fileoff "
Kevin Enderby10769742014-07-01 22:26:31 +0000257 << Seg.fileoff << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000258 outs() << "\n";
259 total += Seg.vmsize;
260 uint64_t sec_total = 0;
261 for (unsigned J = 0; J < Seg.nsects; ++J) {
262 MachO::section Sec = MachO->getSection(Load, J);
263 if (Filetype == MachO::MH_OBJECT)
264 outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
265 << format("%.16s", &Sec.sectname) << "): ";
266 else
267 outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000268 uint64_t Sec_size = Sec.size;
269 outs() << format(fmt.str().c_str(), Sec_size);
Kevin Enderby246a4602014-06-17 17:54:13 +0000270 if (DarwinLongFormat)
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000271 outs() << " (addr 0x" << format("%" PRIx32, Sec.addr) << " offset "
Kevin Enderby10769742014-07-01 22:26:31 +0000272 << Sec.offset << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000273 outs() << "\n";
274 sec_total += Sec.size;
275 }
276 if (Seg.nsects != 0)
277 outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
278 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000279 }
280 outs() << "total " << format(fmt.str().c_str(), total) << "\n";
281}
282
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000283/// Print the summary sizes of the standard Mach-O segments in @p MachO.
Kevin Enderby246a4602014-06-17 17:54:13 +0000284///
285/// This is when used when @c OutputFormat is berkeley with a Mach-O file and
286/// produces the same output as darwin's size(1) default output.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000287static void printDarwinSegmentSizes(MachOObjectFile *MachO) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000288 uint64_t total_text = 0;
289 uint64_t total_data = 0;
290 uint64_t total_objc = 0;
291 uint64_t total_others = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000292 for (const auto &Load : MachO->load_commands()) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000293 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
294 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
295 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
296 for (unsigned J = 0; J < Seg.nsects; ++J) {
297 MachO::section_64 Sec = MachO->getSection64(Load, J);
298 StringRef SegmentName = StringRef(Sec.segname);
299 if (SegmentName == "__TEXT")
300 total_text += Sec.size;
301 else if (SegmentName == "__DATA")
302 total_data += Sec.size;
303 else if (SegmentName == "__OBJC")
304 total_objc += Sec.size;
305 else
306 total_others += Sec.size;
Kevin Enderby10769742014-07-01 22:26:31 +0000307 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000308 } else {
309 StringRef SegmentName = StringRef(Seg.segname);
310 if (SegmentName == "__TEXT")
311 total_text += Seg.vmsize;
312 else if (SegmentName == "__DATA")
313 total_data += Seg.vmsize;
314 else if (SegmentName == "__OBJC")
315 total_objc += Seg.vmsize;
316 else
317 total_others += Seg.vmsize;
318 }
Kevin Enderby10769742014-07-01 22:26:31 +0000319 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000320 MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
321 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
322 for (unsigned J = 0; J < Seg.nsects; ++J) {
323 MachO::section Sec = MachO->getSection(Load, J);
324 StringRef SegmentName = StringRef(Sec.segname);
325 if (SegmentName == "__TEXT")
326 total_text += Sec.size;
327 else if (SegmentName == "__DATA")
328 total_data += Sec.size;
329 else if (SegmentName == "__OBJC")
330 total_objc += Sec.size;
331 else
332 total_others += Sec.size;
Kevin Enderby10769742014-07-01 22:26:31 +0000333 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000334 } else {
335 StringRef SegmentName = StringRef(Seg.segname);
336 if (SegmentName == "__TEXT")
337 total_text += Seg.vmsize;
338 else if (SegmentName == "__DATA")
339 total_data += Seg.vmsize;
340 else if (SegmentName == "__OBJC")
341 total_objc += Seg.vmsize;
342 else
343 total_others += Seg.vmsize;
344 }
345 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000346 }
347 uint64_t total = total_text + total_data + total_objc + total_others;
348
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000349 if (!BerkeleyHeaderPrinted) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000350 outs() << "__TEXT\t__DATA\t__OBJC\tothers\tdec\thex\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000351 BerkeleyHeaderPrinted = true;
Kevin Enderby246a4602014-06-17 17:54:13 +0000352 }
353 outs() << total_text << "\t" << total_data << "\t" << total_objc << "\t"
354 << total_others << "\t" << total << "\t" << format("%" PRIx64, total)
355 << "\t";
356}
357
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000358/// Print the size of each section in @p Obj.
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000359///
360/// The format used is determined by @c OutputFormat and @c Radix.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000361static void printObjectSectionSizes(ObjectFile *Obj) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000362 uint64_t total = 0;
363 std::string fmtbuf;
364 raw_string_ostream fmt(fmtbuf);
Kevin Enderby246a4602014-06-17 17:54:13 +0000365 const char *radix_fmt = getRadixFmt();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000366
Kevin Enderby246a4602014-06-17 17:54:13 +0000367 // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
368 // size(1) -m output, else if OutputFormat is darwin and not a Mach-O object
369 // let it fall through to OutputFormat berkeley.
370 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
371 if (OutputFormat == darwin && MachO)
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000372 printDarwinSectionSizes(MachO);
Kevin Enderby246a4602014-06-17 17:54:13 +0000373 // If we have a MachOObjectFile and the OutputFormat is berkeley print as
374 // darwin's default berkeley format for Mach-O files.
375 else if (MachO && OutputFormat == berkeley)
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000376 printDarwinSegmentSizes(MachO);
Kevin Enderby246a4602014-06-17 17:54:13 +0000377 else if (OutputFormat == sysv) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000378 // Run two passes over all sections. The first gets the lengths needed for
379 // formatting the output. The second actually does the output.
380 std::size_t max_name_len = strlen("section");
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000381 std::size_t max_size_len = strlen("size");
382 std::size_t max_addr_len = strlen("addr");
Alexey Samsonov48803e52014-03-13 14:37:36 +0000383 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000384 if (!considerForSize(Obj, Section))
385 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000386 uint64_t size = Section.getSize();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000387 total += size;
388
George Rimarbcc00e12019-08-14 11:10:11 +0000389 Expected<StringRef> name_or_err = Section.getName();
390 if (!name_or_err) {
391 error(name_or_err.takeError(), Obj->getFileName());
Alexey Samsonov48803e52014-03-13 14:37:36 +0000392 return;
George Rimarbcc00e12019-08-14 11:10:11 +0000393 }
394
Rafael Espindola80291272014-10-08 15:28:58 +0000395 uint64_t addr = Section.getAddress();
George Rimarbcc00e12019-08-14 11:10:11 +0000396 max_name_len = std::max(max_name_len, name_or_err->size());
Andrew Trick7dc278d2011-09-29 01:22:31 +0000397 max_size_len = std::max(max_size_len, getNumLengthAsString(size));
398 max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000399 }
400
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000401 // Add extra padding.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000402 max_name_len += 2;
403 max_size_len += 2;
404 max_addr_len += 2;
405
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000406 // Setup header format.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000407 fmt << "%-" << max_name_len << "s "
408 << "%" << max_size_len << "s "
409 << "%" << max_addr_len << "s\n";
410
411 // Print header
Kevin Enderby10769742014-07-01 22:26:31 +0000412 outs() << format(fmt.str().c_str(), static_cast<const char *>("section"),
413 static_cast<const char *>("size"),
414 static_cast<const char *>("addr"));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000415 fmtbuf.clear();
416
417 // Setup per section format.
418 fmt << "%-" << max_name_len << "s "
419 << "%#" << max_size_len << radix_fmt << " "
420 << "%#" << max_addr_len << radix_fmt << "\n";
421
422 // Print each section.
Alexey Samsonov48803e52014-03-13 14:37:36 +0000423 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000424 if (!considerForSize(Obj, Section))
425 continue;
George Rimarbcc00e12019-08-14 11:10:11 +0000426
427 Expected<StringRef> name_or_err = Section.getName();
428 if (!name_or_err) {
429 error(name_or_err.takeError(), Obj->getFileName());
Alexey Samsonov48803e52014-03-13 14:37:36 +0000430 return;
George Rimarbcc00e12019-08-14 11:10:11 +0000431 }
432
Rafael Espindola80291272014-10-08 15:28:58 +0000433 uint64_t size = Section.getSize();
434 uint64_t addr = Section.getAddress();
George Rimarbcc00e12019-08-14 11:10:11 +0000435 outs() << format(fmt.str().c_str(), name_or_err->str().c_str(), size, addr);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000436 }
437
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000438 if (ELFCommons) {
439 uint64_t CommonSize = getCommonSize(Obj);
440 total += CommonSize;
441 outs() << format(fmt.str().c_str(), std::string("*COM*").c_str(),
442 CommonSize, static_cast<uint64_t>(0));
443 }
444
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000445 // Print total.
446 fmtbuf.clear();
447 fmt << "%-" << max_name_len << "s "
448 << "%#" << max_size_len << radix_fmt << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000449 outs() << format(fmt.str().c_str(), static_cast<const char *>("Total"),
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000450 total);
451 } else {
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000452 // The Berkeley format does not display individual section sizes. It
453 // displays the cumulative size for each section type.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000454 uint64_t total_text = 0;
455 uint64_t total_data = 0;
456 uint64_t total_bss = 0;
457
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000458 // Make one pass over the section table to calculate sizes.
Alexey Samsonov48803e52014-03-13 14:37:36 +0000459 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000460 uint64_t size = Section.getSize();
Jordan Rupprecht4888c4a2018-12-13 19:40:12 +0000461 bool isText = Section.isBerkeleyText();
462 bool isData = Section.isBerkeleyData();
Rafael Espindola80291272014-10-08 15:28:58 +0000463 bool isBSS = Section.isBSS();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000464 if (isText)
465 total_text += size;
466 else if (isData)
467 total_data += size;
468 else if (isBSS)
469 total_bss += size;
470 }
471
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000472 if (ELFCommons)
473 total_bss += getCommonSize(Obj);
474
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000475 total = total_text + total_data + total_bss;
476
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000477 if (TotalSizes) {
478 TotalObjectText += total_text;
479 TotalObjectData += total_data;
480 TotalObjectBss += total_bss;
481 TotalObjectTotal += total;
482 }
483
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000484 if (!BerkeleyHeaderPrinted) {
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000485 outs() << " text\t"
486 " data\t"
487 " bss\t"
488 " "
489 << (Radix == octal ? "oct" : "dec")
490 << "\t"
491 " hex\t"
492 "filename\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000493 BerkeleyHeaderPrinted = true;
Kevin Enderby246a4602014-06-17 17:54:13 +0000494 }
495
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000496 // Print result.
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000497 fmt << "%#7" << radix_fmt << "\t"
498 << "%#7" << radix_fmt << "\t"
499 << "%#7" << radix_fmt << "\t";
Kevin Enderby10769742014-07-01 22:26:31 +0000500 outs() << format(fmt.str().c_str(), total_text, total_data, total_bss);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000501 fmtbuf.clear();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000502 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
503 << "%7" PRIx64 "\t";
Kevin Enderby10769742014-07-01 22:26:31 +0000504 outs() << format(fmt.str().c_str(), total, total);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000505 }
506}
507
David Majnemer91160d82016-10-31 17:11:31 +0000508/// Checks to see if the @p O ObjectFile is a Mach-O file and if it is and there
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000509/// 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.
David Majnemer91160d82016-10-31 17:11:31 +0000513static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
514 auto *MachO = dyn_cast<MachOObjectFile>(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(H_64.cputype, H_64.cpusubtype);
525 } else {
526 H = MachO->MachOObjectFile::getHeader();
527 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
528 }
529 if (none_of(ArchFlags, [&](const std::string &Name) {
530 return Name == T.getArchName();
531 })) {
532 error(Filename + ": No architecture specified");
533 return false;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000534 }
535 return true;
536}
537
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000538/// Print the section sizes for @p file. If @p file is an archive, print the
539/// section sizes for each archive member.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000540static void printFileSectionSizes(StringRef file) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000541
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000542 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000543 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
544 if (!BinaryOrErr) {
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000545 error(BinaryOrErr.takeError(), file);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000546 return;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000547 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000548 Binary &Bin = *BinaryOrErr.get().getBinary();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000549
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000550 if (Archive *a = dyn_cast<Archive>(&Bin)) {
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000551 // This is an archive. Iterate over each member and display its sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000552 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000553 for (auto &C : a->children(Err)) {
554 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000555 if (!ChildOrErr) {
556 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000557 error(std::move(E), a->getFileName(), C);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000558 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000559 }
Rafael Espindolaae460022014-06-16 16:08:36 +0000560 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000561 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000562 if (!checkMachOAndArchFlags(o, file))
563 return;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000564 if (OutputFormat == sysv)
Kevin Enderby10769742014-07-01 22:26:31 +0000565 outs() << o->getFileName() << " (ex " << a->getFileName() << "):\n";
566 else if (MachO && OutputFormat == darwin)
567 outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000568 printObjectSectionSizes(o);
Kevin Enderby246a4602014-06-17 17:54:13 +0000569 if (OutputFormat == berkeley) {
570 if (MachO)
571 outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
572 else
573 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
574 }
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000575 }
576 }
Lang Hamesfc209622016-07-14 02:24:01 +0000577 if (Err)
578 error(std::move(Err), a->getFileName());
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000579 } else if (MachOUniversalBinary *UB =
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000580 dyn_cast<MachOUniversalBinary>(&Bin)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000581 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000582 if (!ArchAll && !ArchFlags.empty()) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000583 // Look for a slice in the universal binary that matches each ArchFlag.
584 bool ArchFound;
Kevin Enderby10769742014-07-01 22:26:31 +0000585 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000586 ArchFound = false;
587 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
588 E = UB->end_objects();
589 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +0000590 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000591 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000592 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000593 if (UO) {
594 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
595 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
596 if (OutputFormat == sysv)
597 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000598 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000599 if (MoreThanOneFile || ArchFlags.size() > 1)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000600 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000601 << I->getArchFlagName() << "): \n";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000602 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000603 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000604 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000605 if (!MachO || MoreThanOneFile || ArchFlags.size() > 1)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000606 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000607 << I->getArchFlagName() << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000608 outs() << "\n";
609 }
610 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000611 } else if (auto E = isNotObjectErrorInvalidFileType(
612 UO.takeError())) {
613 error(std::move(E), file, ArchFlags.size() > 1 ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000614 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000615 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000616 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000617 I->getAsArchive()) {
618 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000619 // This is an archive. Iterate over each member and display its
Kevin Enderby10769742014-07-01 22:26:31 +0000620 // sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000621 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000622 for (auto &C : UA->children(Err)) {
623 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000624 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000625 if (auto E = isNotObjectErrorInvalidFileType(
626 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000627 error(std::move(E), UA->getFileName(), C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000628 ArchFlags.size() > 1 ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000629 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000630 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000631 }
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000632 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
633 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
634 if (OutputFormat == sysv)
635 outs() << o->getFileName() << " (ex " << UA->getFileName()
636 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000637 else if (MachO && OutputFormat == darwin)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000638 outs() << UA->getFileName() << "(" << o->getFileName()
Kevin Enderby10769742014-07-01 22:26:31 +0000639 << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000640 << " (for architecture " << I->getArchFlagName()
Kevin Enderby10769742014-07-01 22:26:31 +0000641 << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000642 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000643 if (OutputFormat == berkeley) {
644 if (MachO) {
645 outs() << UA->getFileName() << "(" << o->getFileName()
646 << ")";
647 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +0000648 outs() << " (for architecture " << I->getArchFlagName()
Kevin Enderby10769742014-07-01 22:26:31 +0000649 << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000650 outs() << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000651 } else
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000652 outs() << o->getFileName() << " (ex " << UA->getFileName()
653 << ")\n";
654 }
655 }
656 }
Lang Hamesfc209622016-07-14 02:24:01 +0000657 if (Err)
658 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000659 } else {
660 consumeError(AOrErr.takeError());
661 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000662 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000663 " is not a Mach-O file or an archive file");
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000664 }
665 }
666 }
667 if (!ArchFound) {
668 errs() << ToolName << ": file: " << file
669 << " does not contain architecture" << ArchFlags[i] << ".\n";
670 return;
671 }
672 }
673 return;
674 }
675 // No architecture flags were specified so if this contains a slice that
676 // matches the host architecture dump only that.
677 if (!ArchAll) {
Kevin Enderby10769742014-07-01 22:26:31 +0000678 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000679 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
680 E = UB->end_objects();
681 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +0000682 if (HostArchName == I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000683 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000684 if (UO) {
685 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
686 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
687 if (OutputFormat == sysv)
688 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000689 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000690 if (MoreThanOneFile)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000691 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000692 << I->getArchFlagName() << "):\n";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000693 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000694 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000695 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000696 if (!MachO || MoreThanOneFile)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000697 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000698 << I->getArchFlagName() << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000699 outs() << "\n";
700 }
701 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000702 } else if (auto E = isNotObjectErrorInvalidFileType(UO.takeError())) {
703 error(std::move(E), file);
704 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000705 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000706 I->getAsArchive()) {
707 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000708 // This is an archive. Iterate over each member and display its
709 // sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000710 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000711 for (auto &C : UA->children(Err)) {
712 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000713 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000714 if (auto E = isNotObjectErrorInvalidFileType(
715 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000716 error(std::move(E), UA->getFileName(), C);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000717 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000718 }
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000719 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
720 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
721 if (OutputFormat == sysv)
722 outs() << o->getFileName() << " (ex " << UA->getFileName()
723 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000724 else if (MachO && OutputFormat == darwin)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000725 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000726 << " (for architecture " << I->getArchFlagName()
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000727 << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000728 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000729 if (OutputFormat == berkeley) {
730 if (MachO)
731 outs() << UA->getFileName() << "(" << o->getFileName()
732 << ")\n";
733 else
734 outs() << o->getFileName() << " (ex " << UA->getFileName()
735 << ")\n";
736 }
737 }
738 }
Lang Hamesfc209622016-07-14 02:24:01 +0000739 if (Err)
740 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000741 } else {
742 consumeError(AOrErr.takeError());
743 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000744 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000745 " is not a Mach-O file or an archive file");
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000746 }
747 return;
748 }
749 }
750 }
751 // Either all architectures have been specified or none have been specified
752 // and this does not contain the host architecture so dump all the slices.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000753 bool MoreThanOneArch = UB->getNumberOfObjects() > 1;
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000754 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
755 E = UB->end_objects();
756 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000757 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000758 if (UO) {
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000759 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000760 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000761 if (OutputFormat == sysv)
762 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000763 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000764 if (MoreThanOneFile || MoreThanOneArch)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000765 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000766 << I->getArchFlagName() << "):";
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000767 outs() << "\n";
768 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000769 printObjectSectionSizes(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000770 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000771 if (!MachO || MoreThanOneFile || MoreThanOneArch)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000772 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000773 << I->getArchFlagName() << ")";
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000774 outs() << "\n";
775 }
776 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000777 } else if (auto E = isNotObjectErrorInvalidFileType(UO.takeError())) {
778 error(std::move(E), file, MoreThanOneArch ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000779 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000780 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000781 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000782 I->getAsArchive()) {
783 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000784 // This is an archive. Iterate over each member and display its sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000785 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000786 for (auto &C : UA->children(Err)) {
787 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000788 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000789 if (auto E = isNotObjectErrorInvalidFileType(
790 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000791 error(std::move(E), UA->getFileName(), C, MoreThanOneArch ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000792 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000793 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000794 }
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000795 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
796 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
797 if (OutputFormat == sysv)
798 outs() << o->getFileName() << " (ex " << UA->getFileName()
799 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000800 else if (MachO && OutputFormat == darwin)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000801 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000802 << " (for architecture " << I->getArchFlagName() << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000803 printObjectSectionSizes(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000804 if (OutputFormat == berkeley) {
805 if (MachO)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000806 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000807 << " (for architecture " << I->getArchFlagName()
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000808 << ")\n";
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000809 else
810 outs() << o->getFileName() << " (ex " << UA->getFileName()
811 << ")\n";
812 }
813 }
814 }
Lang Hamesfc209622016-07-14 02:24:01 +0000815 if (Err)
816 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000817 } else {
818 consumeError(AOrErr.takeError());
819 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000820 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000821 " is not a Mach-O file or an archive file");
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000822 }
823 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000824 } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000825 if (!checkMachOAndArchFlags(o, file))
826 return;
Kevin Enderby5997c942016-12-01 19:12:55 +0000827 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000828 if (OutputFormat == sysv)
829 outs() << o->getFileName() << " :\n";
Kevin Enderby5997c942016-12-01 19:12:55 +0000830 else if (MachO && OutputFormat == darwin && MoreThanOneFile)
831 outs() << o->getFileName() << ":\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000832 printObjectSectionSizes(o);
Kevin Enderby246a4602014-06-17 17:54:13 +0000833 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000834 if (!MachO || MoreThanOneFile)
Kevin Enderby246a4602014-06-17 17:54:13 +0000835 outs() << o->getFileName();
836 outs() << "\n";
837 }
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000838 } else {
Kevin Enderby10769742014-07-01 22:26:31 +0000839 errs() << ToolName << ": " << file << ": "
840 << "Unrecognized file type.\n";
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000841 }
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000842 // System V adds an extra newline at the end of each file.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000843 if (OutputFormat == sysv)
844 outs() << "\n";
845}
846
James Hendersoncd893e52019-09-13 12:00:42 +0000847static void printBerkeleyTotals() {
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000848 std::string fmtbuf;
849 raw_string_ostream fmt(fmtbuf);
850 const char *radix_fmt = getRadixFmt();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000851 fmt << "%#7" << radix_fmt << "\t"
852 << "%#7" << radix_fmt << "\t"
853 << "%#7" << radix_fmt << "\t";
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000854 outs() << format(fmt.str().c_str(), TotalObjectText, TotalObjectData,
855 TotalObjectBss);
856 fmtbuf.clear();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000857 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
858 << "%7" PRIx64 "\t";
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000859 outs() << format(fmt.str().c_str(), TotalObjectTotal, TotalObjectTotal)
860 << "(TOTALS)\n";
861}
862
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000863int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000864 InitLLVM X(argc, argv);
Serge Gueltondaeeb332019-06-05 10:32:28 +0000865 cl::HideUnrelatedOptions(SizeCat);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000866 cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
867
868 ToolName = argv[0];
869 if (OutputFormatShort.getNumOccurrences())
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000870 OutputFormat = static_cast<OutputFormatTy>(OutputFormatShort);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000871 if (RadixShort.getNumOccurrences())
James Hendersonb3735ee2018-10-30 11:52:47 +0000872 Radix = RadixShort.getValue();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000873
Fangrui Song64449e62018-11-22 00:44:17 +0000874 for (StringRef Arch : ArchFlags) {
875 if (Arch == "all") {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000876 ArchAll = true;
Kevin Enderby10769742014-07-01 22:26:31 +0000877 } else {
Fangrui Song64449e62018-11-22 00:44:17 +0000878 if (!MachOObjectFile::isValidArch(Arch)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000879 outs() << ToolName << ": for the -arch option: Unknown architecture "
Fangrui Song64449e62018-11-22 00:44:17 +0000880 << "named '" << Arch << "'";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000881 return 1;
882 }
883 }
884 }
885
Fangrui Song64449e62018-11-22 00:44:17 +0000886 if (InputFilenames.empty())
Dimitry Andrice4f5d012017-12-18 19:46:56 +0000887 InputFilenames.push_back("a.out");
888
889 MoreThanOneFile = InputFilenames.size() > 1;
890 llvm::for_each(InputFilenames, printFileSectionSizes);
891 if (OutputFormat == berkeley && TotalSizes)
James Hendersoncd893e52019-09-13 12:00:42 +0000892 printBerkeleyTotals();
Dimitry Andrice4f5d012017-12-18 19:46:56 +0000893
Kevin Enderby64f7a992016-05-02 21:41:03 +0000894 if (HadError)
895 return 1;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000896}