Apply the relocation information to the image using the provided image base. This method will apply the relocation information to the image. Given the new base, all the relocations will be processed and both the raw data and the section's data will be fixed accordingly.
(self, new_ImageBase)
| 6990 | self.set_data_bytes(section_data_start, section.get_data()) |
| 6991 | |
| 6992 | def relocate_image(self, new_ImageBase): |
| 6993 | """Apply the relocation information to the image using the provided image base. |
| 6994 | |
| 6995 | This method will apply the relocation information to the image. Given the new |
| 6996 | base, all the relocations will be processed and both the raw data and the |
| 6997 | section's data will be fixed accordingly. |
| 6998 | The resulting image can be retrieved as well through the method: |
| 6999 | |
| 7000 | get_memory_mapped_image() |
| 7001 | |
| 7002 | In order to get something that would more closely match what could be found in |
| 7003 | memory once the Windows loader finished its work. |
| 7004 | """ |
| 7005 | |
| 7006 | relocation_difference = new_ImageBase - self.OPTIONAL_HEADER.ImageBase |
| 7007 | |
| 7008 | if ( |
| 7009 | len(self.OPTIONAL_HEADER.DATA_DIRECTORY) >= 6 |
| 7010 | and self.OPTIONAL_HEADER.DATA_DIRECTORY[5].Size |
| 7011 | ): |
| 7012 | if not hasattr(self, "DIRECTORY_ENTRY_BASERELOC"): |
| 7013 | self.parse_data_directories( |
| 7014 | directories=[DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_BASERELOC"]] |
| 7015 | ) |
| 7016 | if not hasattr(self, "DIRECTORY_ENTRY_BASERELOC"): |
| 7017 | self.__warnings.append( |
| 7018 | "Relocating image but PE does not have (or pefile cannot " |
| 7019 | "parse) a DIRECTORY_ENTRY_BASERELOC" |
| 7020 | ) |
| 7021 | else: |
| 7022 | for reloc in self.DIRECTORY_ENTRY_BASERELOC: |
| 7023 | |
| 7024 | # We iterate with an index because if the relocation is of type |
| 7025 | # IMAGE_REL_BASED_HIGHADJ we need to also process the next entry |
| 7026 | # at once and skip it for the next iteration |
| 7027 | # |
| 7028 | entry_idx = 0 |
| 7029 | while entry_idx < len(reloc.entries): |
| 7030 | |
| 7031 | entry = reloc.entries[entry_idx] |
| 7032 | entry_idx += 1 |
| 7033 | |
| 7034 | if entry.type == RELOCATION_TYPE["IMAGE_REL_BASED_ABSOLUTE"]: |
| 7035 | # Nothing to do for this type of relocation |
| 7036 | pass |
| 7037 | |
| 7038 | elif entry.type == RELOCATION_TYPE["IMAGE_REL_BASED_HIGH"]: |
| 7039 | # Fix the high 16-bits of a relocation |
| 7040 | # |
| 7041 | # Add high 16-bits of relocation_difference to the |
| 7042 | # 16-bit value at RVA=entry.rva |
| 7043 | |
| 7044 | self.set_word_at_rva( |
| 7045 | entry.rva, |
| 7046 | ( |
| 7047 | self.get_word_at_rva(entry.rva) |
| 7048 | + relocation_difference |
| 7049 | >> 16 |
no test coverage detected