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;
34 enum OutputFormatTy {berkeley, sysv};
35 static cl::opt<OutputFormatTy>
36 OutputFormat("format",
37 cl::desc("Specify output format"),
38 cl::values(clEnumVal(sysv, "System V format"),
39 clEnumVal(berkeley, "Berkeley format"),
43 static cl::opt<OutputFormatTy>
44 OutputFormatShort(cl::desc("Specify output format"),
45 cl::values(clEnumValN(sysv, "A", "System V format"),
46 clEnumValN(berkeley, "B", "Berkeley format"),
50 enum RadixTy {octal = 8, decimal = 10, hexadecimal = 16};
51 static cl::opt<unsigned int>
53 cl::desc("Print size in radix. Only 8, 10, and 16 are valid"),
56 static cl::opt<RadixTy>
57 RadixShort(cl::desc("Print size in radix:"),
58 cl::values(clEnumValN(octal, "o", "Print size in octal"),
59 clEnumValN(decimal, "d", "Print size in decimal"),
60 clEnumValN(hexadecimal, "x", "Print size in hexadecimal"),
64 static cl::list<std::string>
65 InputFilenames(cl::Positional, cl::desc("<input files>"),
68 static std::string ToolName;
70 /// @brief If ec is not success, print the error and return true.
71 static bool error(std::error_code ec) {
72 if (!ec) return false;
74 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
79 /// @brief Get the length of the string that represents @p num in Radix
80 /// including the leading 0x or 0 for hexadecimal and octal respectively.
81 static size_t getNumLengthAsString(uint64_t num) {
83 SmallString<32> result;
84 conv.toString(result, Radix, false, true);
88 /// @brief Print the size of each section in @p Obj.
90 /// The format used is determined by @c OutputFormat and @c Radix.
91 static void PrintObjectSectionSizes(ObjectFile *Obj) {
94 raw_string_ostream fmt(fmtbuf);
96 const char *radix_fmt = nullptr;
108 if (OutputFormat == sysv) {
109 // Run two passes over all sections. The first gets the lengths needed for
110 // formatting the output. The second actually does the output.
111 std::size_t max_name_len = strlen("section");
112 std::size_t max_size_len = strlen("size");
113 std::size_t max_addr_len = strlen("addr");
114 for (const SectionRef &Section : Obj->sections()) {
116 if (error(Section.getSize(size)))
122 if (error(Section.getName(name)))
124 if (error(Section.getAddress(addr)))
126 max_name_len = std::max(max_name_len, name.size());
127 max_size_len = std::max(max_size_len, getNumLengthAsString(size));
128 max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr));
131 // Add extra padding.
136 // Setup header format.
137 fmt << "%-" << max_name_len << "s "
138 << "%" << max_size_len << "s "
139 << "%" << max_addr_len << "s\n";
142 outs() << format(fmt.str().c_str(),
143 static_cast<const char*>("section"),
144 static_cast<const char*>("size"),
145 static_cast<const char*>("addr"));
148 // Setup per section format.
149 fmt << "%-" << max_name_len << "s "
150 << "%#" << max_size_len << radix_fmt << " "
151 << "%#" << max_addr_len << radix_fmt << "\n";
153 // Print each section.
154 for (const SectionRef &Section : Obj->sections()) {
158 if (error(Section.getName(name)))
160 if (error(Section.getSize(size)))
162 if (error(Section.getAddress(addr)))
164 std::string namestr = name;
166 outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr);
171 fmt << "%-" << max_name_len << "s "
172 << "%#" << max_size_len << radix_fmt << "\n";
173 outs() << format(fmt.str().c_str(),
174 static_cast<const char*>("Total"),
177 // The Berkeley format does not display individual section sizes. It
178 // displays the cumulative size for each section type.
179 uint64_t total_text = 0;
180 uint64_t total_data = 0;
181 uint64_t total_bss = 0;
183 // Make one pass over the section table to calculate sizes.
184 for (const SectionRef &Section : Obj->sections()) {
189 if (error(Section.getSize(size)))
191 if (error(Section.isText(isText)))
193 if (error(Section.isData(isData)))
195 if (error(Section.isBSS(isBSS)))
205 total = total_text + total_data + total_bss;
208 fmt << "%#7" << radix_fmt << " "
209 << "%#7" << radix_fmt << " "
210 << "%#7" << radix_fmt << " ";
211 outs() << format(fmt.str().c_str(),
216 fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << " "
218 outs() << format(fmt.str().c_str(),
224 /// @brief Print the section sizes for @p file. If @p file is an archive, print
225 /// the section sizes for each archive member.
226 static void PrintFileSectionSizes(StringRef file) {
227 // If file is not stdin, check that it exists.
230 if (sys::fs::exists(file, exists) || !exists) {
231 errs() << ToolName << ": '" << file << "': " << "No such file\n";
236 // Attempt to open the binary.
237 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
238 if (std::error_code EC = BinaryOrErr.getError()) {
239 errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
242 std::unique_ptr<Binary> binary(BinaryOrErr.get());
244 if (Archive *a = dyn_cast<Archive>(binary.get())) {
245 // This is an archive. Iterate over each member and display its sizes.
246 for (object::Archive::child_iterator i = a->child_begin(),
247 e = a->child_end(); i != e; ++i) {
248 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
249 if (std::error_code EC = ChildOrErr.getError()) {
250 errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
253 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
254 if (OutputFormat == sysv)
255 outs() << o->getFileName() << " (ex " << a->getFileName()
257 PrintObjectSectionSizes(o);
258 if (OutputFormat == berkeley)
259 outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
262 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
263 if (OutputFormat == sysv)
264 outs() << o->getFileName() << " :\n";
265 PrintObjectSectionSizes(o);
266 if (OutputFormat == berkeley)
267 outs() << o->getFileName() << "\n";
269 errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n";
271 // System V adds an extra newline at the end of each file.
272 if (OutputFormat == sysv)
276 int main(int argc, char **argv) {
277 // Print a stack trace if we signal out.
278 sys::PrintStackTraceOnErrorSignal();
279 PrettyStackTraceProgram X(argc, argv);
281 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
282 cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
285 if (OutputFormatShort.getNumOccurrences())
286 OutputFormat = OutputFormatShort;
287 if (RadixShort.getNumOccurrences())
290 if (InputFilenames.size() == 0)
291 InputFilenames.push_back("a.out");
293 if (OutputFormat == berkeley)
294 outs() << " text data bss "
295 << (Radix == octal ? "oct" : "dec")
296 << " hex filename\n";
298 std::for_each(InputFilenames.begin(), InputFilenames.end(),
299 PrintFileSectionSizes);