1 // Copyright (c) 2010, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
31 
32 // macho_dump.cc: Dump the contents of a Mach-O file. This is mostly
33 // a test program for the Mach_O::FatReader and Mach_O::Reader classes.
34 
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <mach-o/arch.h>
38 #include <sys/mman.h>
39 #include <stdint.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 
44 #include <sstream>
45 #include <string>
46 #include <vector>
47 
48 #include "common/byte_cursor.h"
49 #include "common/mac/arch_utilities.h"
50 #include "common/mac/macho_reader.h"
51 #include "common/path_helper.h"
52 
53 using google_breakpad::ByteBuffer;
54 using std::ostringstream;
55 using std::string;
56 using std::vector;
57 
58 namespace {
59 namespace mach_o = google_breakpad::mach_o;
60 
61 string program_name;
62 
check_syscall(int result,const char * operation,const char * filename)63 int check_syscall(int result, const char *operation, const char *filename) {
64   if (result < 0) {
65     fprintf(stderr, "%s: %s '%s': %s\n",
66             program_name.c_str(), operation,
67             filename, strerror(errno));
68     exit(1);
69   }
70   return result;
71 }
72 
73 class DumpSection: public mach_o::Reader::SectionHandler {
74  public:
DumpSection()75   DumpSection() : index_(0) { }
HandleSection(const mach_o::Section & section)76   bool HandleSection(const mach_o::Section &section) {
77     printf("        section %d '%s' in segment '%s'\n"
78            "          address: 0x%llx\n"
79            "          alignment: 1 << %d B\n"
80            "          flags: %d\n"
81            "          size: %ld\n",
82            index_++, section.section_name.c_str(), section.segment_name.c_str(),
83            section.address, section.align,
84            mach_o::SectionFlags(section.flags),
85            section.contents.Size());
86     return true;
87   }
88 
89  private:
90   int index_;
91 };
92 
93 class DumpCommand: public mach_o::Reader::LoadCommandHandler {
94  public:
DumpCommand(mach_o::Reader * reader)95   DumpCommand(mach_o::Reader *reader) : reader_(reader), index_(0) { }
UnknownCommand(mach_o::LoadCommandType type,const ByteBuffer & contents)96   bool UnknownCommand(mach_o::LoadCommandType type,
97                       const ByteBuffer &contents) {
98     printf("      load command %d: %d", index_++, type);
99     return true;
100   }
SegmentCommand(const mach_o::Segment & segment)101   bool SegmentCommand(const mach_o::Segment &segment) {
102     printf("      load command %d: %s-bit segment '%s'\n"
103            "        address: 0x%llx\n"
104            "        memory size: 0x%llx\n"
105            "        maximum protection: 0x%x\n"
106            "        initial protection: 0x%x\n"
107            "        flags: %d\n"
108            "        section_list size: %ld B\n",
109            index_++, (segment.bits_64 ? "64" : "32"), segment.name.c_str(),
110            segment.vmaddr, segment.vmsize, segment.maxprot,
111            segment.initprot, mach_o::SegmentFlags(segment.flags),
112            segment.section_list.Size());
113 
114     DumpSection dump_section;
115     return reader_->WalkSegmentSections(segment, &dump_section);
116   }
117  private:
118   mach_o::Reader *reader_;
119   int index_;
120 };
121 
DumpFile(const char * filename)122 void DumpFile(const char *filename) {
123   int fd = check_syscall(open(filename, O_RDONLY), "opening", filename);
124   struct stat attributes;
125   check_syscall(fstat(fd, &attributes),
126                 "getting file attributes for", filename);
127   void *mapping = mmap(NULL, attributes.st_size, PROT_READ,
128                        MAP_PRIVATE, fd, 0);
129   close(fd);
130   check_syscall(mapping == (void *)-1 ? -1 : 0,
131                 "mapping contents of", filename);
132 
133   mach_o::FatReader::Reporter fat_reporter(filename);
134   mach_o::FatReader fat_reader(&fat_reporter);
135   if (!fat_reader.Read(reinterpret_cast<uint8_t *>(mapping),
136                        attributes.st_size)) {
137     exit(1);
138   }
139   printf("filename: %s\n", filename);
140   size_t object_files_size;
141   const SuperFatArch* super_fat_object_files =
142       fat_reader.object_files(&object_files_size);
143   struct fat_arch *object_files;
144   if (!super_fat_object_files->ConvertToFatArch(object_files)) {
145     exit(1);
146   }
147   printf("  object file count: %ld\n", object_files_size);
148   for (size_t i = 0; i < object_files_size; i++) {
149     const struct fat_arch &file = object_files[i];
150     const NXArchInfo *fat_arch_info =
151         google_breakpad::BreakpadGetArchInfoFromCpuType(
152             file.cputype, file.cpusubtype);
153     printf("\n  object file %ld:\n"
154            "    fat header:\n:"
155            "      CPU type: %s (%s)\n"
156            "      size: %d B\n"
157            "      alignment: 1<<%d B\n",
158            i, fat_arch_info->name, fat_arch_info->description,
159            file.size, file.align);
160 
161     ostringstream name;
162     name << filename;
163     if (object_files_size > 1)
164       name << ", object file #" << i;
165     ByteBuffer file_contents(reinterpret_cast<uint8_t *>(mapping)
166                              + file.offset, file.size);
167     mach_o::Reader::Reporter reporter(name.str());
168     mach_o::Reader reader(&reporter);
169     if (!reader.Read(file_contents, file.cputype, file.cpusubtype)) {
170       exit(1);
171     }
172 
173     const NXArchInfo *macho_arch_info =
174       NXGetArchInfoFromCpuType(reader.cpu_type(),
175                                reader.cpu_subtype());
176     printf("    Mach-O header:\n"
177            "      word size: %s\n"
178            "      CPU type: %s (%s)\n"
179            "      File type: %d\n"
180            "      flags: %x\n",
181            (reader.bits_64() ? "64 bits" : "32 bits"),
182            macho_arch_info->name, macho_arch_info->description,
183            reader.file_type(), reader.flags());
184 
185     DumpCommand dump_command(&reader);
186     reader.WalkLoadCommands(&dump_command);
187   }
188   munmap(mapping, attributes.st_size);
189 }
190 
191 }  // namespace
192 
main(int argc,char ** argv)193 int main(int argc, char **argv) {
194   program_name = google_breakpad::BaseName(argv[0]);
195   if (argc == 1) {
196     fprintf(stderr, "Usage: %s FILE ...\n"
197             "Dump the contents of the Mach-O or fat binary files "
198             "'FILE ...'.\n", program_name.c_str());
199   }
200   for (int i = 1; i < argc; i++) {
201     DumpFile(argv[i]);
202   }
203 }
204