Don't use 'using std::error_code' in include/llvm.
[oota-llvm.git] / tools / llvm-size / llvm-size.cpp
1 //===-- llvm-size.cpp - Print the size of each object section -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // sections.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
28 #include <algorithm>
29 #include <string>
30 #include <system_error>
31 using namespace llvm;
32 using namespace object;
33 using std::error_code;
34
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"),
41                     clEnumValEnd),
42          cl::init(berkeley));
43
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"),
48                     clEnumValEnd),
49          cl::init(berkeley));
50
51 enum RadixTy {octal = 8, decimal = 10, hexadecimal = 16};
52 static cl::opt<unsigned int>
53        Radix("-radix",
54          cl::desc("Print size in radix. Only 8, 10, and 16 are valid"),
55          cl::init(decimal));
56
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"),
62                     clEnumValEnd),
63          cl::init(decimal));
64
65 static cl::list<std::string>
66        InputFilenames(cl::Positional, cl::desc("<input files>"),
67                       cl::ZeroOrMore);
68
69 static std::string ToolName;
70
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;
74
75   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
76   outs().flush();
77   return true;
78 }
79
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) {
83   APInt conv(64, num);
84   SmallString<32> result;
85   conv.toString(result, Radix, false, true);
86   return result.size();
87 }
88
89 /// @brief Print the size of each section in @p Obj.
90 ///
91 /// The format used is determined by @c OutputFormat and @c Radix.
92 static void PrintObjectSectionSizes(ObjectFile *Obj) {
93   uint64_t total = 0;
94   std::string fmtbuf;
95   raw_string_ostream fmt(fmtbuf);
96
97   const char *radix_fmt = nullptr;
98   switch (Radix) {
99   case octal:
100     radix_fmt = PRIo64;
101     break;
102   case decimal:
103     radix_fmt = PRIu64;
104     break;
105   case hexadecimal:
106     radix_fmt = PRIx64;
107     break;
108   }
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()) {
116       uint64_t size = 0;
117       if (error(Section.getSize(size)))
118         return;
119       total += size;
120
121       StringRef name;
122       uint64_t addr = 0;
123       if (error(Section.getName(name)))
124         return;
125       if (error(Section.getAddress(addr)))
126         return;
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));
130     }
131
132     // Add extra padding.
133     max_name_len += 2;
134     max_size_len += 2;
135     max_addr_len += 2;
136
137     // Setup header format.
138     fmt << "%-" << max_name_len << "s "
139         << "%" << max_size_len << "s "
140         << "%" << max_addr_len << "s\n";
141
142     // Print header
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"));
147     fmtbuf.clear();
148
149     // Setup per section format.
150     fmt << "%-" << max_name_len << "s "
151         << "%#" << max_size_len << radix_fmt << " "
152         << "%#" << max_addr_len << radix_fmt << "\n";
153
154     // Print each section.
155     for (const SectionRef &Section : Obj->sections()) {
156       StringRef name;
157       uint64_t size = 0;
158       uint64_t addr = 0;
159       if (error(Section.getName(name)))
160         return;
161       if (error(Section.getSize(size)))
162         return;
163       if (error(Section.getAddress(addr)))
164         return;
165       std::string namestr = name;
166
167       outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr);
168     }
169
170     // Print total.
171     fmtbuf.clear();
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"),
176                      total);
177   } else {
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;
183
184     // Make one pass over the section table to calculate sizes.
185     for (const SectionRef &Section : Obj->sections()) {
186       uint64_t size = 0;
187       bool isText = false;
188       bool isData = false;
189       bool isBSS = false;
190       if (error(Section.getSize(size)))
191         return;
192       if (error(Section.isText(isText)))
193         return;
194       if (error(Section.isData(isData)))
195         return;
196       if (error(Section.isBSS(isBSS)))
197         return;
198       if (isText)
199         total_text += size;
200       else if (isData)
201         total_data += size;
202       else if (isBSS)
203         total_bss += size;
204     }
205
206     total = total_text + total_data + total_bss;
207
208     // Print result.
209     fmt << "%#7" << radix_fmt << " "
210         << "%#7" << radix_fmt << " "
211         << "%#7" << radix_fmt << " ";
212     outs() << format(fmt.str().c_str(),
213                      total_text,
214                      total_data,
215                      total_bss);
216     fmtbuf.clear();
217     fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << " "
218         << "%7" PRIx64 " ";
219     outs() << format(fmt.str().c_str(),
220                      total,
221                      total);
222   }
223 }
224
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.
229   if (file != "-") {
230     bool exists;
231     if (sys::fs::exists(file, exists) || !exists) {
232       errs() << ToolName << ": '" << file << "': " << "No such file\n";
233       return;
234     }
235   }
236
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";
241     return;
242   }
243   std::unique_ptr<Binary> binary(BinaryOrErr.get());
244
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";
252         continue;
253       }
254       if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
255         if (OutputFormat == sysv)
256           outs() << o->getFileName() << "   (ex " << a->getFileName()
257                   << "):\n";
258         PrintObjectSectionSizes(o);
259         if (OutputFormat == berkeley)
260           outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
261       }
262     }
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";
269   } else {
270     errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n";
271   }
272   // System V adds an extra newline at the end of each file.
273   if (OutputFormat == sysv)
274     outs() << "\n";
275 }
276
277 int main(int argc, char **argv) {
278   // Print a stack trace if we signal out.
279   sys::PrintStackTraceOnErrorSignal();
280   PrettyStackTraceProgram X(argc, argv);
281
282   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
283   cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
284
285   ToolName = argv[0];
286   if (OutputFormatShort.getNumOccurrences())
287     OutputFormat = OutputFormatShort;
288   if (RadixShort.getNumOccurrences())
289     Radix = RadixShort;
290
291   if (InputFilenames.size() == 0)
292     InputFilenames.push_back("a.out");
293
294   if (OutputFormat == berkeley)
295     outs() << "   text    data     bss     "
296            << (Radix == octal ? "oct" : "dec")
297            << "     hex filename\n";
298
299   std::for_each(InputFilenames.begin(), InputFilenames.end(),
300                 PrintFileSectionSizes);
301
302   return 0;
303 }