Ghidra is a software reverse engineering (SRE) framework
GP-1605 improved ELF logging and processing of malformed/missing headers
ghidra1df97c0a50939
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.javaindex 26c947419e..b423fe8060 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java@@ -80,7 +80,8 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPIByteProvider provider = new MemoryByteProvider(currentProgram.getMemory(),currentProgram.getAddressFactory().getDefaultAddressSpace());try {- ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider,+ msg -> messages.appendMsg(msg));elf.parse();processElfHeader(elf, listing);@@ -325,7 +326,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPIElfStringTable dynamicStringTable = elf.getDynamicStringTable();if (dynamicStringTable != null) {String str = dynamicStringTable.readString(reader, dynamic.getValue());- if (str != null) {+ if (str != null && str.length() != 0) {data.setComment(CodeUnit.EOL_COMMENT, str);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.javaindex 0d3a28734c..504d7ae0b6 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java@@ -158,9 +158,8 @@ public class BinaryReader {* the underlying byte provider is valid.* @param index the index in the byte provider* @return returns true if the specified index is valid- * @exception IOException if an I/O error occurs*/- public boolean isValidIndex(int index) throws IOException {+ public boolean isValidIndex(int index) {return provider.isValidIndex(index & Conv.INT_MASK);}@@ -169,9 +168,8 @@ public class BinaryReader {* the underlying byte provider is valid.* @param index the index in the byte provider* @return returns true if the specified index is valid- * @exception IOException if an I/O error occurs*/- public boolean isValidIndex(long index) throws IOException {+ public boolean isValidIndex(long index) {return provider.isValidIndex(index);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProviderWrapper.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProviderWrapper.javaindex b608c8b7f4..fced8c7a90 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProviderWrapper.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProviderWrapper.java@@ -24,10 +24,11 @@ import ghidra.formats.gfilesystem.FSRL;* A {@link ByteProvider} constrained to a sub-section of an existing {@link ByteProvider}.*/public class ByteProviderWrapper implements ByteProvider {- private ByteProvider provider;- private long subOffset;- private long subLength;- private FSRL fsrl;++ protected final ByteProvider provider;+ protected final long subOffset;+ protected final long subLength;+ protected final FSRL fsrl;/*** Creates a wrapper around a {@link ByteProvider} that contains the same bytes as the specified@@ -114,11 +115,20 @@ public class ByteProviderWrapper implements ByteProvider {@Overridepublic byte readByte(long index) throws IOException {+ if (index < 0 || index >= subLength) {+ throw new IOException("Invalid index: " + index);+ }return provider.readByte(subOffset + index);}@Overridepublic byte[] readBytes(long index, long length) throws IOException {+ if (index < 0 || index >= subLength) {+ throw new IOException("Invalid index: " + index);+ }+ if (index + length > subLength) {+ throw new IOException("Unable to read past EOF: " + index + ", " + length);+ }return provider.readBytes(subOffset + index, length);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/UnlimitedByteProviderWrapper.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/UnlimitedByteProviderWrapper.javanew file mode 100644index 0000000000..774243d28b--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/UnlimitedByteProviderWrapper.java@@ -0,0 +1,114 @@+/* ###+ * 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;++import java.io.IOException;++import ghidra.formats.gfilesystem.FSRL;++/**+ * A {@link ByteProvider} constrained to a sub-section of an existing {@link ByteProvider}+ * although reads beyond the specified sub-section are permitted but will return zero byte+ * values. The methods {@link #length()} and {@link #getInputStream(long)} remain+ * bounded by the specified sub-section.+ */+public class UnlimitedByteProviderWrapper extends ByteProviderWrapper {++ /**+ * Creates a wrapper around a {@link ByteProvider} that contains the same bytes as the specified+ * provider.+ * <p>+ *+ * @param provider {@link ByteProvider} to wrap+ * @throws IOException if error+ */+ public UnlimitedByteProviderWrapper(ByteProvider provider) throws IOException {+ this(provider, 0, provider.length(), provider.getFSRL());+ }++ /**+ * Creates a wrapper around a {@link ByteProvider} that contains the same bytes as the specified+ * provider, but with a new {@link FSRL} identity.+ * <p>+ *+ * @param provider {@link ByteProvider} to wrap+ * @param fsrl {@link FSRL} identity for the instance+ * @throws IOException if error+ */+ public UnlimitedByteProviderWrapper(ByteProvider provider, FSRL fsrl) throws IOException {+ this(provider, 0, provider.length(), fsrl);+ }++ /**+ * Constructs a {@link UnlimitedByteProviderWrapper} around the specified {@link ByteProvider},+ * constrained to a subsection of the provider.+ *+ * @param provider the {@link ByteProvider} to wrap+ * @param subOffset the offset in the {@link ByteProvider} of where to start the new+ * {@link UnlimitedByteProviderWrapper}+ * @param subLength the length of the new {@link UnlimitedByteProviderWrapper}+ */+ public UnlimitedByteProviderWrapper(ByteProvider provider, long subOffset, long subLength) {+ this(provider, subOffset, subLength, null);+ }++ /**+ * Constructs a {@link UnlimitedByteProviderWrapper} around the specified {@link ByteProvider},+ * constrained to a subsection of the provider.+ *+ * @param provider the {@link ByteProvider} to wrap+ * @param subOffset the offset in the {@link ByteProvider} of where to start the new+ * {@link UnlimitedByteProviderWrapper}+ * @param subLength the length of the new {@link UnlimitedByteProviderWrapper}+ * @param fsrl {@link FSRL} identity of the file this ByteProvider represents+ */+ public UnlimitedByteProviderWrapper(ByteProvider provider, long subOffset, long subLength, FSRL fsrl) {+ super(provider, subOffset, subLength, fsrl);+ }++ @Override+ public boolean isValidIndex(long index) {+ return index >= 0;+ }++ @Override+ public byte readByte(long index) throws IOException {+ if (index < 0) {+ throw new IOException("Invalid index: " + index);+ }+ if (index >= subLength) {+ return 0;+ }+ return provider.readByte(subOffset + index);+ }++ @Override+ public byte[] readBytes(long index, long length) throws IOException {+ if (index < 0) {+ throw new IOException("Invalid index: " + index);+ }+ if (index >= subLength) {+ return new byte[(int) length];+ }+ if (index + length > subLength) {+ byte[] bytes = new byte[(int) length];+ byte[] partialBytes = provider.readBytes(subOffset + index, subLength - index);+ System.arraycopy(partialBytes, 0, bytes, 0, partialBytes.length);+ return bytes;+ }+ return provider.readBytes(subOffset + index, length);+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.javaindex e34edbdb8a..ae47cf9dce 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java@@ -18,6 +18,7 @@ package ghidra.app.util.bin.format.elf;import java.io.IOException;import java.io.RandomAccessFile;import java.util.*;+import java.util.function.Consumer;import generic.continues.GenericFactory;import ghidra.app.util.bin.*;@@ -47,7 +48,8 @@ public class ElfHeader implements StructConverter, Writeable {private HashMap<Integer, ElfSectionHeaderType> sectionHeaderTypeMap;private HashMap<Integer, ElfDynamicType> dynamicTypeMap;- private FactoryBundledWithBinaryReader reader;+ private ByteProvider provider; // original byte provider+ private FactoryBundledWithBinaryReader reader; // based on unlimited byte providerprivate ElfLoadAdapter elfLoadAdapter = new ElfLoadAdapter();private byte e_ident_magic_num; //magic number@@ -91,18 +93,26 @@ public class ElfHeader implements StructConverter, Writeable {private boolean hasLittleEndianHeaders;+ private Consumer<String> errorConsumer;+private static int INITIAL_READ_LEN = ElfConstants.EI_NIDENT + 18;/*** Constructs a new ELF header using the specified byte provider.+ * Only the one header is parsed. The related headers are not+ * parsed until {@link #parse()} is invoked.+ * @param factory instantiation factory* @param provider the byte provider to supply the bytes+ * @param errorConsumer optional error consumer or null for no logging+ * @return ELF Header object* @throws ElfException if the underlying bytes in the byte provider* do not constitute a valid ELF.*/- public static ElfHeader createElfHeader(GenericFactory factory, ByteProvider provider)+ public static ElfHeader createElfHeader(GenericFactory factory, ByteProvider provider,+ Consumer<String> errorConsumer)throws ElfException {ElfHeader elfHeader = (ElfHeader) factory.create(ElfHeader.class);- elfHeader.initElfHeader(factory, provider);+ elfHeader.initElfHeader(factory, provider, errorConsumer);return elfHeader;}@@ -113,20 +123,40 @@ public class ElfHeader implements StructConverter, Writeable {}/**- * Returns the binary reader.+ * Returns the unconstrained binary reader (i.e., reads beyond EOF+ * will return 0-bytes).* @return the binary reader*/public BinaryReader getReader() {return reader;}- protected void initElfHeader(GenericFactory factory, ByteProvider provider)+ /**+ * Returns the byte provider+ * @return the byte provider+ */+ public ByteProvider getByteProvider() {+ return provider;+ }++ void logError(String msg) {+ errorConsumer.accept(msg);+ }++ protected void initElfHeader(GenericFactory factory, ByteProvider provider,+ Consumer<String> errorConsumer)throws ElfException {try {+ this.provider = provider;+ this.errorConsumer = errorConsumer != null ? errorConsumer : msg -> {+ /* no logging if errorConsumer was null */+ };- determineHeaderEndianess(provider);+ determineHeaderEndianess();- reader = new FactoryBundledWithBinaryReader(factory, provider, hasLittleEndianHeaders);+ // reader uses unbounded provider wrapper to allow handling of missing/truncated headers+ reader = new FactoryBundledWithBinaryReader(factory,+ new UnlimitedByteProviderWrapper(provider), hasLittleEndianHeaders);e_ident_magic_num = reader.readNextByte();e_ident_magic_str = reader.readNextAsciiString(ElfConstants.MAGIC_STR_LEN);@@ -159,7 +189,9 @@ public class ElfHeader implements StructConverter, Writeable {e_shoff = reader.readNextLong();}else {- throw new ElfException("Only 32-bit and 64-bit ELF headers are supported.");+ throw new ElfException(+ "Only 32-bit and 64-bit ELF headers are supported (EI_CLASS=0x" ++ Integer.toHexString(e_ident_class) + ")");}e_flags = reader.readNextInt();@@ -201,6 +233,10 @@ public class ElfHeader implements StructConverter, Writeable {}}+ /**+ * Perform parse of all supported headers.+ * @throws IOException if file IO error occurs+ */public void parse() throws IOException {if (reader == null) {@@ -462,7 +498,8 @@ public class ElfHeader implements StructConverter, Writeable {}}catch (NotFoundException e) {- Msg.error(this, "Failed to process relocation section " + section.getNameAsString() ++ errorConsumer+ .accept("Failed to process relocation section " + section.getNameAsString() +": " + e.getMessage());}}@@ -515,7 +552,8 @@ public class ElfHeader implements StructConverter, Writeable {ElfProgramHeader relocTableLoadHeader = getProgramLoadHeaderContaining(relocTableAddr);if (relocTableLoadHeader == null) {- Msg.warn(this, "Failed to locate " + relocTableAddrType.name + " in memory at 0x" ++ errorConsumer+ .accept("Failed to locate " + relocTableAddrType.name + " in memory at 0x" +Long.toHexString(relocTableAddr));return;}@@ -524,7 +562,7 @@ public class ElfHeader implements StructConverter, Writeable {}if (dynamicSymbolTable == null) {- Msg.warn(this, "Failed to process " + relocTableAddrType.name ++ errorConsumer.accept("Failed to process " + relocTableAddrType.name +", missing dynamic symbol table");return;}@@ -614,7 +652,7 @@ public class ElfHeader implements StructConverter, Writeable {// The p_offset may not refer to the start of the DYNAMIC table so we must use// p_vaddr to find it relative to a PT_LOAD segmentlong vaddr = dynamicHeaders[0].getVirtualAddress();- if (vaddr == 0) {+ if (vaddr == 0 || dynamicHeaders[0].getFileSize() == 0) {Msg.warn(this, "ELF Dynamic table appears to have been stripped from binary");return;}@@ -629,7 +667,7 @@ public class ElfHeader implements StructConverter, Writeable {}}else if (dynamicHeaders.length > 1) {- Msg.error(this, "Multiple ELF Dynamic table program headers found");+ errorConsumer.accept("Multiple ELF Dynamic table program headers found");}ElfSectionHeader[] dynamicSections = getSections(ElfSectionHeaderConstants.SHT_DYNAMIC);@@ -658,7 +696,7 @@ public class ElfHeader implements StructConverter, Writeable {adjustAddressForPrelink(dynamicTable.getDynamicValue(ElfDynamicType.DT_STRTAB));}catch (NotFoundException e) {- Msg.warn(this, "ELF does not contain a dynamic string table (DT_STRTAB)");+ errorConsumer.accept("ELF does not contain a dynamic string table (DT_STRTAB)");}}@@ -689,7 +727,7 @@ public class ElfHeader implements StructConverter, Writeable {private ElfStringTable parseDynamicStringTable(long dynamicStringTableAddr) throws IOException {if (!dynamicTable.containsDynamicValue(ElfDynamicType.DT_STRSZ)) {- Msg.warn(this, "Failed to parse DT_STRTAB, missing dynamic dependency");+ errorConsumer.accept("Failed to parse DT_STRTAB, missing dynamic dependency");return null;}@@ -697,7 +735,7 @@ public class ElfHeader implements StructConverter, Writeable {long stringTableSize = dynamicTable.getDynamicValue(ElfDynamicType.DT_STRSZ);if (dynamicStringTableAddr == 0) {- Msg.warn(this, "ELF Dynamic String Table of size " + stringTableSize ++ errorConsumer.accept("ELF Dynamic String Table of size " + stringTableSize +" appears to have been stripped from binary");return null;}@@ -705,7 +743,7 @@ public class ElfHeader implements StructConverter, Writeable {ElfProgramHeader stringTableLoadHeader =getProgramLoadHeaderContaining(dynamicStringTableAddr);if (stringTableLoadHeader == null) {- Msg.warn(this, "Failed to locate DT_STRTAB in memory at 0x" ++ errorConsumer.accept("Failed to locate DT_STRTAB in memory at 0x" +Long.toHexString(dynamicStringTableAddr));return null;}@@ -729,7 +767,7 @@ public class ElfHeader implements StructConverter, Writeable {adjustAddressForPrelink(dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMTAB));}catch (NotFoundException e) {- Msg.warn(this, "ELF does not contain a dynamic symbol table (DT_SYMTAB)");+ errorConsumer.accept("ELF does not contain a dynamic symbol table (DT_SYMTAB)");}}@@ -792,12 +830,12 @@ public class ElfHeader implements StructConverter, Writeable {long tableAddr = dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMTAB);if (tableAddr == 0) {- Msg.warn(this,+ errorConsumer.accept("ELF Dynamic String Table of size appears to have been stripped from binary");}if (dynamicStringTable == null) {- Msg.warn(this, "Failed to process DT_SYMTAB, missing dynamic string table");+ errorConsumer.accept("Failed to process DT_SYMTAB, missing dynamic string table");return null;}@@ -817,13 +855,13 @@ public class ElfHeader implements StructConverter, Writeable {ElfProgramHeader symbolTableLoadHeader = getProgramLoadHeaderContaining(tableAddr);if (symbolTableLoadHeader == null) {- Msg.warn(this,+ errorConsumer.accept("Failed to locate DT_SYMTAB in memory at 0x" + Long.toHexString(tableAddr));return null;}ElfProgramHeader hashTableLoadHeader = getProgramLoadHeaderContaining(hashTableAddr);if (hashTableLoadHeader == null) {- Msg.warn(this, "Failed to locate DT_HASH or DT_GNU_HASH in memory at 0x" ++ errorConsumer.accept("Failed to locate DT_HASH or DT_GNU_HASH in memory at 0x" +Long.toHexString(hashTableAddr));return null;}@@ -889,7 +927,25 @@ public class ElfHeader implements StructConverter, Writeable {return maxSymbolIndex;}- protected void parseSectionHeaders() throws IOException {+ /**+ * Perform offset region check against byte provider.+ * This is done against the byte provider since the+ * reader is unbounded.+ * @param offset starting offset+ * @param length length of range+ * @return true if provider contains specified byte offset range+ */+ private boolean providerContainsRegion(long offset, int length) {+ try {+ return offset >= 0 && (offset + length) <= provider.length();+ }+ catch (IOException e) {+ return false;+ }+ }++ protected void parseSectionHeaders()+ throws IOException {if (reader == null) {throw new IOException("ELF binary reader is null!");}@@ -898,9 +954,17 @@ public class ElfHeader implements StructConverter, Writeable {}parsedSectionHeaders = true;+ boolean missing = false;sectionHeaders = new ElfSectionHeader[e_shnum];for (int i = 0; i < e_shnum; ++i) {long index = e_shoff + (i * e_shentsize);+ if (!missing && !providerContainsRegion(index, e_shentsize)) {+ int unreadCnt = e_shnum - i;+ errorConsumer.accept(+ unreadCnt + " of " + e_shnum ++ " section headers are truncated/missing from file");+ missing = true;+ }reader.setPointerIndex(index);sectionHeaders[i] = ElfSectionHeader.createElfSectionHeader(reader, this);}@@ -914,26 +978,33 @@ public class ElfHeader implements StructConverter, Writeable {}}- private void parseProgramHeaders() throws IOException {- long fileLength = reader.length();+ private void parseProgramHeaders()+ throws IOException {+ boolean missing = false;programHeaders = new ElfProgramHeader[e_phnum];for (int i = 0; i < e_phnum; ++i) {long index = e_phoff + (i * e_phentsize);+ if (!missing && !providerContainsRegion(index, e_phentsize)) {+ int unreadCnt = e_phnum - i;+ errorConsumer.accept(+ unreadCnt + " of " + e_phnum ++ " program headers are truncated/missing from file");+ missing = true;+ }reader.setPointerIndex(index);programHeaders[i] = ElfProgramHeader.createElfProgramHeader(reader, this);}// TODO: Find sample file which requires this hack to verify its necessity// HACK: 07/01/2013 - Added hack for malformed ELF file with only program header sections- ElfProgramHeader[] pheaders = getProgramHeaders();long size = 0;- for (ElfProgramHeader pheader : pheaders) {+ for (ElfProgramHeader pheader : programHeaders) {size += pheader.getFileSize();}- if (size == fileLength) {+ if (size == reader.length()) {// adjust program section file offset to be based on relative read offsetlong relOffset = 0;- for (ElfProgramHeader pheader : pheaders) {+ for (ElfProgramHeader pheader : programHeaders) {pheader.setOffset(relOffset);relOffset += pheader.getFileSize();}@@ -984,8 +1055,8 @@ public class ElfHeader implements StructConverter, Writeable {/*** Inspect the Elf image and determine the default image base prior- * to the {@link #parse()} method being invoked (i.e., only the main Elf- * header structure has been parsed).+ * to any parse method being invoked (i.e., only the main Elf+ * header structure has been parsed during initialization.* The image base is the virtual address of the PT_LOAD program header* with the smallest address or 0 if no program headers exist. By default,* the image base address should be treated as a addressable unit offset.@@ -1001,6 +1072,9 @@ public class ElfHeader implements StructConverter, Writeable {int n = Math.min(e_phnum, MAX_HEADERS_TO_CHECK_FOR_IMAGEBASE);for (int i = 0; i < n; ++i) {long index = e_phoff + (i * e_phentsize);+ if (!providerContainsRegion(index, e_phentsize)) {+ break;+ }reader.setPointerIndex(index);try {int headerType = reader.peekNextInt();@@ -1131,7 +1205,7 @@ public class ElfHeader implements StructConverter, Writeable {return false;}- private void determineHeaderEndianess(ByteProvider provider) throws ElfException, IOException {+ private void determineHeaderEndianess() throws ElfException, IOException {if (provider.length() < INITIAL_READ_LEN) {throw new ElfException("Not enough bytes to be a valid ELF executable.");@@ -1143,7 +1217,8 @@ public class ElfHeader implements StructConverter, Writeable {hasLittleEndianHeaders = false;}else if (bytes[ElfConstants.EI_DATA] != ElfConstants.ELF_DATA_LE) {- throw new ElfException("Unsupported Elf Header");+ errorConsumer.accept("Invalid EI_DATA, assuming little-endian headers (EI_DATA=0x" ++ Integer.toHexString(bytes[ElfConstants.EI_DATA]) + ")");}if (!hasLittleEndianHeaders && bytes[ElfConstants.EI_NIDENT] != 0) {// Header endianess sanity check@@ -1389,6 +1464,9 @@ public class ElfHeader implements StructConverter, Writeable {*/public ElfSectionHeader getSectionAt(long address) {for (ElfSectionHeader sectionHeader : sectionHeaders) {+ if (!sectionHeader.isAlloc()) {+ continue;+ }if (sectionHeader.getAddress() == address) {return sectionHeader;}@@ -1427,7 +1505,7 @@ public class ElfHeader implements StructConverter, Writeable {long fileRangeLength) {long maxOffset = fileOffset + fileRangeLength - 1;for (ElfSectionHeader section : sectionHeaders) {- if (section.getType() == ElfSectionHeaderConstants.SHN_UNDEF) {+ if (section.getType() == ElfSectionHeaderConstants.SHT_NULL) {continue;}long size = section.getSize();@@ -1517,7 +1595,8 @@ public class ElfHeader implements StructConverter, Writeable {*/public ElfProgramHeader getProgramHeaderAt(long virtualAddr) {for (ElfProgramHeader programHeader : programHeaders) {- if (programHeader.getVirtualAddress() == virtualAddr) {+ if (programHeader.getType() == ElfProgramHeaderConstants.PT_LOAD &&+ programHeader.getVirtualAddress() == virtualAddr) {return programHeader;}}@@ -1532,8 +1611,7 @@ public class ElfHeader implements StructConverter, Writeable {*/public ElfProgramHeader getProgramLoadHeaderContaining(long virtualAddr) {for (ElfProgramHeader programHeader : programHeaders) {- if (programHeader == null ||- programHeader.getType() != ElfProgramHeaderConstants.PT_LOAD) {+ if (programHeader.getType() != ElfProgramHeaderConstants.PT_LOAD) {continue;}long start = programHeader.getVirtualAddress();@@ -1818,7 +1896,7 @@ public class ElfHeader implements StructConverter, Writeable {* @param ph the new program header*/public void addProgramHeader(ElfProgramHeader ph) {- ElfProgramHeader[] tmp = new ElfProgramHeader[e_phnum + 1];+ ElfProgramHeader[] tmp = new ElfProgramHeader[programHeaders.length + 1];int pos = tmp.length - 1;@@ -1849,11 +1927,8 @@ public class ElfHeader implements StructConverter, Writeable {programHeaders = tmp;- ++e_phnum;+ e_phnum = (short) programHeaders.length;- if (e_phnum != programHeaders.length) {- throw new IllegalStateException();- }}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.javaindex d6c87c4d73..fa8983b3b1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.java@@ -216,7 +216,7 @@ public class ElfRelocationTable implements ElfFileSection, ByteArrayConverter {// group_sizelong groupSize = LEB128.readAsLong(reader, true);if (groupSize > remainingRelocations) {- Msg.warn(this, "Group relocation count " + groupSize ++ elfHeader.logError("Group relocation count " + groupSize +" exceeded total count " + remainingRelocations);break;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfStringTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfStringTable.javaindex 858eecfd2e..2ed4a2c709 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfStringTable.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfStringTable.java@@ -20,7 +20,6 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.FactoryBundledWithBinaryReader;import ghidra.program.model.data.DataType;-import ghidra.util.Msg;import ghidra.util.exception.DuplicateNameException;public class ElfStringTable implements ElfFileSection {@@ -87,7 +86,7 @@ public class ElfStringTable implements ElfFileSection {return reader.readAsciiString(fileOffset + stringOffset);}catch (IOException e) {- Msg.error(this,+ header.logError("Failed to read Elf String at offset 0x" + Long.toHexString(stringOffset) +" within String Table at offset 0x" + Long.toHexString(fileOffset));}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationContext.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationContext.javaindex 7de8d26b0b..98e80dcbb1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationContext.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationContext.java@@ -24,7 +24,6 @@ import ghidra.program.model.address.Address;import ghidra.program.model.listing.*;import ghidra.program.model.mem.MemoryAccessException;import ghidra.program.model.mem.MemoryBlock;-import ghidra.util.Msg;import ghidra.util.exception.*;/**@@ -264,7 +263,7 @@ public class ElfRelocationContext {}}catch (DuplicateNameException | NotEmptyException | NotFoundException e) {- Msg.error(this, "Failed to reconcile extended EXTERNAL block fragment");+ loadHelper.log("Failed to reconcile extended EXTERNAL block fragment");}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfDataType.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfDataType.javaindex 3e741ad02b..23b0d837d7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfDataType.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfDataType.java@@ -56,8 +56,8 @@ public class ElfDataType extends FactoryStructureDataType {ByteArrayProvider bap = new ByteArrayProvider(bytes);- ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, bap);- elf.parse();+ ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, bap, null);+ elf.parse();struct.add(elf.toDataType());}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoader.javaindex 989dbe1edb..9439010d81 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoader.java@@ -106,7 +106,8 @@ public class ElfLoader extends AbstractLibrarySupportLoader {List<LoadSpec> loadSpecs = new ArrayList<>();try {- ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ ElfHeader elf =+ ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider, null);// TODO: Why do we convey image base to loader ? This will be managed by each loader !List<QueryResult> results =QueryOpinionService.query(getName(), elf.getMachineName(), elf.getFlags());@@ -149,7 +150,7 @@ public class ElfLoader extends AbstractLibrarySupportLoader {try {GenericFactory factory = MessageLogContinuesFactory.create(log);- ElfHeader elf = ElfHeader.createElfHeader(factory, provider);+ ElfHeader elf = ElfHeader.createElfHeader(factory, provider, msg -> log.appendMsg(msg));ElfProgramBuilder.loadElf(elf, program, options, log, monitor);}catch (ElfException e) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoaderOptionsFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoaderOptionsFactory.javaindex 9fe094e5a0..0a10df0409 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoaderOptionsFactory.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfLoaderOptionsFactory.java@@ -61,7 +61,7 @@ public class ElfLoaderOptionsFactory {options.add(new Option(PERFORM_RELOCATIONS_NAME, PERFORM_RELOCATIONS_DEFAULT, Boolean.class,Loader.COMMAND_LINE_ARG_PREFIX + "-applyRelocations"));- ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider, null);long imageBase = elf.findImageBase();if (imageBase == 0 && (elf.isRelocatable() || elf.isSharedObject())) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.javaindex 1159e134ea..1198a3c43e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java@@ -120,7 +120,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {program.setExecutableFormat(ElfLoader.ELF_NAME);// resolve segment/sections and create program memory blocks- ByteProvider byteProvider = elf.getReader().getByteProvider();+ ByteProvider byteProvider = elf.getByteProvider();try (InputStream fileIn = byteProvider.getInputStream(0)) {fileBytes = program.getMemory().createFileBytes(byteProvider.getName(), 0, byteProvider.length(), fileIn,@@ -692,7 +692,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {if (interpProgramHeaders.length != 0) {long offset = interpProgramHeaders[0].getOffset();if (offset == 0) {- Msg.warn(this, "ELF PT_INTERP appears to have been stripped from binary");+ log("ELF PT_INTERP appears to have been stripped from binary");return;}interpStrAddr = findLoadAddress(interpProgramHeaders[0].getOffset(), 1);@@ -879,7 +879,8 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {memory.convertToInitialized(relocBlock, (byte) 0);}catch (Exception e) {- Msg.error(this, "Unexpected Exception", e);+ Msg.error(this,+ "Unexpected exception while converting block to initialized", e);ElfRelocationHandler.markAsUninitializedMemory(program, relocAddr, type,reloc.getSymbolIndex(), symbolName, log);continue;@@ -974,8 +975,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {headerAddr, 0, elf.e_ehsize(), "Elf File Header", false, false, false, monitor);headerAddr = block.getStart();}-- createData(headerAddr, dt);+ createData(headerAddr, program.getDataTypeManager().resolve(dt, null));}catch (Exception e) {log("Failed to markup Elf header: " + getMessage(e));@@ -1012,7 +1012,11 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {addElfHeaderReferenceMarkup(elf.getPhoffComponentOrdinal(), headerAddr);- Data array = createData(headerAddr, arrayDt);+ Data array =+ createData(headerAddr, program.getDataTypeManager().resolve(arrayDt, null));+ if (array == null) {+ return;+ }ElfProgramHeader[] programHeaders = elf.getProgramHeaders();int vaddrFieldIndex = elf.is64Bit() ? 3 : 2; // p_vaddr structure element index@@ -1035,7 +1039,6 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {}}catch (Exception e) {- e.printStackTrace();log("Failed to markup Elf program/segment headers: " + getMessage(e));}}@@ -1070,7 +1073,11 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {addElfHeaderReferenceMarkup(elf.getShoffComponentOrdinal(), headerAddr);- Data array = createData(headerAddr, arrayDt);+ Data array =+ createData(headerAddr, program.getDataTypeManager().resolve(arrayDt, null));+ if (array == null) {+ return;+ }ElfSectionHeader[] sections = elf.getSections();for (int i = 0; i < sections.length; i++) {@@ -1215,7 +1222,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {if (maxRange == null ||(size > 0 && maxRange.getLength() > 0 && maxRange.getLength() < size)) {- Msg.error(this, "ELF unable to find unallocated memory required for " + purpose + ": " ++ log("ELF unable to find unallocated memory required for " + purpose + ": " +program.getName());return null; // NOTE: this will likely cause other errors to follow}@@ -1897,7 +1904,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {.addExtFunction(Library.UNKNOWN, name, null, SourceType.IMPORTED);}catch (InvalidInputException e) {- log.appendMsg("Failed to create external function '" + name + "': " + getMessage(e));+ log("Failed to create external function '" + name + "': " + getMessage(e));return null;}catch (DuplicateNameException e) {@@ -1908,7 +1915,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {if (indirectPointerAddr != null) {MemoryBlock block = memory.getBlock(indirectPointerAddr);if (block == null) {- log.appendMsg("Indirect linkage memory not found at: " + indirectPointerAddr);+ log("Indirect linkage memory not found at: " + indirectPointerAddr);return null;}try {@@ -1916,7 +1923,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {memory.convertToInitialized(block, (byte) 0);}if (program.getDefaultPointerSize() != (elf.is64Bit() ? 8 : 4)) {- log.appendMsg(+ log("Unsupported pointer size for indirect linkage at: " + indirectPointerAddr);return null;}@@ -1929,7 +1936,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {}}catch (Exception e) {- log.appendMsg("Failed to establish linkage to external function '" + name + "': " ++ log("Failed to establish linkage to external function '" + name + "': " +getMessage(e));return null;}@@ -1987,7 +1994,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {listing.createData(address, Undefined.getUndefinedDataType(length));}catch (CodeUnitInsertionException e) {- Msg.warn(this, "ELF data markup conflict at " + address);+ log("ELF data markup conflict at " + address);}catch (DataTypeConflictException e) {throw new AssertException("unexpected", e);@@ -2006,10 +2013,10 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {return d;}catch (CodeUnitInsertionException e) {- Msg.warn(this, "ELF data markup conflict at " + address);+ log("ELF data markup conflict while applying " + dt.getName() + " at " + address);}catch (DataTypeConflictException e) {- Msg.error(this, "ELF data type markup conflict:" + getMessage(e));+ log("ELF data type conflict:" + getMessage(e));}return null;}@@ -2225,8 +2232,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {// Rely on dynamic symbol table for number of symbolsElfSymbolTable dynamicSymbolTable = elf.getDynamicSymbolTable();if (dynamicSymbolTable == null) {- Msg.error(this,- "Failed to markup GNU Hash Table chain data - missing dynamic symbol table");+ log("Failed to markup GNU Hash Table chain data - missing dynamic symbol table");return;}@@ -2324,7 +2330,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {ElfStringTable dynamicStringTable = elf.getDynamicStringTable();if (dynamicStringTable != null) {String str = dynamicStringTable.readString(elf.getReader(), value);- if (str != null) {+ if (str != null && str.length() != 0) {valueData.setComment(CodeUnit.EOL_COMMENT, str);}}@@ -3190,7 +3196,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {return program.getSymbolTable().getSymbol(name, addr, sym.getParentNamespace());}- Msg.error(this, cmd.getStatusMsg());+ log(cmd.getStatusMsg());return sym;}@@ -3206,7 +3212,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {*/private InputStream getInitializedBlockInputStream(MemoryLoadable loadable, Address start,long fileOffset, long dataLength) throws IOException {- InputStream dataInput = elf.getReader().getByteProvider().getInputStream(fileOffset);+ InputStream dataInput = elf.getByteProvider().getInputStream(fileOffset);return elf.getLoadAdapter().getFilteredLoadInputStream(this, loadable, start, dataLength, dataInput);}@@ -3300,7 +3306,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {finally {if (block == null) {Address end = start.addNoWrap(revisedLength - 1);- Msg.error(this, "Unexpected ELF memory bock load conflict when creating '" + name ++ log("Unexpected ELF memory bock load conflict when creating '" + name +"' at " + start.toString(true) + "-" + end.toString(true));}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.javaindex a740f6ae76..ea37005455 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.java@@ -56,14 +56,16 @@ public class OatFileSystem extends GFileSystemBase {if (magicMatch) {ElfHeader elf =- ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider, null);elf.parse();ElfSymbolTable dynamicSymbolTable = elf.getDynamicSymbolTable();- ElfSymbol[] symbols = dynamicSymbolTable.getSymbols();- for (ElfSymbol symbol : symbols) {- if (OatConstants.SYMBOL_OAT_DATA.equals(symbol.getNameAsString())) {- return true;+ if (dynamicSymbolTable != null) {+ ElfSymbol[] symbols = dynamicSymbolTable.getSymbols();+ for (ElfSymbol symbol : symbols) {+ if (OatConstants.SYMBOL_OAT_DATA.equals(symbol.getNameAsString())) {+ return true;+ }}}@@ -96,7 +98,8 @@ public class OatFileSystem extends GFileSystemBase {monitor.setMaximum(10);monitor.setMessage("Parsing ELF header...");monitor.incrementProgress(1);- ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ ElfHeader elf =+ ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider, null);elf.parse();monitor.incrementProgress(1);