[email protected] | f76b3b0 | 2009-05-06 04:02:10 | [diff] [blame] | 1 | // Copyright (c) 2009 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
[email protected] | 04ca1bc | 2009-05-08 23:00:29 | [diff] [blame] | 5 | #include "courgette/image_info.h" |
[email protected] | f76b3b0 | 2009-05-06 04:02:10 | [diff] [blame] | 6 | |
| 7 | #include <memory.h> |
| 8 | #include <algorithm> |
| 9 | #include <map> |
| 10 | #include <set> |
| 11 | #include <sstream> |
| 12 | #include <vector> |
| 13 | |
| 14 | #include "base/logging.h" |
| 15 | |
| 16 | namespace courgette { |
| 17 | |
| 18 | std::string SectionName(const Section* section) { |
| 19 | if (section == NULL) |
| 20 | return "<none>"; |
| 21 | char name[9]; |
| 22 | memcpy(name, section->name, 8); |
| 23 | name[8] = '\0'; // Ensure termination. |
| 24 | return name; |
| 25 | } |
| 26 | |
| 27 | PEInfo::PEInfo() |
| 28 | : failure_reason_("uninitialized"), |
| 29 | start_(0), end_(0), length_(0), |
| 30 | is_PE32_plus_(0), file_length_(0), has_text_section_(false) { |
| 31 | } |
| 32 | |
| 33 | void PEInfo::Init(const void* start, size_t length) { |
| 34 | start_ = reinterpret_cast<const uint8*>(start); |
| 35 | length_ = length; |
| 36 | end_ = start_ + length_; |
| 37 | failure_reason_ = "unparsed"; |
| 38 | } |
| 39 | |
| 40 | // DescribeRVA is for debugging only. I would put it under #ifdef DEBUG except |
| 41 | // that during development I'm finding I need to call it when compiled in |
| 42 | // Release mode. Hence: |
| 43 | // TODO(sra): make this compile only for debug mode. |
| 44 | std::string PEInfo::DescribeRVA(RVA rva) const { |
| 45 | const Section* section = RVAToSection(rva); |
| 46 | std::ostringstream s; |
| 47 | s << std::hex << rva; |
| 48 | if (section) { |
| 49 | s << " ("; |
| 50 | s << SectionName(section) << "+" |
| 51 | << std::hex << (rva - section->virtual_address) |
| 52 | << ")"; |
| 53 | } |
| 54 | return s.str(); |
| 55 | } |
| 56 | |
| 57 | const Section* PEInfo::FindNextSection(uint32 fileOffset) const { |
| 58 | const Section* best = 0; |
| 59 | for (int i = 0; i < number_of_sections_; i++) { |
| 60 | const Section* section = §ions_[i]; |
[email protected] | 077d7bd | 2009-05-27 19:12:32 | [diff] [blame^] | 61 | if (section->size_of_raw_data > 0) { // i.e. has data in file. |
| 62 | if (fileOffset <= section->file_offset_of_raw_data) { |
| 63 | if (best == 0 || |
| 64 | section->file_offset_of_raw_data < best->file_offset_of_raw_data) { |
| 65 | best = section; |
| 66 | } |
[email protected] | f76b3b0 | 2009-05-06 04:02:10 | [diff] [blame] | 67 | } |
| 68 | } |
| 69 | } |
| 70 | return best; |
| 71 | } |
| 72 | |
| 73 | const Section* PEInfo::RVAToSection(RVA rva) const { |
| 74 | for (int i = 0; i < number_of_sections_; i++) { |
| 75 | const Section* section = §ions_[i]; |
| 76 | uint32 offset = rva - section->virtual_address; |
| 77 | if (offset < section->virtual_size) { |
| 78 | return section; |
| 79 | } |
| 80 | } |
| 81 | return NULL; |
| 82 | } |
| 83 | |
| 84 | int PEInfo::RVAToFileOffset(RVA rva) const { |
| 85 | const Section* section = RVAToSection(rva); |
| 86 | if (section) { |
| 87 | uint32 offset = rva - section->virtual_address; |
| 88 | if (offset < section->size_of_raw_data) { |
| 89 | return section->file_offset_of_raw_data + offset; |
| 90 | } else { |
| 91 | return kNoOffset; // In section but not in file (e.g. uninit data). |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Small RVA values point into the file header in the loaded image. |
| 96 | // RVA 0 is the module load address which Windows uses as the module handle. |
| 97 | // RVA 2 sometimes occurs, I'm not sure what it is, but it would map into the |
| 98 | // DOS header. |
| 99 | if (rva == 0 || rva == 2) |
| 100 | return rva; |
| 101 | |
| 102 | NOTREACHED(); |
| 103 | return kNoOffset; |
| 104 | } |
| 105 | |
| 106 | const uint8* PEInfo::RVAToPointer(RVA rva) const { |
| 107 | int file_offset = RVAToFileOffset(rva); |
| 108 | if (file_offset == kNoOffset) |
| 109 | return NULL; |
| 110 | else |
| 111 | return start_ + file_offset; |
| 112 | } |
| 113 | |
| 114 | RVA PEInfo::FileOffsetToRVA(uint32 file_offset) const { |
| 115 | for (int i = 0; i < number_of_sections_; i++) { |
| 116 | const Section* section = §ions_[i]; |
| 117 | uint32 offset = file_offset - section->file_offset_of_raw_data; |
| 118 | if (offset < section->size_of_raw_data) { |
| 119 | return section->virtual_address + offset; |
| 120 | } |
| 121 | } |
| 122 | return 0; |
| 123 | } |
| 124 | |
| 125 | //////////////////////////////////////////////////////////////////////////////// |
| 126 | |
| 127 | namespace { |
| 128 | |
| 129 | // Constants and offsets gleaned from WINNT.H and various articles on the |
| 130 | // format of Windows PE executables. |
| 131 | |
| 132 | // This is FIELD_OFFSET(IMAGE_DOS_HEADER, e_lfanew): |
| 133 | const size_t kOffsetOfFileAddressOfNewExeHeader = 0x3c; |
| 134 | |
| 135 | const uint16 kImageNtOptionalHdr32Magic = 0x10b; |
| 136 | const uint16 kImageNtOptionalHdr64Magic = 0x20b; |
| 137 | |
| 138 | const size_t kSizeOfCoffHeader = 20; |
| 139 | const size_t kOffsetOfDataDirectoryFromImageOptionalHeader32 = 96; |
| 140 | const size_t kOffsetOfDataDirectoryFromImageOptionalHeader64 = 112; |
| 141 | |
| 142 | // These helper functions avoid the need for casts in the main code. |
| 143 | inline uint16 ReadU16(const uint8* address, size_t offset) { |
| 144 | return *reinterpret_cast<const uint16*>(address + offset); |
| 145 | } |
| 146 | |
| 147 | inline uint32 ReadU32(const uint8* address, size_t offset) { |
| 148 | return *reinterpret_cast<const uint32*>(address + offset); |
| 149 | } |
| 150 | |
| 151 | inline uint64 ReadU64(const uint8* address, size_t offset) { |
| 152 | return *reinterpret_cast<const uint64*>(address + offset); |
| 153 | } |
| 154 | |
| 155 | } // namespace |
| 156 | |
| 157 | // ParseHeader attempts to match up the buffer with the Windows data |
| 158 | // structures that exist within a Windows 'Portable Executable' format file. |
| 159 | // Returns 'true' if the buffer matches, and 'false' if the data looks |
| 160 | // suspicious. Rather than try to 'map' the buffer to the numerous windows |
| 161 | // structures, we extract the information we need into the courgette::PEInfo |
| 162 | // structure. |
| 163 | // |
| 164 | bool PEInfo::ParseHeader() { |
| 165 | if (length_ < kOffsetOfFileAddressOfNewExeHeader + 4 /*size*/) |
| 166 | return Bad("Too small"); |
| 167 | |
| 168 | // Have 'MZ' magic for a DOS header? |
| 169 | if (start_[0] != 'M' || start_[1] != 'Z') |
| 170 | return Bad("Not MZ"); |
| 171 | |
| 172 | // offset from DOS header to PE header is stored in DOS header. |
| 173 | uint32 offset = ReadU32(start_, kOffsetOfFileAddressOfNewExeHeader); |
| 174 | |
| 175 | const uint8* const pe_header = start_ + offset; |
| 176 | const size_t kMinPEHeaderSize = 4 /*signature*/ + kSizeOfCoffHeader; |
| 177 | if (pe_header <= start_ || pe_header >= end_ - kMinPEHeaderSize) |
| 178 | return Bad("Bad offset to PE header"); |
| 179 | |
| 180 | if (offset % 8 != 0) |
| 181 | return Bad("Misaligned PE header"); |
| 182 | |
| 183 | // The 'PE' header is an IMAGE_NT_HEADERS structure as defined in WINNT.H. |
| 184 | // See http://msdn.microsoft.com/en-us/library/ms680336(VS.85).aspx |
| 185 | // |
| 186 | // The first field of the IMAGE_NT_HEADERS is the signature. |
| 187 | if (!(pe_header[0] == 'P' && |
| 188 | pe_header[1] == 'E' && |
| 189 | pe_header[2] == 0 && |
| 190 | pe_header[3] == 0)) |
| 191 | return Bad("no PE signature"); |
| 192 | |
| 193 | // The second field of the IMAGE_NT_HEADERS is the COFF header. |
| 194 | // The COFF header is also called an IMAGE_FILE_HEADER |
| 195 | // http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx |
| 196 | const uint8* const coff_header = pe_header + 4; |
| 197 | machine_type_ = ReadU16(coff_header, 0); |
| 198 | number_of_sections_ = ReadU16(coff_header, 2); |
| 199 | size_of_optional_header_ = ReadU16(coff_header, 16); |
| 200 | |
| 201 | // The rest of the IMAGE_NT_HEADERS is the IMAGE_OPTIONAL_HEADER(32|64) |
| 202 | const uint8* const optional_header = coff_header + kSizeOfCoffHeader; |
| 203 | optional_header_ = optional_header; |
| 204 | |
| 205 | if (optional_header + size_of_optional_header_ >= end_) |
| 206 | return Bad("optional header past end of file"); |
| 207 | |
| 208 | // Check we can read the magic. |
| 209 | if (size_of_optional_header_ < 2) |
| 210 | return Bad("optional header no magic"); |
| 211 | |
| 212 | uint16 magic = ReadU16(optional_header, 0); |
| 213 | |
| 214 | if (magic == kImageNtOptionalHdr32Magic) { |
| 215 | is_PE32_plus_ = false; |
| 216 | offset_of_data_directories_ = |
| 217 | kOffsetOfDataDirectoryFromImageOptionalHeader32; |
| 218 | } else if (magic == kImageNtOptionalHdr64Magic) { |
| 219 | is_PE32_plus_ = true; |
| 220 | offset_of_data_directories_ = |
| 221 | kOffsetOfDataDirectoryFromImageOptionalHeader64; |
| 222 | } else { |
| 223 | return Bad("unrecognized magic"); |
| 224 | } |
| 225 | |
| 226 | // Check that we can read the rest of the the fixed fields. Data directories |
| 227 | // directly follow the fixed fields of the IMAGE_OPTIONAL_HEADER. |
| 228 | if (size_of_optional_header_ < offset_of_data_directories_) |
| 229 | return Bad("optional header too short"); |
| 230 | |
| 231 | // The optional header is either an IMAGE_OPTIONAL_HEADER32 or |
| 232 | // IMAGE_OPTIONAL_HEADER64 |
| 233 | // http://msdn.microsoft.com/en-us/library/ms680339(VS.85).aspx |
| 234 | // |
| 235 | // Copy the fields we care about. |
| 236 | size_of_code_ = ReadU32(optional_header, 4); |
| 237 | size_of_initialized_data_ = ReadU32(optional_header, 8); |
| 238 | size_of_uninitialized_data_ = ReadU32(optional_header, 12); |
| 239 | base_of_code_ = ReadU32(optional_header, 20); |
| 240 | if (is_PE32_plus_) { |
| 241 | base_of_data_ = 0; |
| 242 | image_base_ = ReadU64(optional_header, 24); |
| 243 | } else { |
| 244 | base_of_data_ = ReadU32(optional_header, 24); |
| 245 | image_base_ = ReadU32(optional_header, 28); |
| 246 | } |
| 247 | size_of_image_ = ReadU32(optional_header, 56); |
| 248 | number_of_data_directories_ = |
| 249 | ReadU32(optional_header, (is_PE32_plus_ ? 108 : 92)); |
| 250 | |
| 251 | if (size_of_code_ >= length_ || |
| 252 | size_of_initialized_data_ >= length_ || |
| 253 | size_of_code_ + size_of_initialized_data_ >= length_) { |
| 254 | // This validation fires on some perfectly fine executables. |
| 255 | // return Bad("code or initialized data too big"); |
| 256 | } |
| 257 | |
| 258 | // TODO(sra): we can probably get rid of most of the data directories. |
| 259 | bool b = true; |
| 260 | // 'b &= ...' could be short circuit 'b = b && ...' but it is not necessary |
| 261 | // for correctness and it compiles smaller this way. |
| 262 | b &= ReadDataDirectory(0, &export_table_); |
| 263 | b &= ReadDataDirectory(1, &import_table_); |
| 264 | b &= ReadDataDirectory(2, &resource_table_); |
| 265 | b &= ReadDataDirectory(3, &exception_table_); |
| 266 | b &= ReadDataDirectory(5, &base_relocation_table_); |
| 267 | b &= ReadDataDirectory(11, &bound_import_table_); |
| 268 | b &= ReadDataDirectory(12, &import_address_table_); |
| 269 | b &= ReadDataDirectory(13, &delay_import_descriptor_); |
| 270 | b &= ReadDataDirectory(14, &clr_runtime_header_); |
| 271 | if (!b) { |
| 272 | return Bad("malformed data directory"); |
| 273 | } |
| 274 | |
| 275 | // Sections follow the optional header. |
| 276 | sections_ = |
| 277 | reinterpret_cast<const Section*>(optional_header + |
| 278 | size_of_optional_header_); |
| 279 | file_length_ = 0; |
| 280 | |
| 281 | for (int i = 0; i < number_of_sections_; ++i) { |
| 282 | const Section* section = §ions_[i]; |
| 283 | |
| 284 | // TODO(sra): consider using the 'characteristics' field of the section |
| 285 | // header to see if the section contains instructions. |
| 286 | if (memcmp(section->name, ".text", 6) == 0) |
| 287 | has_text_section_ = true; |
| 288 | |
| 289 | uint32 section_end = |
| 290 | section->file_offset_of_raw_data + section->size_of_raw_data; |
| 291 | if (section_end > file_length_) |
| 292 | file_length_ = section_end; |
| 293 | } |
| 294 | |
| 295 | failure_reason_ = NULL; |
| 296 | return true; |
| 297 | } |
| 298 | |
| 299 | bool PEInfo::ReadDataDirectory(int index, ImageDataDirectory* directory) { |
| 300 | if (index < number_of_data_directories_) { |
| 301 | size_t offset = index * 8 + offset_of_data_directories_; |
| 302 | if (offset >= size_of_optional_header_) |
| 303 | return Bad("number of data directories inconsistent"); |
| 304 | const uint8* data_directory = optional_header_ + offset; |
| 305 | if (data_directory < start_ || data_directory + 8 >= end_) |
| 306 | return Bad("data directory outside image"); |
| 307 | RVA rva = ReadU32(data_directory, 0); |
| 308 | size_t size = ReadU32(data_directory, 4); |
| 309 | if (size > size_of_image_) |
| 310 | return Bad("data directory size too big"); |
| 311 | |
| 312 | // TODO(sra): validate RVA. |
| 313 | directory->address_ = rva; |
| 314 | directory->size_ = size; |
| 315 | return true; |
| 316 | } else { |
| 317 | directory->address_ = 0; |
| 318 | directory->size_ = 0; |
| 319 | return true; |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | bool PEInfo::Bad(const char* reason) { |
| 324 | failure_reason_ = reason; |
| 325 | return false; |
| 326 | } |
| 327 | |
| 328 | //////////////////////////////////////////////////////////////////////////////// |
| 329 | |
| 330 | bool PEInfo::ParseRelocs(std::vector<RVA> *relocs) { |
| 331 | relocs->clear(); |
| 332 | |
| 333 | size_t relocs_size = base_relocation_table_.size_; |
| 334 | if (relocs_size == 0) |
| 335 | return true; |
| 336 | |
| 337 | // The format of the base relocation table is a sequence of variable sized |
| 338 | // IMAGE_BASE_RELOCATION blocks. Search for |
| 339 | // "The format of the base relocation data is somewhat quirky" |
| 340 | // at http://msdn.microsoft.com/en-us/library/ms809762.aspx |
| 341 | |
| 342 | const uint8* start = RVAToPointer(base_relocation_table_.address_); |
| 343 | const uint8* end = start + relocs_size; |
| 344 | |
| 345 | // Make sure entire base relocation table is within the buffer. |
| 346 | if (start < start_ || |
| 347 | start >= end_ || |
| 348 | end <= start_ || |
| 349 | end > end_) { |
| 350 | return Bad(".relocs outside image"); |
| 351 | } |
| 352 | |
| 353 | const uint8* block = start; |
| 354 | |
| 355 | // Walk the variable sized blocks. |
| 356 | while (block + 8 < end) { |
| 357 | RVA page_rva = ReadU32(block, 0); |
| 358 | uint32 size = ReadU32(block, 4); |
| 359 | if (size < 8 || // Size includes header ... |
| 360 | size % 4 != 0) // ... and is word aligned. |
| 361 | return Bad("unreasonable relocs block"); |
| 362 | |
| 363 | const uint8* end_entries = block + size; |
| 364 | |
| 365 | if (end_entries <= block || end_entries <= start_ || end_entries > end_) |
| 366 | return Bad(".relocs block outside image"); |
| 367 | |
| 368 | // Walk through the two-byte entries. |
| 369 | for (const uint8* p = block + 8; p < end_entries; p += 2) { |
| 370 | uint16 entry = ReadU16(p, 0); |
| 371 | int type = entry >> 12; |
| 372 | int offset = entry & 0xFFF; |
| 373 | |
| 374 | RVA rva = page_rva + offset; |
| 375 | if (type == 3) { // IMAGE_REL_BASED_HIGHLOW |
| 376 | relocs->push_back(rva); |
| 377 | } else if (type == 0) { // IMAGE_REL_BASED_ABSOLUTE |
| 378 | // Ignore, used as padding. |
| 379 | } else { |
| 380 | // Does not occur in Windows x86 executables. |
| 381 | return Bad("unknown type of reloc"); |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | block += size; |
| 386 | } |
| 387 | |
| 388 | std::sort(relocs->begin(), relocs->end()); |
| 389 | |
| 390 | return true; |
| 391 | } |
| 392 | |
| 393 | } // namespace courgette |