1 //===-- llvm-size.cpp - Print the size of each object section -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that works like traditional Unix "size",
11 // that is, it prints out the size of each section, and the total size of all
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/raw_ostream.h"
30 #include <system_error>
32 using namespace object;
33 using std::error_code;
35 enum OutputFormatTy {berkeley, sysv};
36 static cl::opt<OutputFormatTy>
37 OutputFormat("format",
38 cl::desc("Specify output format"),
39 cl::values(clEnumVal(sysv, "System V format"),
40 clEnumVal(berkeley, "Berkeley format"),
44 static cl::opt<OutputFormatTy>
45 OutputFormatShort(cl::desc("Specify output format"),
46 cl::values(clEnumValN(sysv, "A", "System V format"),
47 clEnumValN(berkeley, "B", "Berkeley format"),
51 enum RadixTy {octal = 8, decimal = 10, hexadecimal = 16};
52 static cl::opt<unsigned int>
54 cl::desc("Print size in radix. Only 8, 10, and 16 are valid"),
57 static cl::opt<RadixTy>
58 RadixShort(cl::desc("Print size in radix:"),
59 cl::values(clEnumValN(octal, "o", "Print size in octal"),
60 clEnumValN(decimal, "d", "Print size in decimal"),
61 clEnumValN(hexadecimal, "x", "Print size in hexadecimal"),
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input files>"),
69 static std::string ToolName;
71 /// @brief If ec is not success, print the error and return true.
72 static bool error(error_code ec) {
73 if (!ec) return false;
75 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
80 /// @brief Get the length of the string that represents @p num in Radix
81 /// including the leading 0x or 0 for hexadecimal and octal respectively.
82 static size_t getNumLengthAsString(uint64_t num) {
84 SmallString<32> result;
85 conv.toString(result, Radix, false, true);
89 /// @brief Print the size of each section in @p Obj.
91 /// The format used is determined by @c OutputFormat and @c Radix.
92 static void PrintObjectSectionSizes(ObjectFile *Obj) {
95 raw_string_ostream fmt(fmtbuf);
97 const char *radix_fmt = nullptr;
109 if (OutputFormat == sysv) {
110 // Run two passes over all sections. The first gets the lengths needed for
111 // formatting the output. The second actually does the output.
112 std::size_t max_name_len = strlen("section");
113 std::size_t max_size_len = strlen("size");
114 std::size_t max_addr_len = strlen("addr");
115 for (const SectionRef &Section : Obj->sections()) {
117 if (error(Section.getSize(size)))
123 if (error(Section.getName(name)))
125 if (error(Section.getAddress(addr)))
127 max_name_len = std::max(max_name_len, name.size());
128 max_size_len = std::max(max_size_len, getNumLengthAsString(size));
129 max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr));
132 // Add extra padding.
137 // Setup header format.
138 fmt << "%-" << max_name_len << "s "
139 << "%" << max_size_len << "s "
140 << "%" << max_addr_len << "s\n";
143 outs() << format(fmt.str().c_str(),
144 static_cast<const char*>("section"),
145 static_cast<const char*>("size"),
146 static_cast<const char*>("addr"));
149 // Setup per section format.
150 fmt << "%-" << max_name_len << "s "
151 << "%#" << max_size_len << radix_fmt << " "
152 << "%#" << max_addr_len << radix_fmt << "\n";
154 // Print each section.
155 for (const SectionRef &Section : Obj->sections()) {
159 if (error(Section.getName(name)))
161 if (error(Section.getSize(size)))
163 if (error(Section.getAddress(addr)))
165 std::string namestr = name;
167 outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr);
172 fmt << "%-" << max_name_len << "s "
173 << "%#" << max_size_len << radix_fmt << "\n";
174 outs() << format(fmt.str().c_str(),
175 static_cast<const char*>("Total"),
178 // The Berkeley format does not display individual section sizes. It
179 // displays the cumulative size for each section type.
180 uint64_t total_text = 0;
181 uint64_t total_data = 0;
182 uint64_t total_bss = 0;
184 // Make one pass over the section table to calculate sizes.
185 for (const SectionRef &Section : Obj->sections()) {
190 if (error(Section.getSize(size)))
192 if (error(Section.isText(isText)))
194 if (error(Section.isData(isData)))
196 if (error(Section.isBSS(isBSS)))
206 total = total_text + total_data + total_bss;
209 fmt << "%#7" << radix_fmt << " "
210 << "%#7" << radix_fmt << " "
211 << "%#7" << radix_fmt << " ";
212 outs() << format(fmt.str().c_str(),
217 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << " "
219 outs() << format(fmt.str().c_str(),
225 /// @brief Print the section sizes for @p file. If @p file is an archive, print
226 /// the section sizes for each archive member.
227 static void PrintFileSectionSizes(StringRef file) {
228 // If file is not stdin, check that it exists.
231 if (sys::fs::exists(file, exists) || !exists) {
232 errs() << ToolName << ": '" << file << "': " << "No such file\n";
237 // Attempt to open the binary.
238 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
239 if (error_code EC = BinaryOrErr.getError()) {
240 errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
243 std::unique_ptr<Binary> binary(BinaryOrErr.get());
245 if (Archive *a = dyn_cast<Archive>(binary.get())) {
246 // This is an archive. Iterate over each member and display its sizes.
247 for (object::Archive::child_iterator i = a->child_begin(),
248 e = a->child_end(); i != e; ++i) {
249 std::unique_ptr<Binary> child;
250 if (error_code ec = i->getAsBinary(child)) {
251 errs() << ToolName << ": " << file << ": " << ec.message() << ".\n";
254 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
255 if (OutputFormat == sysv)
256 outs() << o->getFileName() << " (ex " << a->getFileName()
258 PrintObjectSectionSizes(o);
259 if (OutputFormat == berkeley)
260 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
263 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
264 if (OutputFormat == sysv)
265 outs() << o->getFileName() << " :\n";
266 PrintObjectSectionSizes(o);
267 if (OutputFormat == berkeley)
268 outs() << o->getFileName() << "\n";
270 errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n";
272 // System V adds an extra newline at the end of each file.
273 if (OutputFormat == sysv)
277 int main(int argc, char **argv) {
278 // Print a stack trace if we signal out.
279 sys::PrintStackTraceOnErrorSignal();
280 PrettyStackTraceProgram X(argc, argv);
282 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
283 cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
286 if (OutputFormatShort.getNumOccurrences())
287 OutputFormat = OutputFormatShort;
288 if (RadixShort.getNumOccurrences())
291 if (InputFilenames.size() == 0)
292 InputFilenames.push_back("a.out");
294 if (OutputFormat == berkeley)
295 outs() << " text data bss "
296 << (Radix == octal ? "oct" : "dec")
297 << " hex filename\n";
299 std::for_each(InputFilenames.begin(), InputFilenames.end(),
300 PrintFileSectionSizes);