blob: e422e69f78515121c54a498b00988571be2ea9be [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 "
68 "Berkely 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
Fangrui Song1e2d5cb2018-06-22 22:20:10 +0000102static bool HadError = false;
Kevin Enderby64f7a992016-05-02 21:41:03 +0000103
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000104static std::string ToolName;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000105
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000106/// If ec is not success, print the error and return true.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000107static bool error(std::error_code ec) {
Kevin Enderby10769742014-07-01 22:26:31 +0000108 if (!ec)
109 return false;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000110
Kevin Enderby64f7a992016-05-02 21:41:03 +0000111 HadError = true;
Davide Italiano911eb312016-01-25 01:24:15 +0000112 errs() << ToolName << ": error reading file: " << ec.message() << ".\n";
113 errs().flush();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000114 return true;
115}
116
Kevin Enderby42398052016-06-28 23:16:13 +0000117static bool error(Twine Message) {
118 HadError = true;
119 errs() << ToolName << ": " << Message << ".\n";
120 errs().flush();
121 return true;
122}
123
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000124// This version of error() prints the archive name and member name, for example:
125// "libx.a(foo.o)" after the ToolName before the error message. It sets
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000126// HadError but returns allowing the code to move on to other archive members.
Kevin Enderby9acb1092016-05-31 20:35:34 +0000127static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
128 StringRef ArchitectureName = StringRef()) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000129 HadError = true;
130 errs() << ToolName << ": " << FileName;
131
Kevin Enderbyf4586032016-07-29 17:44:13 +0000132 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000133 // TODO: if we have a error getting the name then it would be nice to print
134 // the index of which archive member this is and or its offset in the
135 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000136 if (!NameOrErr) {
137 consumeError(NameOrErr.takeError());
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000138 errs() << "(" << "???" << ")";
Kevin Enderbyf4586032016-07-29 17:44:13 +0000139 } else
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000140 errs() << "(" << NameOrErr.get() << ")";
141
Kevin Enderby9acb1092016-05-31 20:35:34 +0000142 if (!ArchitectureName.empty())
143 errs() << " (for architecture " << ArchitectureName << ") ";
144
145 std::string Buf;
146 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000147 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000148 OS.flush();
149 errs() << " " << Buf << "\n";
150}
151
152// 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
153// before the error message. It sets HadError but returns allowing the code to
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000154// move on to other architecture slices.
Kevin Enderby9acb1092016-05-31 20:35:34 +0000155static void error(llvm::Error E, StringRef FileName,
156 StringRef ArchitectureName = StringRef()) {
157 HadError = true;
158 errs() << ToolName << ": " << FileName;
159
160 if (!ArchitectureName.empty())
161 errs() << " (for architecture " << ArchitectureName << ") ";
162
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000163 std::string Buf;
164 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000165 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000166 OS.flush();
167 errs() << " " << Buf << "\n";
168}
169
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000170/// Get the length of the string that represents @p num in Radix including the
171/// leading 0x or 0 for hexadecimal and octal respectively.
Andrew Trick7dc278d2011-09-29 01:22:31 +0000172static size_t getNumLengthAsString(uint64_t num) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000173 APInt conv(64, num);
174 SmallString<32> result;
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000175 conv.toString(result, Radix, false, true);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000176 return result.size();
177}
178
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000179/// Return the printing format for the Radix.
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000180static const char *getRadixFmt() {
Kevin Enderby246a4602014-06-17 17:54:13 +0000181 switch (Radix) {
182 case octal:
183 return PRIo64;
184 case decimal:
185 return PRIu64;
186 case hexadecimal:
187 return PRIx64;
188 }
189 return nullptr;
190}
191
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000192/// Remove unneeded ELF sections from calculation
193static bool considerForSize(ObjectFile *Obj, SectionRef Section) {
194 if (!Obj->isELF())
195 return true;
196 switch (static_cast<ELFSectionRef>(Section).getType()) {
197 case ELF::SHT_NULL:
198 case ELF::SHT_SYMTAB:
199 case ELF::SHT_STRTAB:
200 case ELF::SHT_REL:
201 case ELF::SHT_RELA:
202 return false;
203 }
204 return true;
205}
206
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000207/// Total size of all ELF common symbols
208static uint64_t getCommonSize(ObjectFile *Obj) {
209 uint64_t TotalCommons = 0;
210 for (auto &Sym : Obj->symbols())
211 if (Obj->getSymbolFlags(Sym.getRawDataRefImpl()) & SymbolRef::SF_Common)
212 TotalCommons += Obj->getCommonSymbolSize(Sym.getRawDataRefImpl());
213 return TotalCommons;
214}
215
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000216/// Print the size of each Mach-O segment and section in @p MachO.
Kevin Enderby246a4602014-06-17 17:54:13 +0000217///
218/// This is when used when @c OutputFormat is darwin and produces the same
219/// output as darwin's size(1) -m output.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000220static void printDarwinSectionSizes(MachOObjectFile *MachO) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000221 std::string fmtbuf;
222 raw_string_ostream fmt(fmtbuf);
223 const char *radix_fmt = getRadixFmt();
224 if (Radix == hexadecimal)
225 fmt << "0x";
226 fmt << "%" << radix_fmt;
227
Kevin Enderby246a4602014-06-17 17:54:13 +0000228 uint32_t Filetype = MachO->getHeader().filetype;
Kevin Enderby246a4602014-06-17 17:54:13 +0000229
230 uint64_t total = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000231 for (const auto &Load : MachO->load_commands()) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000232 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
233 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
234 outs() << "Segment " << Seg.segname << ": "
235 << format(fmt.str().c_str(), Seg.vmsize);
236 if (DarwinLongFormat)
Kevin Enderby10769742014-07-01 22:26:31 +0000237 outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff "
238 << Seg.fileoff << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000239 outs() << "\n";
240 total += Seg.vmsize;
241 uint64_t sec_total = 0;
242 for (unsigned J = 0; J < Seg.nsects; ++J) {
243 MachO::section_64 Sec = MachO->getSection64(Load, J);
244 if (Filetype == MachO::MH_OBJECT)
245 outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
246 << format("%.16s", &Sec.sectname) << "): ";
247 else
248 outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
249 outs() << format(fmt.str().c_str(), Sec.size);
250 if (DarwinLongFormat)
Kevin Enderby10769742014-07-01 22:26:31 +0000251 outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset "
252 << Sec.offset << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000253 outs() << "\n";
254 sec_total += Sec.size;
255 }
256 if (Seg.nsects != 0)
257 outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000258 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000259 MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000260 uint64_t Seg_vmsize = Seg.vmsize;
Kevin Enderby246a4602014-06-17 17:54:13 +0000261 outs() << "Segment " << Seg.segname << ": "
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000262 << format(fmt.str().c_str(), Seg_vmsize);
Kevin Enderby246a4602014-06-17 17:54:13 +0000263 if (DarwinLongFormat)
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000264 outs() << " (vmaddr 0x" << format("%" PRIx32, Seg.vmaddr) << " fileoff "
Kevin Enderby10769742014-07-01 22:26:31 +0000265 << Seg.fileoff << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000266 outs() << "\n";
267 total += Seg.vmsize;
268 uint64_t sec_total = 0;
269 for (unsigned J = 0; J < Seg.nsects; ++J) {
270 MachO::section Sec = MachO->getSection(Load, J);
271 if (Filetype == MachO::MH_OBJECT)
272 outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", "
273 << format("%.16s", &Sec.sectname) << "): ";
274 else
275 outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": ";
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000276 uint64_t Sec_size = Sec.size;
277 outs() << format(fmt.str().c_str(), Sec_size);
Kevin Enderby246a4602014-06-17 17:54:13 +0000278 if (DarwinLongFormat)
Kevin Enderby2058e9d2016-02-09 18:33:15 +0000279 outs() << " (addr 0x" << format("%" PRIx32, Sec.addr) << " offset "
Kevin Enderby10769742014-07-01 22:26:31 +0000280 << Sec.offset << ")";
Kevin Enderby246a4602014-06-17 17:54:13 +0000281 outs() << "\n";
282 sec_total += Sec.size;
283 }
284 if (Seg.nsects != 0)
285 outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n";
286 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000287 }
288 outs() << "total " << format(fmt.str().c_str(), total) << "\n";
289}
290
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000291/// Print the summary sizes of the standard Mach-O segments in @p MachO.
Kevin Enderby246a4602014-06-17 17:54:13 +0000292///
293/// This is when used when @c OutputFormat is berkeley with a Mach-O file and
294/// produces the same output as darwin's size(1) default output.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000295static void printDarwinSegmentSizes(MachOObjectFile *MachO) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000296 uint64_t total_text = 0;
297 uint64_t total_data = 0;
298 uint64_t total_objc = 0;
299 uint64_t total_others = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000300 for (const auto &Load : MachO->load_commands()) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000301 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
302 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load);
303 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
304 for (unsigned J = 0; J < Seg.nsects; ++J) {
305 MachO::section_64 Sec = MachO->getSection64(Load, 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;
Kevin Enderby10769742014-07-01 22:26:31 +0000315 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000316 } 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
325 total_others += Seg.vmsize;
326 }
Kevin Enderby10769742014-07-01 22:26:31 +0000327 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000328 MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load);
329 if (MachO->getHeader().filetype == MachO::MH_OBJECT) {
330 for (unsigned J = 0; J < Seg.nsects; ++J) {
331 MachO::section Sec = MachO->getSection(Load, J);
332 StringRef SegmentName = StringRef(Sec.segname);
333 if (SegmentName == "__TEXT")
334 total_text += Sec.size;
335 else if (SegmentName == "__DATA")
336 total_data += Sec.size;
337 else if (SegmentName == "__OBJC")
338 total_objc += Sec.size;
339 else
340 total_others += Sec.size;
Kevin Enderby10769742014-07-01 22:26:31 +0000341 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000342 } else {
343 StringRef SegmentName = StringRef(Seg.segname);
344 if (SegmentName == "__TEXT")
345 total_text += Seg.vmsize;
346 else if (SegmentName == "__DATA")
347 total_data += Seg.vmsize;
348 else if (SegmentName == "__OBJC")
349 total_objc += Seg.vmsize;
350 else
351 total_others += Seg.vmsize;
352 }
353 }
Kevin Enderby246a4602014-06-17 17:54:13 +0000354 }
355 uint64_t total = total_text + total_data + total_objc + total_others;
356
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000357 if (!BerkeleyHeaderPrinted) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000358 outs() << "__TEXT\t__DATA\t__OBJC\tothers\tdec\thex\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000359 BerkeleyHeaderPrinted = true;
Kevin Enderby246a4602014-06-17 17:54:13 +0000360 }
361 outs() << total_text << "\t" << total_data << "\t" << total_objc << "\t"
362 << total_others << "\t" << total << "\t" << format("%" PRIx64, total)
363 << "\t";
364}
365
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000366/// Print the size of each section in @p Obj.
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000367///
368/// The format used is determined by @c OutputFormat and @c Radix.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000369static void printObjectSectionSizes(ObjectFile *Obj) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000370 uint64_t total = 0;
371 std::string fmtbuf;
372 raw_string_ostream fmt(fmtbuf);
Kevin Enderby246a4602014-06-17 17:54:13 +0000373 const char *radix_fmt = getRadixFmt();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000374
Kevin Enderby246a4602014-06-17 17:54:13 +0000375 // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
376 // size(1) -m output, else if OutputFormat is darwin and not a Mach-O object
377 // let it fall through to OutputFormat berkeley.
378 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
379 if (OutputFormat == darwin && MachO)
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000380 printDarwinSectionSizes(MachO);
Kevin Enderby246a4602014-06-17 17:54:13 +0000381 // If we have a MachOObjectFile and the OutputFormat is berkeley print as
382 // darwin's default berkeley format for Mach-O files.
383 else if (MachO && OutputFormat == berkeley)
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000384 printDarwinSegmentSizes(MachO);
Kevin Enderby246a4602014-06-17 17:54:13 +0000385 else if (OutputFormat == sysv) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000386 // Run two passes over all sections. The first gets the lengths needed for
387 // formatting the output. The second actually does the output.
388 std::size_t max_name_len = strlen("section");
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000389 std::size_t max_size_len = strlen("size");
390 std::size_t max_addr_len = strlen("addr");
Alexey Samsonov48803e52014-03-13 14:37:36 +0000391 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000392 if (!considerForSize(Obj, Section))
393 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000394 uint64_t size = Section.getSize();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000395 total += size;
396
397 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000398 if (error(Section.getName(name)))
399 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000400 uint64_t addr = Section.getAddress();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000401 max_name_len = std::max(max_name_len, name.size());
Andrew Trick7dc278d2011-09-29 01:22:31 +0000402 max_size_len = std::max(max_size_len, getNumLengthAsString(size));
403 max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000404 }
405
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000406 // Add extra padding.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000407 max_name_len += 2;
408 max_size_len += 2;
409 max_addr_len += 2;
410
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000411 // Setup header format.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000412 fmt << "%-" << max_name_len << "s "
413 << "%" << max_size_len << "s "
414 << "%" << max_addr_len << "s\n";
415
416 // Print header
Kevin Enderby10769742014-07-01 22:26:31 +0000417 outs() << format(fmt.str().c_str(), static_cast<const char *>("section"),
418 static_cast<const char *>("size"),
419 static_cast<const char *>("addr"));
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000420 fmtbuf.clear();
421
422 // Setup per section format.
423 fmt << "%-" << max_name_len << "s "
424 << "%#" << max_size_len << radix_fmt << " "
425 << "%#" << max_addr_len << radix_fmt << "\n";
426
427 // Print each section.
Alexey Samsonov48803e52014-03-13 14:37:36 +0000428 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindolaa0ff5562016-02-09 21:39:49 +0000429 if (!considerForSize(Obj, Section))
430 continue;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000431 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000432 if (error(Section.getName(name)))
433 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000434 uint64_t size = Section.getSize();
435 uint64_t addr = Section.getAddress();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000436 std::string namestr = name;
437
Alexey Samsonov48803e52014-03-13 14:37:36 +0000438 outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000439 }
440
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000441 if (ELFCommons) {
442 uint64_t CommonSize = getCommonSize(Obj);
443 total += CommonSize;
444 outs() << format(fmt.str().c_str(), std::string("*COM*").c_str(),
445 CommonSize, static_cast<uint64_t>(0));
446 }
447
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000448 // Print total.
449 fmtbuf.clear();
450 fmt << "%-" << max_name_len << "s "
451 << "%#" << max_size_len << radix_fmt << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000452 outs() << format(fmt.str().c_str(), static_cast<const char *>("Total"),
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000453 total);
454 } else {
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000455 // The Berkeley format does not display individual section sizes. It
456 // displays the cumulative size for each section type.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000457 uint64_t total_text = 0;
458 uint64_t total_data = 0;
459 uint64_t total_bss = 0;
460
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000461 // Make one pass over the section table to calculate sizes.
Alexey Samsonov48803e52014-03-13 14:37:36 +0000462 for (const SectionRef &Section : Obj->sections()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000463 uint64_t size = Section.getSize();
Jordan Rupprecht4888c4a2018-12-13 19:40:12 +0000464 bool isText = Section.isBerkeleyText();
465 bool isData = Section.isBerkeleyData();
Rafael Espindola80291272014-10-08 15:28:58 +0000466 bool isBSS = Section.isBSS();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000467 if (isText)
468 total_text += size;
469 else if (isData)
470 total_data += size;
471 else if (isBSS)
472 total_bss += size;
473 }
474
Hemant Kulkarni274457e2016-03-28 16:48:10 +0000475 if (ELFCommons)
476 total_bss += getCommonSize(Obj);
477
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000478 total = total_text + total_data + total_bss;
479
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000480 if (TotalSizes) {
481 TotalObjectText += total_text;
482 TotalObjectData += total_data;
483 TotalObjectBss += total_bss;
484 TotalObjectTotal += total;
485 }
486
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000487 if (!BerkeleyHeaderPrinted) {
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000488 outs() << " text\t"
489 " data\t"
490 " bss\t"
491 " "
492 << (Radix == octal ? "oct" : "dec")
493 << "\t"
494 " hex\t"
495 "filename\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000496 BerkeleyHeaderPrinted = true;
Kevin Enderby246a4602014-06-17 17:54:13 +0000497 }
498
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000499 // Print result.
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000500 fmt << "%#7" << radix_fmt << "\t"
501 << "%#7" << radix_fmt << "\t"
502 << "%#7" << radix_fmt << "\t";
Kevin Enderby10769742014-07-01 22:26:31 +0000503 outs() << format(fmt.str().c_str(), total_text, total_data, total_bss);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000504 fmtbuf.clear();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000505 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
506 << "%7" PRIx64 "\t";
Kevin Enderby10769742014-07-01 22:26:31 +0000507 outs() << format(fmt.str().c_str(), total, total);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000508 }
509}
510
David Majnemer91160d82016-10-31 17:11:31 +0000511/// 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 +0000512/// is a list of architecture flags specified then check to make sure this
513/// Mach-O file is one of those architectures or all architectures was
514/// specificed. If not then an error is generated and this routine returns
515/// false. Else it returns true.
David Majnemer91160d82016-10-31 17:11:31 +0000516static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
517 auto *MachO = dyn_cast<MachOObjectFile>(O);
518
519 if (!MachO || ArchAll || ArchFlags.empty())
520 return true;
521
522 MachO::mach_header H;
523 MachO::mach_header_64 H_64;
524 Triple T;
525 if (MachO->is64Bit()) {
526 H_64 = MachO->MachOObjectFile::getHeader64();
527 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
528 } else {
529 H = MachO->MachOObjectFile::getHeader();
530 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
531 }
532 if (none_of(ArchFlags, [&](const std::string &Name) {
533 return Name == T.getArchName();
534 })) {
535 error(Filename + ": No architecture specified");
536 return false;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000537 }
538 return true;
539}
540
Rafael Espindola49a0e5e2016-02-09 21:32:56 +0000541/// Print the section sizes for @p file. If @p file is an archive, print the
542/// section sizes for each archive member.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000543static void printFileSectionSizes(StringRef file) {
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000544
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000545 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000546 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
547 if (!BinaryOrErr) {
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000548 error(BinaryOrErr.takeError(), file);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000549 return;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000550 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000551 Binary &Bin = *BinaryOrErr.get().getBinary();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000552
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000553 if (Archive *a = dyn_cast<Archive>(&Bin)) {
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000554 // This is an archive. Iterate over each member and display its sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000555 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000556 for (auto &C : a->children(Err)) {
557 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000558 if (!ChildOrErr) {
559 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000560 error(std::move(E), a->getFileName(), C);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000561 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000562 }
Rafael Espindolaae460022014-06-16 16:08:36 +0000563 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
Kevin Enderby246a4602014-06-17 17:54:13 +0000564 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000565 if (!checkMachOAndArchFlags(o, file))
566 return;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000567 if (OutputFormat == sysv)
Kevin Enderby10769742014-07-01 22:26:31 +0000568 outs() << o->getFileName() << " (ex " << a->getFileName() << "):\n";
569 else if (MachO && OutputFormat == darwin)
570 outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000571 printObjectSectionSizes(o);
Kevin Enderby246a4602014-06-17 17:54:13 +0000572 if (OutputFormat == berkeley) {
573 if (MachO)
574 outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
575 else
576 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
577 }
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000578 }
579 }
Lang Hamesfc209622016-07-14 02:24:01 +0000580 if (Err)
581 error(std::move(Err), a->getFileName());
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000582 } else if (MachOUniversalBinary *UB =
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000583 dyn_cast<MachOUniversalBinary>(&Bin)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000584 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000585 if (!ArchAll && !ArchFlags.empty()) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000586 // Look for a slice in the universal binary that matches each ArchFlag.
587 bool ArchFound;
Kevin Enderby10769742014-07-01 22:26:31 +0000588 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000589 ArchFound = false;
590 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
591 E = UB->end_objects();
592 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +0000593 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000594 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000595 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000596 if (UO) {
597 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
598 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
599 if (OutputFormat == sysv)
600 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000601 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000602 if (MoreThanOneFile || ArchFlags.size() > 1)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000603 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000604 << I->getArchFlagName() << "): \n";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000605 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000606 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000607 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000608 if (!MachO || MoreThanOneFile || ArchFlags.size() > 1)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000609 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000610 << I->getArchFlagName() << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000611 outs() << "\n";
612 }
613 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000614 } else if (auto E = isNotObjectErrorInvalidFileType(
615 UO.takeError())) {
616 error(std::move(E), file, ArchFlags.size() > 1 ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000617 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000618 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000619 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000620 I->getAsArchive()) {
621 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000622 // This is an archive. Iterate over each member and display its
Kevin Enderby10769742014-07-01 22:26:31 +0000623 // sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000624 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000625 for (auto &C : UA->children(Err)) {
626 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000627 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000628 if (auto E = isNotObjectErrorInvalidFileType(
629 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000630 error(std::move(E), UA->getFileName(), C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000631 ArchFlags.size() > 1 ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000632 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000633 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000634 }
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000635 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
636 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
637 if (OutputFormat == sysv)
638 outs() << o->getFileName() << " (ex " << UA->getFileName()
639 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000640 else if (MachO && OutputFormat == darwin)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000641 outs() << UA->getFileName() << "(" << o->getFileName()
Kevin Enderby10769742014-07-01 22:26:31 +0000642 << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000643 << " (for architecture " << I->getArchFlagName()
Kevin Enderby10769742014-07-01 22:26:31 +0000644 << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000645 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000646 if (OutputFormat == berkeley) {
647 if (MachO) {
648 outs() << UA->getFileName() << "(" << o->getFileName()
649 << ")";
650 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +0000651 outs() << " (for architecture " << I->getArchFlagName()
Kevin Enderby10769742014-07-01 22:26:31 +0000652 << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000653 outs() << "\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000654 } else
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000655 outs() << o->getFileName() << " (ex " << UA->getFileName()
656 << ")\n";
657 }
658 }
659 }
Lang Hamesfc209622016-07-14 02:24:01 +0000660 if (Err)
661 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000662 } else {
663 consumeError(AOrErr.takeError());
664 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000665 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000666 " is not a Mach-O file or an archive file");
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000667 }
668 }
669 }
670 if (!ArchFound) {
671 errs() << ToolName << ": file: " << file
672 << " does not contain architecture" << ArchFlags[i] << ".\n";
673 return;
674 }
675 }
676 return;
677 }
678 // No architecture flags were specified so if this contains a slice that
679 // matches the host architecture dump only that.
680 if (!ArchAll) {
Kevin Enderby10769742014-07-01 22:26:31 +0000681 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000682 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
683 E = UB->end_objects();
684 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +0000685 if (HostArchName == I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000686 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000687 if (UO) {
688 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
689 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
690 if (OutputFormat == sysv)
691 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000692 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000693 if (MoreThanOneFile)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000694 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000695 << I->getArchFlagName() << "):\n";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000696 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000697 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000698 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000699 if (!MachO || MoreThanOneFile)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000700 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000701 << I->getArchFlagName() << ")";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000702 outs() << "\n";
703 }
704 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000705 } else if (auto E = isNotObjectErrorInvalidFileType(UO.takeError())) {
706 error(std::move(E), file);
707 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000708 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000709 I->getAsArchive()) {
710 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000711 // This is an archive. Iterate over each member and display its
712 // sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000713 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000714 for (auto &C : UA->children(Err)) {
715 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000716 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000717 if (auto E = isNotObjectErrorInvalidFileType(
718 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000719 error(std::move(E), UA->getFileName(), C);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000720 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000721 }
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000722 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
723 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
724 if (OutputFormat == sysv)
725 outs() << o->getFileName() << " (ex " << UA->getFileName()
726 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000727 else if (MachO && OutputFormat == darwin)
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000728 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000729 << " (for architecture " << I->getArchFlagName()
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000730 << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000731 printObjectSectionSizes(o);
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000732 if (OutputFormat == berkeley) {
733 if (MachO)
734 outs() << UA->getFileName() << "(" << o->getFileName()
735 << ")\n";
736 else
737 outs() << o->getFileName() << " (ex " << UA->getFileName()
738 << ")\n";
739 }
740 }
741 }
Lang Hamesfc209622016-07-14 02:24:01 +0000742 if (Err)
743 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000744 } else {
745 consumeError(AOrErr.takeError());
746 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000747 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000748 " is not a Mach-O file or an archive file");
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000749 }
750 return;
751 }
752 }
753 }
754 // Either all architectures have been specified or none have been specified
755 // and this does not contain the host architecture so dump all the slices.
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000756 bool MoreThanOneArch = UB->getNumberOfObjects() > 1;
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000757 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
758 E = UB->end_objects();
759 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000760 Expected<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000761 if (UO) {
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000762 if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000763 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000764 if (OutputFormat == sysv)
765 outs() << o->getFileName() << " :\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000766 else if (MachO && OutputFormat == darwin) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000767 if (MoreThanOneFile || MoreThanOneArch)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000768 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000769 << I->getArchFlagName() << "):";
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000770 outs() << "\n";
771 }
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000772 printObjectSectionSizes(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000773 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000774 if (!MachO || MoreThanOneFile || MoreThanOneArch)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000775 outs() << o->getFileName() << " (for architecture "
Kevin Enderby59343a92016-12-16 22:54:02 +0000776 << I->getArchFlagName() << ")";
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000777 outs() << "\n";
778 }
779 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000780 } else if (auto E = isNotObjectErrorInvalidFileType(UO.takeError())) {
781 error(std::move(E), file, MoreThanOneArch ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000782 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000783 return;
Kevin Enderby42398052016-06-28 23:16:13 +0000784 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000785 I->getAsArchive()) {
786 std::unique_ptr<Archive> &UA = *AOrErr;
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000787 // This is an archive. Iterate over each member and display its sizes.
Mehdi Amini41af4302016-11-11 04:28:40 +0000788 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000789 for (auto &C : UA->children(Err)) {
790 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000791 if (!ChildOrErr) {
Kevin Enderby9acb1092016-05-31 20:35:34 +0000792 if (auto E = isNotObjectErrorInvalidFileType(
793 ChildOrErr.takeError()))
Lang Hamesfc209622016-07-14 02:24:01 +0000794 error(std::move(E), UA->getFileName(), C, MoreThanOneArch ?
Kevin Enderby59343a92016-12-16 22:54:02 +0000795 StringRef(I->getArchFlagName()) : StringRef());
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000796 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000797 }
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000798 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
799 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
800 if (OutputFormat == sysv)
801 outs() << o->getFileName() << " (ex " << UA->getFileName()
802 << "):\n";
Kevin Enderby10769742014-07-01 22:26:31 +0000803 else if (MachO && OutputFormat == darwin)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000804 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000805 << " (for architecture " << I->getArchFlagName() << "):\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000806 printObjectSectionSizes(o);
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000807 if (OutputFormat == berkeley) {
808 if (MachO)
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000809 outs() << UA->getFileName() << "(" << o->getFileName() << ")"
Kevin Enderby59343a92016-12-16 22:54:02 +0000810 << " (for architecture " << I->getArchFlagName()
Kevin Enderby1983fcf2014-06-19 22:03:18 +0000811 << ")\n";
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000812 else
813 outs() << o->getFileName() << " (ex " << UA->getFileName()
814 << ")\n";
815 }
816 }
817 }
Lang Hamesfc209622016-07-14 02:24:01 +0000818 if (Err)
819 error(std::move(Err), UA->getFileName());
Kevin Enderby42398052016-06-28 23:16:13 +0000820 } else {
821 consumeError(AOrErr.takeError());
822 error("Mach-O universal file: " + file + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +0000823 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +0000824 " is not a Mach-O file or an archive file");
Kevin Enderby4b8fc282014-06-18 22:04:40 +0000825 }
826 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000827 } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000828 if (!checkMachOAndArchFlags(o, file))
829 return;
Kevin Enderby5997c942016-12-01 19:12:55 +0000830 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000831 if (OutputFormat == sysv)
832 outs() << o->getFileName() << " :\n";
Kevin Enderby5997c942016-12-01 19:12:55 +0000833 else if (MachO && OutputFormat == darwin && MoreThanOneFile)
834 outs() << o->getFileName() << ":\n";
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000835 printObjectSectionSizes(o);
Kevin Enderby246a4602014-06-17 17:54:13 +0000836 if (OutputFormat == berkeley) {
Rafael Espindola1dc30a42016-02-09 21:35:14 +0000837 if (!MachO || MoreThanOneFile)
Kevin Enderby246a4602014-06-17 17:54:13 +0000838 outs() << o->getFileName();
839 outs() << "\n";
840 }
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000841 } else {
Kevin Enderby10769742014-07-01 22:26:31 +0000842 errs() << ToolName << ": " << file << ": "
843 << "Unrecognized file type.\n";
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000844 }
Michael J. Spencercc5f8d42011-09-29 00:59:18 +0000845 // System V adds an extra newline at the end of each file.
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000846 if (OutputFormat == sysv)
847 outs() << "\n";
848}
849
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000850static void printBerkelyTotals() {
851 std::string fmtbuf;
852 raw_string_ostream fmt(fmtbuf);
853 const char *radix_fmt = getRadixFmt();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000854 fmt << "%#7" << radix_fmt << "\t"
855 << "%#7" << radix_fmt << "\t"
856 << "%#7" << radix_fmt << "\t";
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000857 outs() << format(fmt.str().c_str(), TotalObjectText, TotalObjectData,
858 TotalObjectBss);
859 fmtbuf.clear();
Jordan Rupprecht8d60f9b2018-09-21 23:48:12 +0000860 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << "\t"
861 << "%7" PRIx64 "\t";
Hemant Kulkarni5f4ca2f2016-09-12 17:08:28 +0000862 outs() << format(fmt.str().c_str(), TotalObjectTotal, TotalObjectTotal)
863 << "(TOTALS)\n";
864}
865
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000866int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000867 InitLLVM X(argc, argv);
Serge Gueltondaeeb332019-06-05 10:32:28 +0000868 cl::HideUnrelatedOptions(SizeCat);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000869 cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
870
871 ToolName = argv[0];
872 if (OutputFormatShort.getNumOccurrences())
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000873 OutputFormat = static_cast<OutputFormatTy>(OutputFormatShort);
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000874 if (RadixShort.getNumOccurrences())
James Hendersonb3735ee2018-10-30 11:52:47 +0000875 Radix = RadixShort.getValue();
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000876
Fangrui Song64449e62018-11-22 00:44:17 +0000877 for (StringRef Arch : ArchFlags) {
878 if (Arch == "all") {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000879 ArchAll = true;
Kevin Enderby10769742014-07-01 22:26:31 +0000880 } else {
Fangrui Song64449e62018-11-22 00:44:17 +0000881 if (!MachOObjectFile::isValidArch(Arch)) {
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000882 outs() << ToolName << ": for the -arch option: Unknown architecture "
Fangrui Song64449e62018-11-22 00:44:17 +0000883 << "named '" << Arch << "'";
Kevin Enderbyafef4c92014-07-01 17:19:10 +0000884 return 1;
885 }
886 }
887 }
888
Fangrui Song64449e62018-11-22 00:44:17 +0000889 if (InputFilenames.empty())
Dimitry Andrice4f5d012017-12-18 19:46:56 +0000890 InputFilenames.push_back("a.out");
891
892 MoreThanOneFile = InputFilenames.size() > 1;
893 llvm::for_each(InputFilenames, printFileSectionSizes);
894 if (OutputFormat == berkeley && TotalSizes)
895 printBerkelyTotals();
896
Kevin Enderby64f7a992016-05-02 21:41:03 +0000897 if (HadError)
898 return 1;
Michael J. Spencerc4ad4662011-09-28 20:57:46 +0000899}