Ghidra is a software reverse engineering (SRE) framework
GP-7076: PeLoader improvements
Ryan Kurtzf21a2f5755bd
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/PortableExecutableBinaryAnalysisCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/PortableExecutableBinaryAnalysisCommand.javaindex 4984c2fb0d..298ddb993b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/PortableExecutableBinaryAnalysisCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/PortableExecutableBinaryAnalysisCommand.java@@ -221,9 +221,8 @@ public class PortableExecutableBinaryAnalysisCommand extends FlatProgramAPIprivate void processSections(NTHeader nt)throws Exception, DuplicateNameException, InvalidInputException {FileHeader fh = nt.getFileHeader();- SectionHeader[] sections = fh.getSectionHeaders();int index = fh.getPointerToSections();- for (SectionHeader section : sections) {+ for (SectionHeader section : fh.getSectionHeaders()) {DataType sectionDT = section.toDataType();Address sectionStartAddr = toAddr(index);createData(sectionStartAddr, sectionDT);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/Writeable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/Writeable.javadeleted file mode 100644index ec2365e41c..0000000000--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/Writeable.java+++ /dev/null@@ -1,36 +0,0 @@-/* ###- * IP: GHIDRA- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package ghidra.app.util.bin.format;--import java.io.IOException;-import java.io.RandomAccessFile;--import ghidra.util.DataConverter;--/**- * An interface for writing out class state information- */-public interface Writeable {- /**- * Writes this object to the specified random access file using the data converter to handle- * endianness- *- * @param raf the random access file- * @param dc the data converter- * @throws IOException if an I/O error occurs- */- public void write(RandomAccessFile raf, DataConverter dc) throws IOException;-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/DOSHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/DOSHeader.javaindex 1292f6a306..b3c99d1a57 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/DOSHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/DOSHeader.java@@ -16,11 +16,9 @@package ghidra.app.util.bin.format.mz;import java.io.IOException;-import java.io.RandomAccessFile;import ghidra.app.util.bin.BinaryReader;import ghidra.program.model.data.*;-import ghidra.util.DataConverter;import ghidra.util.exception.DuplicateNameException;@@ -202,19 +200,4 @@ public class DOSHeader extends OldDOSHeader {}}}-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {- super.write(raf, dc);- for (short e_re : e_res) {- raf.write(dc.getBytes(e_re));- }- raf.write(dc.getBytes(e_oemid));- raf.write(dc.getBytes(e_oeminfo));- for (short element : e_res2) {- raf.write(dc.getBytes(element));- }- raf.write(dc.getBytes(e_lfanew));- raf.write(stubBytes);- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/OldDOSHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/OldDOSHeader.javaindex d92ab3262e..72a21b2737 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/OldDOSHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/mz/OldDOSHeader.java@@ -16,13 +16,10 @@package ghidra.app.util.bin.format.mz;import java.io.IOException;-import java.io.RandomAccessFile;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.Writeable;import ghidra.program.model.data.*;-import ghidra.util.DataConverter;import ghidra.util.exception.DuplicateNameException;/**@@ -47,7 +44,7 @@ import ghidra.util.exception.DuplicateNameException;* </pre>*/-public class OldDOSHeader implements StructConverter, Writeable {+public class OldDOSHeader implements StructConverter {/** The name to use when converting into a structure data type. */public static final String NAME = "OLD_IMAGE_DOS_HEADER";@@ -265,22 +262,4 @@ public class OldDOSHeader implements StructConverter, Writeable {e_lfarlc = reader.readNextShort();e_ovno = reader.readNextShort();}-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {- raf.write(dc.getBytes(e_magic));- raf.write(dc.getBytes(e_cblp));- raf.write(dc.getBytes(e_cp));- raf.write(dc.getBytes(e_crlc));- raf.write(dc.getBytes(e_cparhdr));- raf.write(dc.getBytes(e_minalloc));- raf.write(dc.getBytes(e_maxalloc));- raf.write(dc.getBytes(e_ss));- raf.write(dc.getBytes(e_sp));- raf.write(dc.getBytes(e_csum));- raf.write(dc.getBytes(e_ip));- raf.write(dc.getBytes(e_cs));- raf.write(dc.getBytes(e_lfarlc));- raf.write(dc.getBytes(e_ovno));- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DebugDataDirectory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DebugDataDirectory.javaindex d62001940c..3912aadd31 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DebugDataDirectory.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DebugDataDirectory.java@@ -56,8 +56,9 @@ public class DebugDataDirectory extends DataDirectory {return false;}- parser = new DebugDirectoryParser(reader, ptr, size,- ntHeader.getOptionalHeader().getSizeOfImage());+ OptionalHeader optHdr = ntHeader.getOptionalHeader();+ parser = new DebugDirectoryParser(reader, ptr, size, optHdr.getSizeOfImage(),+ optHdr.getSectionAlignment(), optHdr.getFileAlignment());return true;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/FileHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/FileHeader.javaindex a3410a5a6e..04d0dcfd6c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/FileHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/FileHeader.java@@ -16,17 +16,14 @@package ghidra.app.util.bin.format.pe;import java.io.IOException;-import java.io.RandomAccessFile;-import java.util.*;+import java.util.ArrayList;+import java.util.List;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.Writeable;import ghidra.app.util.bin.format.pe.debug.DebugCOFFSymbol;import ghidra.app.util.bin.format.pe.debug.DebugCOFFSymbolAux;import ghidra.program.model.data.*;-import ghidra.program.model.mem.MemoryBlock;-import ghidra.util.DataConverter;import ghidra.util.Msg;import ghidra.util.exception.DuplicateNameException;@@ -43,7 +40,7 @@ import ghidra.util.exception.DuplicateNameException;/// WORD Characteristics; // MANDATORY/// } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;/// ```-public class FileHeader implements StructConverter, Writeable {+public class FileHeader implements StructConverter {/// The name to use when converting into a structure data typepublic final static String NAME = "IMAGE_FILE_HEADER";@@ -147,7 +144,7 @@ public class FileHeader implements StructConverter, Writeable {private short sizeOfOptionalHeader; // delta between start of OptionalHeader and start of section tableprivate short characteristics;- private SectionHeader[] sectionHeaders;+ private List<SectionHeader> sectionHeaders = new ArrayList<>();private List<DebugCOFFSymbol> symbols = new ArrayList<>();private BinaryReader reader;@@ -227,27 +224,30 @@ public class FileHeader implements StructConverter, Writeable {}/**- * {@return the array of section headers}+ * {@return the list of section headers}*/- public SectionHeader[] getSectionHeaders() {- return sectionHeaders != null ? sectionHeaders : new SectionHeader[0];+ public List<SectionHeader> getSectionHeaders() {+ return sectionHeaders;}/**- * {@return the array of symbols}+ * {@return the list of symbols}*/public List<DebugCOFFSymbol> getSymbols() {return symbols;}/**- * {@return the section header that contains the specified virtual address}+ * {@return the section header that contains the specified virtual address, or {@code null} if+ * it does not exist in any section}** @param virtualAddr the virtual address+ * @param optionalHeader The {@link OptionalHeader}*/- public SectionHeader getSectionHeaderContaining(int virtualAddr) {- return Arrays.stream(sectionHeaders)- .filter(e -> virtualAddr >= e.getVirtualAddress() &&+ public SectionHeader getSectionHeaderContaining(int virtualAddr,+ OptionalHeader optionalHeader) {+ return sectionHeaders.stream()+ .filter(e -> virtualAddr >= e.getAlignedVirtualAddress(optionalHeader) &&virtualAddr < e.getVirtualAddress() + e.getVirtualSize()).findFirst().orElse(null);@@ -259,7 +259,7 @@ public class FileHeader implements StructConverter, Writeable {* @param index index of section header to return*/public SectionHeader getSectionHeader(int index) {- return index >= 0 && index < sectionHeaders.length ? sectionHeaders[index] : null;+ return index >= 0 && index < sectionHeaders.size() ? sectionHeaders.get(index) : null;}/**@@ -268,7 +268,7 @@ public class FileHeader implements StructConverter, Writeable {* @param name section name*/public SectionHeader getSectionHeader(String name) {- return Arrays.stream(sectionHeaders)+ return sectionHeaders.stream().filter(e -> e.getName().equals(name)).findFirst().orElse(null);@@ -289,7 +289,7 @@ public class FileHeader implements StructConverter, Writeable {}/**- * {@return the number of symbols in the COFF symbol table}+ * {@return the number of symbols in the COFF symbol table}*/public int getNumberOfSymbols() {return numberOfSymbols;@@ -327,51 +327,14 @@ public class FileHeader implements StructConverter, Writeable {void processSections(OptionalHeader optHeader, boolean symbolsProcessed) throws IOException {long oldIndex = reader.getPointerIndex();- int tmpIndex = getPointerToSections();if (optHeader.getFileAlignment() == 0) {Msg.error(this, "File alignment == 0: section processing skipped");}else {long stringTableOffset = symbolsProcessed ? getStringTableOffset() : -1;- sectionHeaders = new SectionHeader[numberOfSections];+ int tmpIndex = getPointerToSections();for (int i = 0; i < numberOfSections; ++i) {- SectionHeader section = new SectionHeader(reader, tmpIndex, stringTableOffset);- sectionHeaders[i] = section;-- int pointerToRawData = section.getPointerToRawData();- int sizeOfRawData = section.getSizeOfRawData();-- // Ensure PointerToRawData + SizeOfRawData doesn't exceed the length of the file- if (pointerToRawData >= reader.length()) {- sizeOfRawData = 0;- Msg.warn(this, "Section " + section.getName() + " begins after end of file!");- }- else if (pointerToRawData + sizeOfRawData > reader.length()) {- sizeOfRawData = (int) (reader.length() - pointerToRawData);- Msg.warn(this,- String.format("Section %s exceeds file length...truncating from %d to %d",- section.getName(), section.getSizeOfRawData(), sizeOfRawData));- }- section.setSizeOfRawData(sizeOfRawData);-- // Ensure VirtualSize is large enough to accommodate SizeOfRawData, but do not- // exceed the next alignment boundary. We can only do this if the VirtualAddress is- // already properly aligned, since we currently don't support moving sections to- // different addresses to enforce alignment.- int virtualAddress = section.getVirtualAddress();- int virtualSize = section.getVirtualSize();- int alignedVirtualAddress =- PeUtils.align(virtualAddress, optHeader.getSectionAlignment());- int alignedVirtualSize =- PeUtils.align(virtualSize, optHeader.getSectionAlignment());- if (virtualAddress == alignedVirtualAddress) {- if (sizeOfRawData > virtualSize) {- section.setVirtualSize(Math.min(sizeOfRawData, alignedVirtualSize));- }- }- else {- Msg.warn(this, "Section " + section.getName() + " is not aligned!");- }+ sectionHeaders.add(new SectionHeader(reader, tmpIndex, stringTableOffset, i));tmpIndex += SectionHeader.IMAGE_SIZEOF_SECTION_HEADER;}}@@ -454,6 +417,18 @@ public class FileHeader implements StructConverter, Writeable {return false;}+ /**+ * {@return the default page size for the architecture}+ * <p>+ * This is relevant for the {@link OptionalHeader#getSectionAlignment() section alignment}.+ */+ public int getDefaultPageSize() {+ // Seems that the only architectures that don't use 0x1000 are, Alpha AXP, Alpha AXP 64,+ // and Itanium, which all use 0x2000. But we don't support those yet.++ return 0x1000;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException {StructureDataType struct = new StructureDataType(NAME, 0);@@ -467,143 +442,4 @@ public class FileHeader implements StructConverter, Writeable {struct.setCategoryPath(new CategoryPath("/PE"));return struct;}-- private void setSectionHeaders(SectionHeader[] sectionHeaders) {- this.sectionHeaders = sectionHeaders;- numberOfSections = sectionHeaders.length;- }-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {- raf.write(dc.getBytes(machine));- raf.write(dc.getBytes(numberOfSections));- raf.write(dc.getBytes(timeDateStamp));- raf.write(dc.getBytes(pointerToSymbolTable));- raf.write(dc.getBytes(numberOfSymbols));- raf.write(dc.getBytes(sizeOfOptionalHeader));- raf.write(dc.getBytes(characteristics));- }-- /**- * Adds a new section to this file header. Uses the given memory block- * as the section template. The section will have the memory block's name, start address,- * size, etc. The optional header is needed to determine the free byte position in the- * file.- * @param block the memory block template- * @param optionalHeader the related optional header- * @throws RuntimeException if the memory block is uninitialized- */- public void addSection(MemoryBlock block, OptionalHeader optionalHeader) {- DataDirectory[] directories = optionalHeader.getDataDirectories();-- DataDirectory[] dataDirectories = optionalHeader.getDataDirectories();-- SecurityDataDirectory sdd = null;- if (dataDirectories.length > OptionalHeader.IMAGE_DIRECTORY_ENTRY_SECURITY) {- sdd =- (SecurityDataDirectory) dataDirectories[OptionalHeader.IMAGE_DIRECTORY_ENTRY_SECURITY];- if (sdd != null && sdd.getSize() > 0) {- sdd.updatePointers(PeUtils.align((int) block.getSize(),- optionalHeader.getFileAlignment()));- }- }-- int lastPos = computeAlignedNewPosition(optionalHeader, directories);-- SectionHeader newSection = new SectionHeader(block, optionalHeader, lastPos);-- SectionHeader[] newSectionHeaders = new SectionHeader[sectionHeaders.length + 1];- System.arraycopy(sectionHeaders, 0, newSectionHeaders, 0, sectionHeaders.length);- newSectionHeaders[sectionHeaders.length] = newSection;- setSectionHeaders(newSectionHeaders);-- int firstSectionStart = sectionHeaders[0].getPointerToRawData();- int lastSectionEnd = sectionHeaders[sectionHeaders.length - 1].getPointerToRawData() +- sectionHeaders[sectionHeaders.length - 1].getSizeOfRawData();-- for (int i = 0; i < directories.length; i++) {- if (directories[i] == null || directories[i].getSize() == 0 ||- directories[i].isContainedInSection()) {- continue;- }- if (directories[i].getVirtualAddress() < firstSectionStart) {- if (i != OptionalHeader.IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT) {- throw new RuntimeException("PE - Unexpected directory before sections: " + i);- }- }- if (directories[i].getVirtualAddress() > lastSectionEnd) {- if (i != OptionalHeader.IMAGE_DIRECTORY_ENTRY_SECURITY) {- throw new RuntimeException("PE - Unexpected directory after sections: " + i);- }- }- }-- int offset = 0;-- if (dataDirectories.length > OptionalHeader.IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT) {- BoundImportDataDirectory bidd =- (BoundImportDataDirectory) dataDirectories[OptionalHeader.IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT];- if (bidd != null && bidd.getSize() > 0) {- bidd.updatePointers(SectionHeader.IMAGE_SIZEOF_SECTION_HEADER);- int endptr = bidd.getVirtualAddress() + bidd.getSize() - 1;- if (endptr >= sectionHeaders[0].getPointerToRawData()) {- int alignedPtr =- PeUtils.align(endptr, optionalHeader.getFileAlignment());- offset = alignedPtr - sectionHeaders[0].getPointerToRawData();- for (SectionHeader sectionHeader : sectionHeaders) {- sectionHeader.updatePointers(offset);- }- //reset the sizeOfHeaders...- optionalHeader.setSizeOfHeaders(sectionHeaders[0].getPointerToRawData());- }- }- }-- if (dataDirectories.length > OptionalHeader.IMAGE_DIRECTORY_ENTRY_DEBUG) {- DebugDataDirectory ddd =- (DebugDataDirectory) dataDirectories[OptionalHeader.IMAGE_DIRECTORY_ENTRY_DEBUG];- if (ddd != null && ddd.getSize() > 0) {- if (ddd.getVirtualAddress() > newSection.getVirtualAddress()) {- if (sdd != null && sdd.getSize() > 0) {- ddd.updatePointers(offset, sdd.getVirtualAddress() + sdd.getSize());- }- else {- ddd.updatePointers(offset, newSection.getSizeOfRawData());- }- }- }- }-- if (block.isExecute()) {- optionalHeader- .setSizeOfCode(optionalHeader.getSizeOfCode() + newSection.getSizeOfRawData());- }- else {- optionalHeader.setSizeOfInitializedData(- optionalHeader.getSizeOfInitializedData() + newSection.getSizeOfRawData());- }-- int soi = newSection.getVirtualAddress() + newSection.getSizeOfRawData();- soi = PeUtils.align(soi, optionalHeader.getSectionAlignment());- optionalHeader.setSizeOfImage(soi);- }-- private int computeAlignedNewPosition(OptionalHeader optionalHeader,- DataDirectory[] directories) {- int lastPos = 0;- for (SectionHeader sectionHeader : sectionHeaders) {- if (sectionHeader.getPointerToRawData() + sectionHeader.getSizeOfRawData() > lastPos) {- lastPos = sectionHeader.getPointerToRawData() + sectionHeader.getSizeOfRawData();- }- }- for (DataDirectory directorie : directories) {- if (directorie == null || directorie.getSize() == 0) {- continue;- }- if (directorie.rvaToPointer() + directorie.getSize() > lastPos) {- lastPos = directorie.rvaToPointer() + directorie.getSize();- }- }- return PeUtils.align(lastPos, optionalHeader.getFileAlignment());- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/LoadConfigDirectory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/LoadConfigDirectory.javaindex 3e62830151..1327359c89 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/LoadConfigDirectory.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/LoadConfigDirectory.java@@ -214,7 +214,8 @@ public class LoadConfigDirectory implements StructConverter {SectionHeader section = fh.getSectionHeader(dynamicValueRelocTableSection - 1);if (section != null) {long fileOffset = section.getPointerToRawData() + dynamicValueRelocTableOffset;- long rva = section.getVirtualAddress() + dynamicValueRelocTableOffset;+ long rva = section.getAlignedVirtualAddress(nt.getOptionalHeader()) ++ dynamicValueRelocTableOffset;dvrt = new ImageDynamicRelocationTable(reader.clone(fileOffset), rva, is64bit);}else {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/NTHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/NTHeader.javaindex 20a3c7098d..e2935c5de7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/NTHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/NTHeader.java@@ -16,14 +16,11 @@package ghidra.app.util.bin.format.pe;import java.io.IOException;-import java.io.RandomAccessFile;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.Writeable;import ghidra.app.util.bin.format.pe.PortableExecutable.SectionLayout;import ghidra.program.model.data.*;-import ghidra.util.DataConverter;import ghidra.util.Msg;import ghidra.util.exception.DuplicateNameException;@@ -36,7 +33,7 @@ import ghidra.util.exception.DuplicateNameException;/// IMAGE_OPTIONAL_HEADER32 OptionalHeader;/// };/// ```-public class NTHeader implements StructConverter, OffsetValidator, Writeable {+public class NTHeader implements StructConverter, OffsetValidator {/// The size of the NT header signature.public final static int SIZEOF_SIGNATURE = BinaryReader.SIZEOF_INT;@@ -46,7 +43,6 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {private int signature;private FileHeader fileHeader;private OptionalHeader optionalHeader;- private int index;private boolean parseCliHeaders = false;private SectionLayout layout = SectionLayout.FILE;@@ -63,14 +59,11 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {*/public NTHeader(BinaryReader reader, int index, SectionLayout layout, boolean parseCliHeaders)throws InvalidNTHeaderException, IOException {- this.index = index;this.layout = layout;this.parseCliHeaders = parseCliHeaders;- int tmpIndex = index;-try {- signature = reader.readInt(tmpIndex);+ signature = reader.readInt(index);}catch (IndexOutOfBoundsException ioobe) {// Handled below@@ -81,15 +74,15 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {throw new InvalidNTHeaderException();}- tmpIndex += 4;+ index += 4;- fileHeader = new FileHeader(reader, tmpIndex, this);+ fileHeader = new FileHeader(reader, index, this);if (fileHeader.getSizeOfOptionalHeader() == 0) {Msg.warn(this, "Section headers overlap optional header");}- tmpIndex += FileHeader.IMAGE_SIZEOF_FILE_HEADER;+ index += FileHeader.IMAGE_SIZEOF_FILE_HEADER;- optionalHeader = new OptionalHeader(this, reader, tmpIndex);+ optionalHeader = new OptionalHeader(this, reader, index);// Process symbols. Allow parsing to continue on failure.boolean symbolsProcessed = false;@@ -98,6 +91,7 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {symbolsProcessed = true;}catch (Exception e) {+ e.printStackTrace();Msg.error(this, "Failed to process symbols: " + e.getMessage());}@@ -161,8 +155,7 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {* @param rva the relative virtual address*/public long rvaToPointer(long rva) {- SectionHeader[] sections = fileHeader.getSectionHeaders();- for (SectionHeader section : sections) {+ for (SectionHeader section : fileHeader.getSectionHeaders()) {long sectionVA = Integer.toUnsignedLong(section.getVirtualAddress());long vSize = Integer.toUnsignedLong(section.getVirtualSize());long rawPtr = Integer.toUnsignedLong(section.getPointerToRawData());@@ -205,8 +198,7 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {@Overridepublic boolean checkPointer(long ptr) {- SectionHeader[] sections = fileHeader.getSectionHeaders();- for (SectionHeader section : sections) {+ for (SectionHeader section : fileHeader.getSectionHeaders()) {long virtPtr = Integer.toUnsignedLong(section.getVirtualAddress());long virtSize = Integer.toUnsignedLong(section.getVirtualSize());long rawSize = Integer.toUnsignedLong(section.getSizeOfRawData());@@ -220,7 +212,7 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {}}if (optionalHeader != null) {- if (optionalHeader.getFileAlignment() == optionalHeader.getSectionAlignment()) {+ if (getFileAlignment() == getSectionAlignment()) {return checkRVA(ptr);}}@@ -229,10 +221,17 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {@Overridepublic boolean checkRVA(long rva) {- if (optionalHeader != null) {- return (0 <= rva) && (rva <= optionalHeader.getSizeOfImage());- }- return true;+ return optionalHeader == null || (0 <= rva && rva < optionalHeader.getSizeOfImage());+ }++ @Override+ public int getSectionAlignment() {+ return optionalHeader != null ? optionalHeader.getSectionAlignment() : 0;+ }++ @Override+ public int getFileAlignment() {+ return optionalHeader != null ? optionalHeader.getFileAlignment() : 0;}/**@@ -255,23 +254,6 @@ public class NTHeader implements StructConverter, OffsetValidator, Writeable {return rvaToPointer(va - getOptionalHeader().getImageBase());}- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {-- raf.seek(index);-- raf.write(dc.getBytes(signature));-- fileHeader.write(raf, dc);-- optionalHeader.writeHeader(raf, dc);-- SectionHeader[] sections = fileHeader.getSectionHeaders();- for (SectionHeader section : sections) {- section.write(raf, dc);- }- }-/*** {@return whether or not CLI headers should be parsed}*/diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OffsetValidator.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OffsetValidator.javaindex dd18ced98b..3fcda959c4 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OffsetValidator.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OffsetValidator.java@@ -1,13 +1,12 @@/* ###* IP: GHIDRA- * REVIEWED: YES** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -16,10 +15,32 @@*/package ghidra.app.util.bin.format.pe;+/**+ * Provides methods for validating pointers and relative virtual addresses (RVA) in a PE file+ */public interface OffsetValidator {+ /**+ * {@return whether or not the specified pointer is contained within the PE file}+ *+ * @param ptr the pointer value to check+ */public boolean checkPointer(long ptr);+ /**+ * {@return whether or not the specified RVA value is contained within the PE image}+ *+ * @param rva the RVA to check+ */public boolean checkRVA(long rva);+ /**+ * {@return the PE's file alignment, or 0 if unknown/unused}+ */+ public int getFileAlignment();++ /**+ * {@return the PE's sectionAlignment, or 0 if unknown/unused}+ */+ public int getSectionAlignment();}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OptionalHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OptionalHeader.javaindex 5f3aaf3207..38999ef4c0 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OptionalHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/OptionalHeader.java@@ -753,8 +753,8 @@ public class OptionalHeader implements StructConverter {/*** {@return the combined size of all headers}*/- public long getSizeOfHeaders() {- return Integer.toUnsignedLong(sizeOfHeaders);+ public int getSizeOfHeaders() {+ return sizeOfHeaders;}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PeUtils.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PeUtils.javaindex 18a1ed0f5a..aefa33ffa6 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PeUtils.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PeUtils.java@@ -84,11 +84,24 @@ public class PeUtils {* @param value the value to align* @param alignment the alignment value*/- public static int align(int value, int alignment) {+ public static int alignUp(int value, int alignment) {if (alignment == 0) {return value;}return Math.ceilDiv(value, alignment) * alignment;}+ /**+ * {@return the given value rounded down to the nearest given alignment}+ *+ * @param value the value to align+ * @param alignment the alignment value+ */+ public static int alignDown(int value, int alignment) {+ if (alignment == 0) {+ return value;+ }+ return Math.floorDiv(value, alignment) * alignment;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PortableExecutable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PortableExecutable.javaindex 0e8ac2f166..f2e5fb7f04 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PortableExecutable.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/PortableExecutable.java@@ -16,21 +16,18 @@package ghidra.app.util.bin.format.pe;import java.io.IOException;-import java.io.RandomAccessFile;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.ByteProvider;-import ghidra.app.util.bin.format.Writeable;import ghidra.app.util.bin.format.mz.DOSHeader;import ghidra.app.util.importer.MessageLog;-import ghidra.util.DataConverter;import ghidra.util.Msg;import ghidra.util.task.TaskMonitor;/*** A class to manage loading Portable Executables (PE).*/-public class PortableExecutable implements Writeable {+public class PortableExecutable {public static final String NAME = "PORTABLE_EXECUTABLE";public static boolean DEBUG = false;@@ -123,18 +120,4 @@ public class PortableExecutable implements Writeable {public long getFileLength() {return reader != null ? reader.length() : 0;}-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {- raf.seek(0);- if (dosHeader != null) {- dosHeader.write(raf, dc);- }- if (richHeader != null) {- richHeader.write(raf, dc);- }- if (ntHeader != null) {- ntHeader.write(raf, dc);- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/RichHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/RichHeader.javaindex f56155cd4d..c71212b9b1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/RichHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/RichHeader.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -15,21 +15,16 @@*/package ghidra.app.util.bin.format.pe;-import java.io.IOException;-import java.io.RandomAccessFile;-import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.Writeable;import ghidra.app.util.bin.format.pe.rich.RichHeaderRecord;import ghidra.program.model.data.DataType;-import ghidra.util.DataConverter;/*** The "Rich" header contains encoded metadata about the tool chain used to generate the binary.* This class decodes and writes the Rich header (if it exists).*/-public class RichHeader implements StructConverter, Writeable {+public class RichHeader implements StructConverter {public final static int IMAGE_RICH_SIGNATURE = 0x68636952; // Richpublic final static int IMAGE_DANS_SIGNATURE = 0x536E6144; // DanS@@ -106,24 +101,4 @@ public class RichHeader implements StructConverter, Writeable {}return table.toDataType();}-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {-- if (table != null) {- raf.write(dc.getBytes(IMAGE_DANS_SIGNATURE ^ table.getMask()));-- raf.write(dc.getBytes(table.getMask())); // 0 ^ mask- raf.write(dc.getBytes(table.getMask())); // 0 ^ mask- raf.write(dc.getBytes(table.getMask())); // 0 ^ mask-- for (RichHeaderRecord rec : table.getRecords()) {- raf.write(dc.getBytes(rec.getCompId().getValue() ^ table.getMask()));- raf.write(dc.getBytes(rec.getObjectCount() ^ table.getMask()));- }-- raf.write(dc.getBytes(IMAGE_RICH_SIGNATURE));- raf.write(dc.getBytes(table.getMask()));- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SectionHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SectionHeader.javaindex f80a7b701e..cc7bf2d66f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SectionHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SectionHeader.java@@ -15,12 +15,12 @@*/package ghidra.app.util.bin.format.pe;-import java.io.*;+import java.io.IOException;+import java.io.InputStream;import ghidra.app.util.bin.*;-import ghidra.app.util.bin.format.Writeable;+import ghidra.app.util.importer.MessageLog;import ghidra.program.model.data.*;-import ghidra.program.model.mem.*;import ghidra.util.DataConverter;import ghidra.util.exception.DuplicateNameException;@@ -45,7 +45,7 @@ import ghidra.util.exception.DuplicateNameException;////// #define IMAGE_SIZEOF_SECTION_HEADER 40/// ```-public class SectionHeader implements StructConverter, ByteArrayConverter, Writeable {+public class SectionHeader implements StructConverter, ByteArrayConverter {/// The name to use when converting into a structure data typepublic final static String NAME = "IMAGE_SECTION_HEADER";@@ -204,7 +204,13 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Writeprivate short numberOfLinenumbers;private int characteristics;+ private Integer alignedVirtualSize;+ private Integer alignedVirtualAddress;+ private Integer alignedSizeOfRawData;+ private Integer alignedPointerToRawData;+private BinaryReader reader;+ private int sectionNumber;/*** Creates a new {@link SectionHeader} from the specified stream starting at {@code index}@@ -212,11 +218,13 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Write* @param reader {@link BinaryReader} to read from* @param index long offset in the reader where the section header starts* @param stringTableOffset offset of the string table, or -1 if not available+ * @param sectionNumber The section number (0-based)* @throws IOException if error reading data*/- public SectionHeader(BinaryReader reader, long index, long stringTableOffset)+ public SectionHeader(BinaryReader reader, long index, long stringTableOffset, int sectionNumber)throws IOException {this.reader = reader;+ this.sectionNumber = sectionNumber;name = reader.readAsciiString(index, IMAGE_SIZEOF_SHORT_NAME).trim();if (name.startsWith("/") && stringTableOffset != -1) {@@ -244,47 +252,6 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Writecharacteristics = reader.readNextInt();}- /**- * Creates a new {@link SectionHeader} from the given {@link MemoryBlock}- *- * @param block The {@link MemoryBlock}- * @param optHeader The {@link OptionalHeader}- * @param ptr The pointer to raw data- */- SectionHeader(MemoryBlock block, OptionalHeader optHeader, int ptr) {- name = block.getName();- physicalAddress = virtualSize = (int) block.getSize();- virtualAddress = (int) block.getStart().getOffset() - (int) optHeader.getImageBase();- sizeOfRawData = PeUtils.align(virtualSize, optHeader.getFileAlignment());- pointerToRawData = ptr;- pointerToLinenumbers = 0;- pointerToRelocations = 0;- numberOfLinenumbers = 0;- numberOfRelocations = 0;- characteristics = 0;- if (block.isRead()) {- characteristics |= SectionFlags.IMAGE_SCN_MEM_READ.getMask();- }- if (block.isWrite()) {- characteristics |= SectionFlags.IMAGE_SCN_MEM_WRITE.getMask();- }- if (block.isExecute()) {- characteristics |= SectionFlags.IMAGE_SCN_MEM_EXECUTE.getMask() |- SectionFlags.IMAGE_SCN_CNT_CODE.getMask();- }- if (block.isExecute()) {- characteristics |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;- }- else if (block.getType() == MemoryBlockType.DEFAULT) {//not executable, then must be data...- if (block.isInitialized()) {- characteristics |= SectionFlags.IMAGE_SCN_CNT_INITIALIZED_DATA.getMask();- }- else {- characteristics |= SectionFlags.IMAGE_SCN_CNT_UNINITIALIZED_DATA.getMask();- }- }- }-/*** {@return the ASCII name of the section}* <p>@@ -306,6 +273,10 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Write* underscores}*/public String getReadableName() {+ if (name.isBlank()) {+ return "SECTION." + sectionNumber;+ }+StringBuilder sb = new StringBuilder();for (int i = 0; i < name.length(); ++i) {char ch = name.charAt(i);@@ -320,62 +291,158 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Write}/**- * {@return the physical (file) address of this section}+ * {@return the original, unaligned physical address of this section}*/public int getPhysicalAddress() {return physicalAddress;}/**- * {@return the RVA where the section begins in memory}+ * {@return the original, unaligned RVA where the section begins in memory}*/public int getVirtualAddress() {return virtualAddress;}/**- * {@return the actual, used size of the section}- * <p>- * This field may be larger or smaller than the SizeOfRawData field. If the VirtualSize is- * larger, the SizeOfRawData field is the size of the initialized data from the executable, and- * the remaining bytes up to the VirtualSize should be zero-padded. This field is set to 0 in- * OBJ files.+ * {@return the aligned RVA where the section begins in memory}+ *+ * @param optionalHeader The {@link OptionalHeader}, or {@code null} if not available+ */+ public int getAlignedVirtualAddress(OptionalHeader optionalHeader) {+ if (alignedVirtualAddress != null) {+ return alignedVirtualAddress;+ }++ alignedVirtualAddress = optionalHeader != null+ ? PeUtils.alignUp(virtualAddress, optionalHeader.getSectionAlignment())+ : virtualAddress;++ return alignedVirtualAddress;+ }++ /**+ * {@return the original, unaligned size of the section in memory}*/public int getVirtualSize() {- return virtualSize != 0 ? virtualSize : sizeOfRawData;+ return virtualSize;}/**- * {@return the size (in bytes) of data stored for the section}+ * {@return the actual, used size of the section}+ *+ * @param optionalHeader The {@link OptionalHeader}, or {@code null} if not available+ * @param log A log to report errors to*/- public int getSizeOfRawData() {- return sizeOfRawData;+ public int getAlignedVirtualSize(OptionalHeader optionalHeader, MessageLog log) {+ if (alignedVirtualSize != null) {+ return alignedVirtualSize;+ }++ if (virtualSize != 0 && optionalHeader != null) {+ alignedVirtualSize = PeUtils.alignUp(virtualSize, optionalHeader.getSectionAlignment());+ }+ else if (virtualSize != 0) {+ alignedVirtualSize = virtualSize;+ }+ else {+ alignedVirtualSize = getAlignedSizeOfRawData(optionalHeader, log);+ }++ return alignedVirtualSize;}/**- * {@return the file offset where the data for the section begins}- * <p>- * For executables, this value *should* be a multiple of the file alignment given in the PE- * header.- * <p>- * Note: While this value *should* be a multiple of the file alignment, Windows will round down- * to the nearest multiple of 0x200 regardless of the file alignment. Also note that for values- * below 0x200 but above 0x0 Windows will round down to 0 but still load the section into memory- * instead of not loading anything as it would if it were 0 from the start.+ * {@return the original, unaligned offset of the section in the file}*/public int getPointerToRawData() {- return (pointerToRawData / 0x200) * 0x200;+ return pointerToRawData;}/**- * {@return the file offset where the data for the section begins, as specified in the file.- * This value does not take alignment into account, and may not represent the true start of- * the data in the file}+ * {@return the aligned offset of the section in the file}*- * @see #getPointerToRawData()+ * @param optionalHeader The {@link OptionalHeader}, or {@code null} if not available+ * @param log A log to report errors to*/- public int getRawPointerToRawData() {- return pointerToRawData;+ public int getAlignedPointerToRawData(OptionalHeader optionalHeader, MessageLog log) {+ if (alignedPointerToRawData != null) {+ return alignedPointerToRawData;+ }++ alignedPointerToRawData = pointerToRawData;++ // While this value *should* be a multiple of the file alignment, Windows will round down+ // to the nearest multiple of 0x200 regardless of the file alignment. Also note that for+ // values below 0x200 but above 0x0 Windows will round down to 0 but still load the section+ // into memory instead of not loading anything as it would if it were 0 from the start.+ if (optionalHeader.getFileAlignment() >= 0x200) {+ PeUtils.alignDown(pointerToRawData, 0x200);+ }++ // Ensure aligned PointerToRawData is within file bounds+ if (alignedPointerToRawData >= reader.length()) {+ log.appendMsg("NOTE: Section '%s' begins after end of file!".formatted(name));+ alignedPointerToRawData = 0;+ }++ return alignedPointerToRawData;+ }++ /**+ * {@return the original, unaligned size of the section in the file}+ */+ public int getSizeOfRawData() {+ return sizeOfRawData;+ }++ /**+ * {@return the aligned size of the section in the file}+ *+ * @param optionalHeader The {@link OptionalHeader}, or {@code null} if not available+ * @param log A log to report errors to+ */+ public int getAlignedSizeOfRawData(OptionalHeader optionalHeader, MessageLog log) {+ if (alignedSizeOfRawData != null) {+ return alignedSizeOfRawData;+ }++ int fileAlignment = optionalHeader.getFileAlignment();+ if (sizeOfRawData % fileAlignment != 0) {+ log.appendMsg(+ "NOTE: Section '%s' has SizeOfRawData (0x%x) that is not a multiple of the file alignment (0x%x)"+ .formatted(name, sizeOfRawData, fileAlignment));+ }+ alignedSizeOfRawData =+ fileAlignment > 0 ? PeUtils.alignUp(sizeOfRawData, fileAlignment) : sizeOfRawData;++ // Malware can deliberately set invalid or abnormally large values of SizeOfRawData+ // to break static analysis. If we suspect that is happening, default to the+ // VirtualSize. This may result in padding bytes being replaced by garbage bytes,+ // but it will allow the binary to be imported and analyzed.+ if (sizeOfRawData < 0) {+ log.appendMsg("NOTE: Section '%s' has negative SizeOfRawData (0x%x)".formatted(name,+ sizeOfRawData));+ log.appendMsg(+ "Using '%s' VirtualSize (0x%x) in its place".formatted(name, virtualSize));+ alignedSizeOfRawData = virtualSize;+ }++ // Ensure SizeOfRawData does not exceed the aligned VirtualSize+ alignedSizeOfRawData =+ Math.min(alignedSizeOfRawData, getAlignedVirtualSize(optionalHeader, log));++ // Ensure aligned PointerToRawData + SizeOfRawData doesn't exceed the length of the file+ int ptr = getAlignedPointerToRawData(optionalHeader, log);+ if (ptr + alignedSizeOfRawData > reader.length()) {+ int newSizeOfRawData = (int) (reader.length() - ptr);+ log.appendMsg(+ "NOTE: Section '%s' exceeds file length...truncating aligned SizeOfRawData from %d to %d"+ .formatted(name, alignedSizeOfRawData, newSizeOfRawData));+ alignedSizeOfRawData = newSizeOfRawData;+ }++ return alignedSizeOfRawData;}/**@@ -410,8 +477,9 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Writereturn characteristics;}+/**- * {@return the number of line numbers pointed to by the {@code NumberOfRelocations} field}+ * {@return the number of line numbers pointed to by the {@code PointerToLinenumbers} field}*/public short getNumberOfLinenumbers() {return numberOfLinenumbers;@@ -439,6 +507,27 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, WritegetSizeOfRawData());}+ /**+ * {@return whether or not this section has read permissions}+ */+ public boolean isRead() {+ return (characteristics & SectionFlags.IMAGE_SCN_MEM_READ.getMask()) != 0;+ }++ /**+ * {@return whether or not this section has write permissions}+ */+ public boolean isWrite() {+ return (characteristics & SectionFlags.IMAGE_SCN_MEM_WRITE.getMask()) != 0;+ }++ /**+ * {@return whether or not this section has execute permissions}+ */+ public boolean isExecute() {+ return (characteristics & SectionFlags.IMAGE_SCN_MEM_EXECUTE.getMask()) != 0;+ }+@Overridepublic String toString() {StringBuffer buff = new StringBuffer();@@ -489,80 +578,4 @@ public class SectionHeader implements StructConverter, ByteArrayConverter, Writestruct.setCategoryPath(new CategoryPath("/PE"));return struct;}-- @Override- public void write(RandomAccessFile raf, DataConverter dc) throws IOException {- byte[] paddedName = new byte[IMAGE_SIZEOF_SHORT_NAME];- byte[] nameBytes = name.getBytes();- System.arraycopy(nameBytes, 0, paddedName, 0,- Math.min(nameBytes.length, IMAGE_SIZEOF_SHORT_NAME));-- raf.write(paddedName);- raf.write(dc.getBytes(virtualSize));- raf.write(dc.getBytes(virtualAddress));- raf.write(dc.getBytes(sizeOfRawData));- raf.write(dc.getBytes(pointerToRawData));- raf.write(dc.getBytes(pointerToRelocations));- raf.write(dc.getBytes(pointerToLinenumbers));- raf.write(dc.getBytes(numberOfRelocations));- raf.write(dc.getBytes(numberOfLinenumbers));- raf.write(dc.getBytes(characteristics));- }-- /**- * Writes the bytes from this section into the specified random access file. The bytes will be- * written starting at the byte position specified by {@link #getPointerToRawData()}- *- * @param raf the random access file- * @param rafIndex the index into the RAF where the bytes will be written- * @param dc the data converter- * @param block the memory block corresponding to this section- * @param useBlockBytes if true, then use the bytes from the memory block, otherwise use the- * bytes from this section.- * @throws IOException if there are errors writing to the file- * @throws MemoryAccessException if the byte from the memory block cannot be accesses- */- public void writeBytes(RandomAccessFile raf, int rafIndex, DataConverter dc, MemoryBlock block,- boolean useBlockBytes) throws IOException, MemoryAccessException {-- if (getSizeOfRawData() == 0) {- return;- }-- raf.seek(rafIndex);-- if (useBlockBytes) {- byte[] blockBytes = new byte[(int) block.getSize()];- block.getBytes(block.getStart(), blockBytes);- raf.write(blockBytes);- }- else {- raf.write(toBytes(dc));- }-- int padLength = getSizeOfRawData() - getVirtualSize();- if (padLength > 0) {- raf.write(new byte[padLength]);- }- }-- void updatePointers(int offset) {- if (pointerToRawData > 0) {- pointerToRawData += offset;- }- if (pointerToRelocations > 0) {- pointerToRelocations += offset;- }- if (pointerToLinenumbers > 0) {- pointerToLinenumbers += offset;- }- }-- public void setVirtualSize(int size) {- this.virtualSize = size;- }-- public void setSizeOfRawData(int size) {- this.sizeOfRawData = size;- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SeparateDebugHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SeparateDebugHeader.javaindex 4961595e57..0ec8023e31 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SeparateDebugHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/SeparateDebugHeader.java@@ -110,7 +110,7 @@ public class SeparateDebugHeader implements OffsetValidator {sections = new SectionHeader[numberOfSections];for (int i = 0; i < numberOfSections; ++i) {- sections[i] = new SectionHeader(reader, ptr, -1);+ sections[i] = new SectionHeader(reader, ptr, -1, i);ptr += SectionHeader.IMAGE_SIZEOF_SECTION_HEADER;}@@ -126,7 +126,8 @@ public class SeparateDebugHeader implements OffsetValidator {ptr += exportedNamesSize;- parser = new DebugDirectoryParser(reader, ptr, debugDirectorySize, sizeOfImage);+ parser = new DebugDirectoryParser(reader, ptr, debugDirectorySize, sizeOfImage,+ sectionAlignment, 0);}/**@@ -213,9 +214,15 @@ public class SeparateDebugHeader implements OffsetValidator {* Returns the section alignment value.* @return the section alignment value*/+ @Overridepublic int getSectionAlignment() {return sectionAlignment;}++ @Override+ public int getFileAlignment() {+ return 0;+ }/*** Returns the signature (or magic number).@@ -266,5 +273,4 @@ public class SeparateDebugHeader implements OffsetValidator {public boolean checkRVA(long rva) {return (0 <= rva) && (rva <= sizeOfImage);}-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/debug/DebugDirectoryParser.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/debug/DebugDirectoryParser.javaindex c934ade2e5..5a85fd81d9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/debug/DebugDirectoryParser.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/debug/DebugDirectoryParser.java@@ -83,6 +83,8 @@ public class DebugDirectoryParser implements OffsetValidator {private DebugFixup fixupDebug;private BinaryReader reader;private long sizeOfImage;+ private int sectionAlignment;+ private int fileAlignment;/*** Constructs a new debug directory parser.@@ -90,12 +92,16 @@ public class DebugDirectoryParser implements OffsetValidator {* @param ptr the pointer into the binary reader* @param size the size of the directory* @param sizeOfImage the size of the image in memory+ * @param sectionAlignment the section alignment (0 if unknown)+ * @param fileAlignment the file alignment (0 if unknown)* @throws IOException if an I/O error occurs*/- public DebugDirectoryParser(BinaryReader reader, long ptr, int size, long sizeOfImage)- throws IOException {+ public DebugDirectoryParser(BinaryReader reader, long ptr, int size, long sizeOfImage,+ int sectionAlignment, int fileAlignment) throws IOException {this.reader = reader;this.sizeOfImage = sizeOfImage;+ this.sectionAlignment = sectionAlignment;+ this.fileAlignment = fileAlignment;int debugFormatsCount = size / DebugDirectory.IMAGE_SIZEOF_DEBUG_DIRECTORY;for (int i = 0; i < debugFormatsCount; ++i) {@@ -202,4 +208,14 @@ public class DebugDirectoryParser implements OffsetValidator {public boolean checkRVA(long rva) {return (0 <= rva) && (rva <= sizeOfImage);}++ @Override+ public int getFileAlignment() {+ return fileAlignment;+ }++ @Override+ public int getSectionAlignment() {+ return sectionAlignment;+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DbgLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DbgLoader.javaindex 81202e9b61..99f0199624 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DbgLoader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DbgLoader.java@@ -17,10 +17,11 @@ package ghidra.app.util.opinion;import java.io.File;import java.io.IOException;+import java.nio.file.AccessMode;import java.util.*;import ghidra.app.util.bin.ByteProvider;-import ghidra.app.util.bin.RandomAccessByteProvider;+import ghidra.app.util.bin.FileByteProvider;import ghidra.app.util.bin.format.pe.*;import ghidra.app.util.bin.format.pe.PortableExecutable.SectionLayout;import ghidra.program.model.address.Address;@@ -77,26 +78,18 @@ public class DbgLoader extends AbstractPeDebugLoader {String parentPath = prog.getExecutablePath();File parentFile = new File(parentPath);- RandomAccessByteProvider provider2 = null;- try {- provider2 = new RandomAccessByteProvider(parentFile);+ try (FileByteProvider provider2 = new FileByteProvider(parentFile, null, AccessMode.READ)) {PortableExecutable parentPE = new PortableExecutable(provider2, SectionLayout.FILE);Address imageBase = prog.getImageBase();Map<SectionHeader, Address> sectionToAddress = new HashMap<>();FileHeader fileHeader = parentPE.getNTHeader().getFileHeader();- SectionHeader[] sectionHeaders = fileHeader.getSectionHeaders();- for (SectionHeader sectionHeader : sectionHeaders) {+ for (SectionHeader sectionHeader : fileHeader.getSectionHeaders()) {sectionToAddress.put(sectionHeader,imageBase.add(sectionHeader.getVirtualAddress()));}processDebug(debug.getParser(), parentPE.getNTHeader(), sectionToAddress, prog,settings.options(), settings.monitor());}- finally {- if (provider2 != null) {- provider2.close();- }- }}@Overridediff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeDataType.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeDataType.javaindex d95d11876b..7f4f5c466e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeDataType.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeDataType.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -77,8 +77,7 @@ public class PeDataType extends FactoryStructureDataType {addComponent(struct, ntHeader.toDataType(), ntHeader.getName());- SectionHeader[] sections = ntHeader.getFileHeader().getSectionHeaders();- for (SectionHeader section : sections) {+ for (SectionHeader section : ntHeader.getFileHeader().getSectionHeaders()) {addComponent(struct, section.toDataType(), section.getReadableName());}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.javaindex 41c4de5352..2051f33949 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java@@ -52,7 +52,6 @@ import ghidra.program.model.reloc.RelocationTable;import ghidra.program.model.symbol.*;import ghidra.program.model.util.AddressSetPropertyMap;import ghidra.program.model.util.CodeUnitInsertionException;-import ghidra.util.Msg;import ghidra.util.exception.*;import ghidra.util.task.TaskMonitor;@@ -133,7 +132,7 @@ public class PeLoader extends AbstractPeDebugLoader {optionalHeader.validateDataDirectories(program);DataDirectory[] datadirs = optionalHeader.getDataDirectories();- layoutHeaders(program, pe, ntHeader, datadirs);+ layoutHeaders(program, pe, ntHeader, datadirs, monitor, log);for (DataDirectory datadir : datadirs) {if (datadir == null || !datadir.hasParsedCorrectly()) {continue;@@ -153,11 +152,13 @@ public class PeLoader extends AbstractPeDebugLoader {processComments(program.getListing(), monitor);processSymbols(ntHeader, sectionToAddress, program, monitor, log);- processEntryPoints(ntHeader, program, monitor);+ processEntryPoints(ntHeader, program, monitor, log);String compiler =CompilerOpinion.getOpinion(pe, settings.provider(), program, monitor, log).toString();program.setCompiler(compiler);++ reportAnomalies(pe, monitor, log);}catch (AddressOverflowException e) {throw new IOException(e);@@ -233,39 +234,51 @@ public class PeLoader extends AbstractPeDebugLoader {}private void layoutHeaders(Program program, PortableExecutable pe, NTHeader ntHeader,- DataDirectory[] datadirs) {+ DataDirectory[] datadirs, TaskMonitor monitor, MessageLog log) {++ Address imageBase = program.getImageBase();+try {- DataType dt = pe.getDOSHeader().toDataType();- Address start = program.getImageBase();- DataUtilities.createData(program, start, dt, -1,+ DataUtilities.createData(program, imageBase, pe.getDOSHeader().toDataType(), -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ }+ catch (Exception e) {+ log.appendMsg("Error laying down DOS header: " + e.getMessage());+ }- dt = pe.getRichHeader().toDataType();+ try {+ DataType dt = pe.getRichHeader().toDataType();if (dt != null) {- start = program.getImageBase().add(pe.getRichHeader().getOffset());+ Address start = imageBase.add(pe.getRichHeader().getOffset());DataUtilities.createData(program, start, dt, -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);}+ }+ catch (Exception e) {+ log.appendMsg("Error laying down Rich header: " + e.getMessage());+ }- dt = ntHeader.toDataType();- start = program.getImageBase().add(pe.getDOSHeader().e_lfanew());- DataUtilities.createData(program, start, dt, -1,+ try {+ Address start = imageBase.add(pe.getDOSHeader().e_lfanew());+ DataUtilities.createData(program, start, ntHeader.toDataType(), -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ }+ catch (Exception e) {+ log.appendMsg("Error laying down NT header: " + e.getMessage());+ }- FileHeader fh = ntHeader.getFileHeader();- SectionHeader[] sections = fh.getSectionHeaders();- int index = fh.getPointerToSections();- start = program.getImageBase().add(index);- for (SectionHeader section : sections) {- dt = section.toDataType();- DataUtilities.createData(program, start, dt, -1,+ FileHeader fh = ntHeader.getFileHeader();+ Address start = imageBase.add(fh.getPointerToSections());+ for (SectionHeader section : fh.getSectionHeaders()) {+ try {+ DataUtilities.createData(program, start, section.toDataType(), -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);- setComment(CommentType.EOL, start, section.getName());- start = start.add(dt.getLength());}- }- catch (Exception e1) {- Msg.error(this, "Error laying down header structures " + e1);+ catch (Exception e) {+ log.appendMsg("Error laying down Section header: " + e.getMessage());+ }+ setComment(CommentType.EOL, start, section.getReadableName());+ start = start.add(SectionHeader.IMAGE_SIZEOF_SECTION_HEADER);}}@@ -619,166 +632,121 @@ public class PeLoader extends AbstractPeDebugLoader {protected Map<SectionHeader, Address> processMemoryBlocks(PortableExecutable pe, Program prog,FileBytes fileBytes, TaskMonitor monitor, MessageLog log)- throws AddressOverflowException {+ throws AddressOverflowException, IOException, CancelledException {AddressFactory af = prog.getAddressFactory();AddressSpace space = af.getDefaultAddressSpace();Map<SectionHeader, Address> sectionToAddress = new HashMap<>();- if (monitor.isCancelled()) {- return sectionToAddress;- }- monitor.setMessage("[" + prog.getName() + "]: processing memory blocks...");-NTHeader ntHeader = pe.getNTHeader();FileHeader fileHeader = ntHeader.getFileHeader();OptionalHeader optionalHeader = ntHeader.getOptionalHeader();-- SectionHeader[] sections = fileHeader.getSectionHeaders();- if (sections.length == 0) {- Msg.warn(this, "No sections found");- }+ List<SectionHeader> sections = fileHeader.getSectionHeaders();// Header block- int virtualSize = (int) Math.min(getVirtualSize(pe, sections, space), fileBytes.getSize());- long addr = optionalHeader.getImageBase();- Address address = space.getAddress(addr);-- boolean r = true;- boolean w = false;- boolean x = false;- MemoryBlockUtils.createInitializedBlock(prog, false, HEADERS, address, fileBytes, 0,- virtualSize, "", "", r, w, x, log);+ int headerSize = (int) Math.min(getHeaderSize(pe, sections, space), fileBytes.getSize());+ Address imageBase = space.getAddress(optionalHeader.getImageBase());+ MemoryBlockUtils.createInitializedBlock(prog, false, HEADERS, imageBase, fileBytes, 0,+ headerSize, "", "", true, false, false, log);// Section blocks- try {- for (int i = 0; i < sections.length; ++i) {- if (monitor.isCancelled()) {- return sectionToAddress;- }+ monitor.setMessage("[" + prog.getName() + "]: processing sections...");+ if (sections.isEmpty()) {+ log.appendMsg("No sections found");+ }+ for (SectionHeader section : sections) {+ monitor.checkCancelled();- addr = sections[i].getVirtualAddress() + optionalHeader.getImageBase();+ Address addr = imageBase.add(section.getAlignedVirtualAddress(optionalHeader));- address = space.getAddress(addr);+ String sectionName = section.getReadableName();+ int alignedRawSize = section.getAlignedSizeOfRawData(optionalHeader, log);+ int alignedRawPtr = section.getAlignedPointerToRawData(optionalHeader, log);+ int alignedVirtualSize = section.getAlignedVirtualSize(optionalHeader, log);+ MemoryBlock block = null;- String sectionName = sections[i].getReadableName();- if (sectionName.isBlank()) {- sectionName = "SECTION." + i;- }-- r = ((sections[i].getCharacteristics() &- SectionFlags.IMAGE_SCN_MEM_READ.getMask()) != 0x0);- w = ((sections[i].getCharacteristics() &- SectionFlags.IMAGE_SCN_MEM_WRITE.getMask()) != 0x0);- x = ((sections[i].getCharacteristics() &- SectionFlags.IMAGE_SCN_MEM_EXECUTE.getMask()) != 0x0);-- int rawSize = sections[i].getSizeOfRawData();- int rawPtr = sections[i].getPointerToRawData();- long fileBytesSize = fileBytes.getSize();- virtualSize = sections[i].getVirtualSize();- int unchangedRawPtr = sections[i].getRawPointerToRawData();- MemoryBlock block = null;-- if (virtualSize == 0) {- Msg.error(this, "Section '%s' has size zero".formatted(sectionName));- }+ if (section.getVirtualSize() == 0) {+ log.appendMsg("NOTE: Section '%s' has size zero".formatted(sectionName));+ }- // Malware can deliberately set invalid or abnormally large values of SizeOfRawData- // to break static analysis. If we suspect that is happening, default to the- // VirtualSize. This may result in padding bytes being replaced by garbage bytes,- // but it will allow the binary to be imported and analyzed.- if (rawSize < 0) {- log.appendMsg("WARNING: Section '%s' has negative SizeOfRawData (0x%x)"- .formatted(sectionName, rawSize));- log.appendMsg("Using '%s' VirtualSize (0x%x) in its place"- .formatted(sectionName, virtualSize));- rawSize = virtualSize;+ // If PointerToRawData and SizeOfRawData are set, make an initialized block from+ // the FileBytes (check original PointerToRawData value, not the aligned version)+ if (section.getPointerToRawData() != 0 && alignedRawSize != 0) {+ try {+ block = MemoryBlockUtils.createInitializedBlock(prog, false, sectionName, addr,fileBytes, alignedRawPtr, alignedRawSize, "", "", section.isRead(),section.isWrite(), section.isExecute(), log);}-- // If PointerToRawData and SizeOfRawData are set, make an initialized block from- // the FileBytes (check PointerToRawData before it was rounded down)- if (rawSize != 0 && unchangedRawPtr != 0) {- int n = rawSize > virtualSize && virtualSize > 0 ? virtualSize : rawSize;- if (rawPtr + n > fileBytesSize) {- int orig = n;- n = (int) (fileBytesSize - rawPtr);- log.appendMsg(- "WARNING: Section '%s' (0x%x) extends beyond end of file...truncating to 0x%x"- .formatted(sectionName, orig, n));- }- if (n > 0) {- block = MemoryBlockUtils.createInitializedBlock(prog, false, sectionName,- address, fileBytes, rawPtr, n, "", "", r, w, x, log);- sectionToAddress.put(sections[i], address);- virtualSize -= n;- address = address.add(n);- }+ catch (Exception e) {+ throw new IOException(+ "Failed to create memory block for section '%s' (offset 0x%x, size 0x%x, addr %s"+ .formatted(sectionName, alignedRawPtr, alignedRawSize, addr));}+ sectionToAddress.put(section, addr);+ alignedVirtualSize -= alignedRawSize;+ addr = addr.add(alignedRawSize);+ }- // If there is any virtual size left, map in the padding bytes- if (virtualSize > 0) {- if (block != null) {- // Put the padding bytes in the same block we created above- MemoryBlock paddingBlock = MemoryBlockUtils.createInitializedBlock(prog,- false, sectionName, address, virtualSize, "", "", r, w, x, log);- if (paddingBlock != null) {- try {- prog.getMemory().join(block, paddingBlock);- }- catch (Exception e) {- log.appendMsg(e.getMessage());- }+ // If there is any virtual size left, map in the padding bytes+ if (alignedVirtualSize > 0) {+ if (block != null) {+ // Put the padding bytes in the same block we created above+ MemoryBlock paddingBlock = MemoryBlockUtils.createInitializedBlock(prog,+ false, sectionName, addr, alignedVirtualSize, "", "", section.isRead(),+ section.isWrite(), section.isExecute(), log);+ if (paddingBlock != null) {+ try {+ prog.getMemory().join(block, paddingBlock);+ }+ catch (Exception e) {+ log.appendMsg(e.getMessage());}- }- else {- // We didn't create an initialized block above. Put all the padding in a- // new uninitialized block.- MemoryBlockUtils.createUninitializedBlock(prog, false, sectionName,- address, virtualSize, "", "", r, w, x, log);- sectionToAddress.putIfAbsent(sections[i], address);}}-- }- }- catch (IllegalStateException ise) {- if (optionalHeader.getFileAlignment() != optionalHeader.getSectionAlignment()) {- throw new IllegalStateException(ise);+ else {+ // We didn't create an initialized block above. Put all the padding in a+ // new uninitialized block.+ MemoryBlockUtils.createUninitializedBlock(prog, false, sectionName,+ addr, alignedVirtualSize, "", "", section.isRead(), section.isWrite(),+ section.isExecute(), log);+ sectionToAddress.putIfAbsent(section, addr);+ }}- log.appendMsg("Section header processing aborted");}return sectionToAddress;}- protected int getVirtualSize(PortableExecutable pe, SectionHeader[] sections,+ protected int getHeaderSize(PortableExecutable pe, List<SectionHeader> sections,AddressSpace space) {DOSHeader dosHeader = pe.getDOSHeader();- OptionalHeader optionalHeader = pe.getNTHeader().getOptionalHeader();- int virtualSize = optionalHeader.is64bit() ? Constants.IMAGE_SIZEOF_NT_OPTIONAL64_HEADER- : Constants.IMAGE_SIZEOF_NT_OPTIONAL32_HEADER;- virtualSize += FileHeader.IMAGE_SIZEOF_FILE_HEADER + 4;- virtualSize += dosHeader.e_lfanew();- if (optionalHeader.getSizeOfHeaders() > virtualSize) {- virtualSize = (int) optionalHeader.getSizeOfHeaders();- }-- if (optionalHeader.getFileAlignment() == optionalHeader.getSectionAlignment()) {- if (optionalHeader.getFileAlignment() <= 0x800) {- Msg.warn(this,- "File and section alignments identical - possible driver or sectionless image");- }+ NTHeader ntHeader = pe.getNTHeader();+ FileHeader fileHeader = ntHeader.getFileHeader();+ OptionalHeader optionalHeader = ntHeader.getOptionalHeader();++ int optionalHeaderSize = 0;+ if (optionalHeader != null) {+ // The SizeOfOptionalHeader field can be defined to be much larger than the actual size+ // of the structure, but we must respect it+ optionalHeaderSize = Math.max(fileHeader.getSizeOfOptionalHeader(),+ optionalHeader.is64bit() ? Constants.IMAGE_SIZEOF_NT_OPTIONAL64_HEADER+ : Constants.IMAGE_SIZEOF_NT_OPTIONAL32_HEADER);+ }++ int size = dosHeader.e_lfanew();+ size += NTHeader.SIZEOF_SIGNATURE;+ size += FileHeader.IMAGE_SIZEOF_FILE_HEADER;+ size += optionalHeaderSize;+ size += SectionHeader.IMAGE_SIZEOF_SECTION_HEADER * fileHeader.getNumberOfSections();++ if (optionalHeader != null) {+ size = PeUtils.alignUp(Math.max(size, optionalHeader.getSizeOfHeaders()),+ optionalHeader.getFileAlignment());}- //long max = space.getMaxAddress().getOffset() - optionalHeader.getImageBase();- //if (virtualSize > max) {- // virtualSize = (int) max;- // Msg.error(this, "Possible truncation of image at "+Long.toHexString(optionalHeader.getImageBase()));- //}- return virtualSize;++ return size;}- private void processEntryPoints(NTHeader ntHeader, Program prog, TaskMonitor monitor) {+ private void processEntryPoints(NTHeader ntHeader, Program prog, TaskMonitor monitor,+ MessageLog log) {if (monitor.isCancelled()) {return;}@@ -794,7 +762,7 @@ public class PeLoader extends AbstractPeDebugLoader {if (ptr < 0) {if (entry != 0 ||(ntHeader.getFileHeader().getCharacteristics() & FileHeader.IMAGE_FILE_DLL) == 0) {- Msg.warn(this, "Virtual entry point at " + Long.toHexString(entry));+ log.appendMsg("NOTE: Virtual entry point at 0x%x".formatted(entry));}}Address baseAddr = space.getAddress(entry);@@ -814,7 +782,7 @@ public class PeLoader extends AbstractPeDebugLoader {symTable.addExternalEntryPoint(entryAddr);}catch (InvalidInputException e) {- Msg.warn(this,+ log.appendMsg("Backwards compatible native entry point in the CIL binary couldn't be processed");}}@@ -897,6 +865,33 @@ public class PeLoader extends AbstractPeDebugLoader {processDebug(parser, ntHeader, sectionToAddress, program, options, monitor);}+ private void reportAnomalies(PortableExecutable pe, TaskMonitor monitor, MessageLog log) {++ NTHeader ntHeader = pe.getNTHeader();+ FileHeader fileHeader = ntHeader.getFileHeader();+ OptionalHeader optionalHeader = ntHeader.getOptionalHeader();+ final int PAGE_SIZE = fileHeader.getDefaultPageSize();++ int fileAlignment = optionalHeader.getFileAlignment();+ if (fileAlignment < 0x200 || fileAlignment > 0x10000 || fileAlignment % 2 != 0) {+ log.appendMsg("NOTE: File alignment is not a power of 2 between 512 and 64k: 0x%x"+ .formatted(fileAlignment));+ }++ int sectionAlignment = optionalHeader.getSectionAlignment();+ if (sectionAlignment < fileAlignment) {+ log.appendMsg(+ "NOTE: Section alignment (0x%x) is not greater than or equal to file alignment (0x%x)"+ .formatted(sectionAlignment, fileAlignment));+ }++ if (sectionAlignment < PAGE_SIZE && sectionAlignment != fileAlignment) {+ log.appendMsg(+ "NOTE: Section alignment (0x%x) is less than page size (0x%x) but doesn't match file alignment (0x%x)"+ .formatted(sectionAlignment, PAGE_SIZE, fileAlignment));+ }+ }+@Overridepublic String getName() {return PE_NAME;@@ -1013,8 +1008,11 @@ public class PeLoader extends AbstractPeDebugLoader {}} // End PE header offset check- byte[] asm = provider.readBytes(0x40, 256);+ if (0x40 + 256 > provider.length()) {+ return CompilerEnum.Unknown;+ }asmChoice = CompilerEnum.Unknown;+ byte[] asm = provider.readBytes(0x40, 256);if (Arrays.compare(asm, 0, asm16_Borland.length, asm16_Borland, 0,asm16_Borland.length) == 0) {asmChoice = CompilerEnum.BorlandUnk;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/DumpPeShim.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/DumpPeShim.javaindex 917f99eca6..58f7ff8131 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/DumpPeShim.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/DumpPeShim.java@@ -140,102 +140,51 @@ public class DumpPeShim extends PeLoader {@Overrideprotected Map<SectionHeader, Address> processMemoryBlocks(PortableExecutable pe, Program prog,FileBytes fileBytes, TaskMonitor monitor, MessageLog log)- throws AddressOverflowException {+ throws AddressOverflowException, CancelledException {AddressFactory af = prog.getAddressFactory();AddressSpace space = af.getDefaultAddressSpace();Map<SectionHeader, Address> sectionToAddress = new HashMap<>();- if (monitor.isCancelled()) {- return sectionToAddress;- }- monitor.setMessage("[" + prog.getName() + "]: processing memory blocks...");-NTHeader ntHeader = pe.getNTHeader();FileHeader fileHeader = ntHeader.getFileHeader();OptionalHeader optionalHeader = ntHeader.getOptionalHeader();+ List<SectionHeader> sections = fileHeader.getSectionHeaders();++ // Header block+ int headerSize = (int) Math.min(getHeaderSize(pe, sections, space), fileBytes.getSize());+ Address imageBase = space.getAddress(optionalHeader.getImageBase());+ adjustBlock(imageBase, headerSize, HEADERS);- SectionHeader[] sections = fileHeader.getSectionHeaders();- if (sections.length == 0) {- Msg.warn(this, "No sections found");+ // Section blocks+ monitor.setMessage("[" + prog.getName() + "]: processing sections...");+ if (sections.isEmpty()) {+ log.appendMsg("No sections found");}+ for (SectionHeader section : sections) {+ monitor.checkCancelled();- // Header block- int virtualSize = (int) Math.min(getVirtualSize(pe, sections, space), fileBytes.getSize());- long addr = optionalHeader.getImageBase();- Address address = space.getAddress(addr);+ Address addr = imageBase.add(section.getAlignedVirtualAddress(optionalHeader));- adjustBlock(address, virtualSize, HEADERS);+ String sectionName = section.getReadableName();+ int alignedRawSize = section.getAlignedSizeOfRawData(optionalHeader, log);+ int alignedVirtualSize = section.getAlignedVirtualSize(optionalHeader, log);- // Section blocks- try {- for (int i = 0; i < sections.length; ++i) {- if (monitor.isCancelled()) {- return sectionToAddress;- }-- addr = sections[i].getVirtualAddress() + optionalHeader.getImageBase();-- address = space.getAddress(addr);-- int rawDataSize = sections[i].getSizeOfRawData();- int rawDataPtr = sections[i].getPointerToRawData();- virtualSize = sections[i].getVirtualSize();- if (rawDataSize != 0 && rawDataPtr != 0) {- int dataSize =- ((rawDataSize > virtualSize && virtualSize > 0) || rawDataSize < 0)- ? virtualSize- : rawDataSize;- if (ntHeader.checkRVA(dataSize) ||- (0 < dataSize && dataSize < pe.getFileLength())) {- if (!ntHeader.checkRVA(dataSize)) {- Msg.warn(this, "OptionalHeader.SizeOfImage < size of " +- sections[i].getName() + " section");- }- String sectionName = sections[i].getReadableName();- if (sectionName.isBlank()) {- sectionName = "SECTION." + i;- }- sectionToAddress.put(sections[i], address);- adjustBlock(address, virtualSize, sectionName);- }- if (rawDataSize == virtualSize) {- continue;- }- else if (rawDataSize > virtualSize) {- // virtual size fully initialized- continue;- }- // remainder of virtual size is uninitialized- if (rawDataSize < 0) {- Msg.error(this,- "Section[" + i + "] has invalid size " +- Integer.toHexString(rawDataSize) + " (" +- Integer.toHexString(virtualSize) + ")");- break;- }- virtualSize -= rawDataSize;- address = address.add(rawDataSize);- }-- if (virtualSize == 0) {- Msg.error(this, "Section[" + i + "] has size zero");- }- else {- int dataSize = (virtualSize > 0 || rawDataSize < 0) ? virtualSize : 0;- if (dataSize > 0) {- sectionToAddress.put(sections[i], address);- adjustBlock(address, virtualSize, sections[i].getReadableName());- }- }+ if (section.getVirtualSize() == 0) {+ log.appendMsg("Section '%s' has size zero".formatted(sectionName));+ }+ if (section.getPointerToRawData() != 0 && alignedRawSize != 0) {+ sectionToAddress.put(section, addr);+ adjustBlock(addr, alignedVirtualSize, sectionName);+ alignedVirtualSize -= alignedRawSize;+ addr = addr.add(alignedRawSize);}- }- catch (IllegalStateException ise) {- if (optionalHeader.getFileAlignment() != optionalHeader.getSectionAlignment()) {- throw new IllegalStateException(ise);++ if (alignedVirtualSize > 0) {+ adjustBlock(addr, alignedVirtualSize, sectionName);+ sectionToAddress.putIfAbsent(section, addr);}- Msg.warn(this, "Section header processing aborted");}return sectionToAddress;