Fix build failure.
[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/raw_ostream.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/system_error.h"
29 #include <algorithm>
30 #include <string>
31 using namespace llvm;
32 using namespace object;
33
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"),
40                     clEnumValEnd),
41          cl::init(berkeley));
42
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"),
47                     clEnumValEnd),
48          cl::init(berkeley));
49
50 enum RadixTy {octal = 8, decimal = 10, hexadecimal = 16};
51 static cl::opt<unsigned int>
52        Radix("-radix",
53          cl::desc("Print size in radix. Only 8, 10, and 16 are valid"),
54          cl::init(decimal));
55
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"),
61                     clEnumValEnd),
62          cl::init(decimal));
63
64 static cl::list<std::string>
65        InputFilenames(cl::Positional, cl::desc("<input files>"),
66                       cl::ZeroOrMore);
67
68 static std::string ToolName;
69
70 ///  @brief If ec is not success, print the error and return true.
71 static bool error(error_code ec) {
72   if (!ec) return false;
73
74   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
75   outs().flush();
76   return true;
77 }
78
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 unsigned int getNumLengthAsString(uint64_t num) {
82   APInt conv(64, num);
83   SmallString<32> result;
84   conv.toString(result, Radix, false, true);
85   return result.size();
86 }
87
88 /// @brief Print the size of each section in @p o.
89 ///
90 /// The format used is determined by @c OutputFormat and @c Radix.
91 static void PrintObjectSectionSizes(ObjectFile *o) {
92   uint64_t total = 0;
93   std::string fmtbuf;
94   raw_string_ostream fmt(fmtbuf);
95
96   const char *radix_fmt = 0;
97   switch (Radix) {
98   case octal:
99     radix_fmt = "llo";
100     break;
101   case decimal:
102     radix_fmt = "llu";
103     break;
104   case hexadecimal:
105     radix_fmt = "llx";
106     break;
107   }
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     error_code ec;
115     for (ObjectFile::section_iterator i = o->begin_sections(),
116                                       e = o->end_sections(); i != e;
117                                       i.increment(ec)) {
118       if (error(ec))
119         return;
120       uint64_t size = 0;
121       if (error(i->getSize(size)))
122         return;
123       total += size;
124
125       StringRef name;
126       uint64_t addr = 0;
127       if (error(i->getName(name))) return;
128       if (error(i->getAddress(addr))) return;
129       max_name_len = std::max(max_name_len, name.size());
130       max_size_len = std::max(max_size_len,
131                               (std::size_t) getNumLengthAsString(size));
132       max_addr_len = std::max(max_addr_len,
133                               (std::size_t) getNumLengthAsString(addr));
134     }
135
136     // Add extra padding.
137     max_name_len += 2;
138     max_size_len += 2;
139     max_addr_len += 2;
140
141     // Setup header format.
142     fmt << "%-" << max_name_len << "s "
143         << "%" << max_size_len << "s "
144         << "%" << max_addr_len << "s\n";
145
146     // Print header
147     outs() << format(fmt.str().c_str(),
148                      static_cast<const char*>("section"),
149                      static_cast<const char*>("size"),
150                      static_cast<const char*>("addr"));
151     fmtbuf.clear();
152
153     // Setup per section format.
154     fmt << "%-" << max_name_len << "s "
155         << "%#" << max_size_len << radix_fmt << " "
156         << "%#" << max_addr_len << radix_fmt << "\n";
157
158     // Print each section.
159     for (ObjectFile::section_iterator i = o->begin_sections(),
160                                       e = o->end_sections(); i != e;
161                                       i.increment(ec)) {
162       if (error(ec))
163         return;
164
165       StringRef name;
166       uint64_t size = 0;
167       uint64_t addr = 0;
168       if (error(i->getName(name))) return;
169       if (error(i->getSize(size))) return;
170       if (error(i->getAddress(addr))) return;
171       std::string namestr = name;
172
173       outs() << format(fmt.str().c_str(),
174                        namestr.c_str(),
175                        size,
176                        addr);
177     }
178
179     // Print total.
180     fmtbuf.clear();
181     fmt << "%-" << max_name_len << "s "
182         << "%#" << max_size_len << radix_fmt << "\n";
183     outs() << format(fmt.str().c_str(),
184                      static_cast<const char*>("Total"),
185                      total);
186   } else {
187     // The Berkeley format does not display individual section sizes. It
188     // displays the cumulative size for each section type.
189     uint64_t total_text = 0;
190     uint64_t total_data = 0;
191     uint64_t total_bss = 0;
192
193     // Make one pass over the section table to calculate sizes.
194     error_code ec;
195     for (ObjectFile::section_iterator i = o->begin_sections(),
196                                       e = o->end_sections(); i != e;
197                                       i.increment(ec)) {
198       if (error(ec))
199         return;
200
201       uint64_t size = 0;
202       bool isText = false;
203       bool isData = false;
204       bool isBSS = false;
205       if (error(i->getSize(size))) return;
206       if (error(i->isText(isText))) return;
207       if (error(i->isData(isData))) return;
208       if (error(i->isBSS(isBSS))) return;
209       if (isText)
210         total_text += size;
211       else if (isData)
212         total_data += size;
213       else if (isBSS)
214         total_bss += size;
215     }
216
217     total = total_text + total_data + total_bss;
218
219     // Print result.
220     fmt << "%#7" << radix_fmt << " "
221         << "%#7" << radix_fmt << " "
222         << "%#7" << radix_fmt << " ";
223     outs() << format(fmt.str().c_str(),
224                      total_text,
225                      total_data,
226                      total_bss);
227     fmtbuf.clear();
228     fmt << "%7" << (Radix == octal ? "llo" : "llu") << " "
229         << "%7llx ";
230     outs() << format(fmt.str().c_str(),
231                      total,
232                      total);
233   }
234 }
235
236 /// @brief Print the section sizes for @p file. If @p file is an archive, print
237 ///        the section sizes for each archive member.
238 static void PrintFileSectionSizes(StringRef file) {
239   // If file is not stdin, check that it exists.
240   if (file != "-") {
241     bool exists;
242     if (sys::fs::exists(file, exists) || !exists) {
243       errs() << ToolName << ": '" << file << "': " << "No such file\n";
244       return;
245     }
246   }
247
248   // Attempt to open the binary.
249   OwningPtr<Binary> binary;
250   if (error_code ec = createBinary(file, binary)) {
251     errs() << ToolName << ": " << file << ": " << ec.message() << ".\n";
252     return;
253   }
254
255   if (Archive *a = dyn_cast<Archive>(binary.get())) {
256     // This is an archive. Iterate over each member and display its sizes.
257     for (object::Archive::child_iterator i = a->begin_children(),
258                                          e = a->end_children(); i != e; ++i) {
259       OwningPtr<Binary> child;
260       if (error_code ec = i->getAsBinary(child)) {
261         errs() << ToolName << ": " << file << ": " << ec.message() << ".\n";
262         continue;
263       }
264       if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
265         if (OutputFormat == sysv)
266           outs() << o->getFileName() << "   (ex " << a->getFileName()
267                   << "):\n";
268         PrintObjectSectionSizes(o);
269         if (OutputFormat == berkeley)
270           outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
271       }
272     }
273   } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
274     if (OutputFormat == sysv)
275       outs() << o->getFileName() << "  :\n";
276     PrintObjectSectionSizes(o);
277     if (OutputFormat == berkeley)
278       outs() << o->getFileName() << "\n";
279   } else {
280     errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n";
281   }
282   // System V adds an extra newline at the end of each file.
283   if (OutputFormat == sysv)
284     outs() << "\n";
285 }
286
287 int main(int argc, char **argv) {
288   // Print a stack trace if we signal out.
289   sys::PrintStackTraceOnErrorSignal();
290   PrettyStackTraceProgram X(argc, argv);
291
292   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
293   cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n");
294
295   ToolName = argv[0];
296   if (OutputFormatShort.getNumOccurrences())
297     OutputFormat = OutputFormatShort;
298   if (RadixShort.getNumOccurrences())
299     Radix = RadixShort;
300
301   if (InputFilenames.size() == 0)
302     InputFilenames.push_back("a.out");
303
304   if (OutputFormat == berkeley)
305     outs() << "   text    data     bss     "
306            << (Radix == octal ? "oct" : "dec")
307            << "     hex filename\n";
308
309   std::for_each(InputFilenames.begin(), InputFilenames.end(),
310                 PrintFileSectionSizes);
311
312   return 0;
313 }