Ghidra is a software reverse engineering (SRE) framework
GP-7352 refactor ByteProvider, BinaryReader isValidRange()
dev7473687a14a62b3c07
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 2306a6d6b2..7f3d8937b1 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@@ -34,6 +34,8 @@ public class BinaryReader {// to reach exactly 2g elementsprivate static final int MAX_SANE_BUFFER = Integer.MAX_VALUE - 1024;+ private static final int MAX_SANE_ARRAY_ELEMENT_COUNT = Integer.MAX_VALUE - 1024; // same as MAX_SANE_BUFFER for now+/*** The size of a BYTE in Java.*/@@ -237,29 +239,7 @@ public class BinaryReader {* valid (according to the underlying byte provider)*/public boolean isValidRange(long startIndex, int count) {- if (count < 0) {- return false;- }- if (count > 1) {- // check the end of the range first to fail fast-- long endIndex = startIndex + (count - 1);- if (Long.compareUnsigned(endIndex, startIndex) < 0) {- // the requested range [startIndex..startIndex+count] wraps around the int64 to 0, so fail- return false;- }-- if (!provider.isValidIndex(endIndex)) {- return false;- }- count--; // don't check the last element twice- }- for (int i = 0; i < count; i++) {- if (!provider.isValidIndex(startIndex + i)) {- return false;- }- }- return true;+ return provider.isValidRange(startIndex, count);}/**@@ -1167,9 +1147,8 @@ public class BinaryReader {* @exception IOException if an I/O error occurs*/public byte[] readByteArray(long index, int nElements) throws IOException {- if (nElements < 0) {- throw new IOException("Invalid number of elements specified: " + nElements);- }+ ensureArrayRead(index, nElements, SIZEOF_BYTE);+return provider.readBytes(index, nElements);}@@ -1182,9 +1161,7 @@ public class BinaryReader {* @exception IOException if an I/O error occurs*/public short[] readShortArray(long index, int nElements) throws IOException {- if (nElements < 0) {- throw new IOException("Invalid number of elements specified: " + nElements);- }+ ensureArrayRead(index, nElements, SIZEOF_SHORT);short[] arr = new short[nElements];for (int i = 0; i < nElements; ++i) {arr[i] = readShort(index);@@ -1202,9 +1179,7 @@ public class BinaryReader {* @exception IOException if an I/O error occurs*/public int[] readIntArray(long index, int nElements) throws IOException {- if (nElements < 0) {- throw new IOException("Invalid number of elements specified: " + nElements);- }+ ensureArrayRead(index, nElements, SIZEOF_INT);int[] arr = new int[nElements];for (int i = 0; i < nElements; ++i) {arr[i] = readInt(index);@@ -1222,9 +1197,7 @@ public class BinaryReader {* @exception IOException if an I/O error occurs*/public long[] readLongArray(long index, int nElements) throws IOException {- if (nElements < 0) {- throw new IOException("Invalid number of elements specified: " + nElements);- }+ ensureArrayRead(index, nElements, SIZEOF_LONG);long[] arr = new long[nElements];for (int i = 0; i < nElements; ++i) {arr[i] = readLong(index);@@ -1346,6 +1319,16 @@ public class BinaryReader {}}+ private void ensureArrayRead(long index, int count, int elementSize) throws IOException {+ if (count < 0 || count > MAX_SANE_ARRAY_ELEMENT_COUNT) {+ throw new IOException("Invalid number of elements specified: " + count);+ }+ if (!isValidRange(index, count * elementSize)) {+ throw new IOException("Unable to read array at 0x%x, count=%d, size=%d".formatted(index,+ count, elementSize));+ }+ }+/*** Adapter between this BinaryReader and a InputStream.*/diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteArrayProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteArrayProvider.javaindex f12f16a5c3..bca213384a 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteArrayProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteArrayProvider.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.@@ -107,11 +107,6 @@ public class ByteArrayProvider implements ByteProvider {return srcBytes.length;}- @Override- public boolean isValidIndex(long index) {- return index >= 0 && index < length();- }-/*** Throws {@link IOException} if index is not a valid position in the buffer*diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProvider.javaindex 2e37141ccd..6d1779321b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ByteProvider.java@@ -88,7 +88,28 @@ public interface ByteProvider extends Closeable {* @param index the index in the byte provider to check* @return true if the specified index is valid*/- boolean isValidIndex(long index);+ default boolean isValidIndex(long index) {+ // Note: this default implementation can not correctly handle ByteProviders that use the+ // full uint64 index range (because length() can not be accurate). Override and provide+ // a custom implementation.+ return Long.compareUnsigned(index, length()) < 0;+ }++ /**+ * Returns true if the specified range is valid.+ *+ * @param startIndex the starting index to check+ * @param count the number of bytes to check+ * @return boolean true if all bytes between startIndex to startIndex+count (exclusive) are+ * valid+ */+ default boolean isValidRange(long startIndex, int count) {+ // Note: this default implementation can not correctly handle ByteProviders that use the+ // full uint64 index range (because length() can not be accurate). Override and provide+ // a custom implementation.+ return count >= 0 && isValidIndex(startIndex) &&+ Long.compareUnsigned(startIndex + count, length()) <= 0;+ }/*** Releases any resources the {@link ByteProvider} may have occupieddiff --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 3e02dbb681..ddc3b5bcf6 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@@ -109,7 +109,13 @@ public class ByteProviderWrapper implements ByteProvider {@Overridepublic boolean isValidIndex(long index) {- return (0 <= index && index < subLength) && provider.isValidIndex(subOffset + index);+ return ByteProvider.super.isValidIndex(index) && provider.isValidIndex(subOffset + index);+ }++ @Override+ public boolean isValidRange(long startIndex, int count) {+ return ByteProvider.super.isValidRange(startIndex, count) &&+ provider.isValidRange(subOffset + startIndex, count);}@Overridediff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/EmptyByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/EmptyByteProvider.javaindex 266c837a72..ef0e020660 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/EmptyByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/EmptyByteProvider.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.@@ -91,6 +91,11 @@ public class EmptyByteProvider implements ByteProvider {return false;}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ return false;+ }+@Overridepublic void close() throws IOException {// do nothingdiff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileByteProvider.javaindex bb2d26a812..b14e0bc2c7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileByteProvider.java@@ -110,11 +110,6 @@ public class FileByteProvider implements MutableByteProvider {return currentLength;}- @Override- public boolean isValidIndex(long index) {- return 0 <= index && index < currentLength;- }-@Overridepublic byte readByte(long index) throws IOException {ensureBounds(index, 1);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileBytesProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileBytesProvider.javaindex f397eb6758..e456d79cb9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileBytesProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/FileBytesProvider.java@@ -55,11 +55,6 @@ public class FileBytesProvider implements ByteProvider {return fileBytes.getSize();}- @Override- public boolean isValidIndex(long index) {- return 0 <= index && index < length();- }-@Overridepublic void close() throws IOException {// do nothingdiff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InputStreamByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InputStreamByteProvider.javaindex f6ded3d200..40aa7832e5 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InputStreamByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InputStreamByteProvider.java@@ -76,11 +76,6 @@ public class InputStreamByteProvider implements ByteProvider {return length;}- @Override- public boolean isValidIndex(long index) {- return (index >= 0L) && (index < length);- }-@Overridepublic byte readByte(long index) throws IOException {if (index < currentIndex) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemBufferByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemBufferByteProvider.javaindex 497efbde89..64821fe957 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemBufferByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemBufferByteProvider.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,7 +15,8 @@*/package ghidra.app.util.bin;-import java.io.*;+import java.io.File;+import java.io.IOException;import ghidra.program.model.mem.MemBuffer;import ghidra.program.model.mem.MemoryAccessException;@@ -62,7 +63,7 @@ public class MemBufferByteProvider implements ByteProvider {@Overridepublic boolean isValidIndex(long index) {- if (index < 0 || index > Integer.MAX_VALUE) {+ if (!ByteProvider.super.isValidIndex(index)) {return false;}try {@@ -74,6 +75,23 @@ public class MemBufferByteProvider implements ByteProvider {}}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ if (!ByteProvider.super.isValidRange(startIndex, count)) {+ return false;+ }+ try {+ buffer.getByte((int) startIndex);+ if (count > 1) {+ buffer.getByte((int) (startIndex + count - 1));+ }+ return true;+ }+ catch (MemoryAccessException e) {+ return false;+ }+ }+@Overridepublic void close() throws IOException {// not applicablediff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemoryByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemoryByteProvider.javaindex ef52c1c339..b3e7fc2e32 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemoryByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/MemoryByteProvider.java@@ -98,7 +98,7 @@ public class MemoryByteProvider implements ByteProvider {protected Memory memory;protected Address baseAddress;protected long maxOffset; // max valid offset, inclusive- protected boolean isEmtpy; // empty is tracked separately because maxOffset == 0 does not mean empty+ protected boolean isEmpty; // empty is tracked separately because maxOffset == 0 does not mean empty/*** Constructs a new {@link MemoryByteProvider} for a specific {@link AddressSpace}. Bytes@@ -136,9 +136,10 @@ public class MemoryByteProvider implements ByteProvider {* if false, all memory blocks of the address space will be accessible*/public MemoryByteProvider(Memory memory, Address baseAddress, boolean firstBlockOnly) {- this(memory, baseAddress, firstBlockOnly- ? findEndOfBlock(memory, baseAddress)- : findAddressSpaceMax(memory, baseAddress));+ this(memory, baseAddress,+ firstBlockOnly+ ? findEndOfBlock(memory, baseAddress)+ : findAddressSpaceMax(memory, baseAddress));}/**@@ -153,10 +154,8 @@ public class MemoryByteProvider implements ByteProvider {public MemoryByteProvider(Memory memory, Address baseAddress, Address maxAddress) {this.memory = memory;this.baseAddress = baseAddress;- this.maxOffset = maxAddress != null- ? maxAddress.subtract(baseAddress)- : 0;- this.isEmtpy = maxAddress == null;+ this.maxOffset = maxAddress != null ? maxAddress.subtract(baseAddress) : 0;+ this.isEmpty = maxAddress == null;}public Memory getMemory() {@@ -204,7 +203,7 @@ public class MemoryByteProvider implements ByteProvider {@Overridepublic boolean isEmpty() {- return isEmtpy;+ return isEmpty;}@Override@@ -224,7 +223,7 @@ public class MemoryByteProvider implements ByteProvider {@Overridepublic long length() {- if (isEmtpy) {+ if (isEmpty) {return 0;}@@ -236,13 +235,58 @@ public class MemoryByteProvider implements ByteProvider {@Overridepublic boolean isValidIndex(long index) {+ try {+ // this method treats the index as an unsigned int64, and will give accurate results+ // for the entire range of the underlying AddressSpace+ if (isEmpty || Long.compareUnsigned(index, maxOffset) > 0) {+ return false;+ }+ Address addr = getAddress(index);+ MemoryBlock memBlock = memory.getBlock(addr);+ return memBlock != null && memBlock.isInitialized();+ }+ catch (IOException | AddressOutOfBoundsException e) {+ return false;+ }+ }++ @Override+ public boolean isValidRange(long startIndex, int count) {// this method treats the index as an unsigned int64, and will give accurate results// for the entire range of the underlying AddressSpace++ if (isEmpty || // empty+ Long.compareUnsigned(startIndex, maxOffset) > 0 || // bad start index+ count < 0 || // negative bad count or+ (count > 0 && Long.compareUnsigned(count - 1, maxOffset - startIndex) > 0) // count too long(*)+ ) {+ // Note(*): when evaluating count against the memory range we can't "+1" the expression+ // "maxOffset - startIndex" because that could lead to an overflow, so we shift the +1+ // from there to a "-1" on the count+ return false;+ }+ if (count == 0) {+ return true;+ }+try {- if (isEmtpy || Long.compareUnsigned(index, maxOffset) > 0) {- return false;+ for (long i = startIndex, endIndexInclusive = startIndex + (count - 1); Long+ .compareUnsigned(i, endIndexInclusive) <= 0;) {+ Address address = getAddress(i);+ MemoryBlock block = memory.getBlock(address);+ if (block == null || !block.isInitialized()) {+ return false;+ }+ long delta = block.getEnd().subtract(address);+ i += delta;+ if (Long.compareUnsigned(i, endIndexInclusive) >= 0) {+ // have to check before advancing past the end of the mem block as it might+ // be the absolute end of memory and cause a wrap around+ break;+ }+ i++;}- return memory.contains(getAddress(index));+ return true;}catch (IOException | AddressOutOfBoundsException e) {return false;@@ -298,7 +342,7 @@ public class MemoryByteProvider implements ByteProvider {}// ensure read start index is valid- if (isEmtpy || Long.compareUnsigned(index, maxOffset) > 0) {+ if (isEmpty || Long.compareUnsigned(index, maxOffset) > 0) {throw new EOFException("Invalid index: %s".formatted(Long.toUnsignedString(index)));}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/RangeMappedByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/RangeMappedByteProvider.javaindex 105f03ef01..542cf6378c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/RangeMappedByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/RangeMappedByteProvider.java@@ -133,11 +133,6 @@ public class RangeMappedByteProvider implements ByteProvider {return length;}- @Override- public boolean isValidIndex(long index) {- return 0 <= index && index < length;- }-@Overridepublic void close() throws IOException {// do not close wrapped delegate ByteProviderdiff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/StaticValueByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/StaticValueByteProvider.javanew file mode 100644index 0000000000..d7921c54cf--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/StaticValueByteProvider.java@@ -0,0 +1,110 @@+/* ###+ * 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.*;+import java.util.Arrays;++import ghidra.formats.gfilesystem.FSRL;++/**+ * A {@link ByteProvider} that only has a single value for its entire length+ */+public class StaticValueByteProvider implements ByteProvider {++ private final FSRL fsrl;+ private long length;+ private byte value;++ /**+ * Create an instance with the specified {@link FSRL} identity.+ * @param length provider length+ * @param value byte value of entire provider+ *+ * @param fsrl {@link FSRL} identity for this instance+ */+ public StaticValueByteProvider(long length, byte value, FSRL fsrl) {+ this.length = length;+ this.value = value;+ this.fsrl = fsrl;+ }++ @Override+ public void close() {+ // nothing+ }++ @Override+ public FSRL getFSRL() {+ return fsrl;+ }++ @Override+ public File getFile() {+ return null;+ }++ @Override+ public String getName() {+ return fsrl != null ? fsrl.getName() : null;+ }++ @Override+ public String getAbsolutePath() {+ return fsrl != null ? fsrl.getPath() : "";+ }++ @Override+ public InputStream getInputStream(long index) throws IOException {+ assertValidIndex(index, true);+ return new ByteProviderInputStream(this, index);+ }++ @Override+ public long length() {+ return length;+ }++ /**+ * Throws {@link IOException} if index is not a valid position in the buffer+ *+ * @param index position in buffer to test+ * @param inclusiveMax allow buffer.length as index+ * @throws IOException if index is out of bounds+ */+ private void assertValidIndex(long index, boolean inclusiveMax) throws IOException {+ if (index < 0 || index > length || (inclusiveMax == false && index == length)) {+ throw new IOException("Invalid position, index: " + index + ", max is: " + length);+ }+ }++ @Override+ public byte readByte(long index) throws IOException {+ assertValidIndex(index, false);+ return value;+ }++ @Override+ public byte[] readBytes(long index, long length) throws IOException {+ assertValidIndex(index, true);+ if (index + length > length) {+ throw new IOException("Attempt to read beyond end of byte data");+ }+ byte[] destBytes = new byte[(int) length];+ Arrays.fill(destBytes, value);+ return destBytes;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/SynchronizedByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/SynchronizedByteProvider.javaindex ff90d8aba4..6ed6e966a6 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/SynchronizedByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/SynchronizedByteProvider.java@@ -64,6 +64,11 @@ public class SynchronizedByteProvider implements ByteProvider {return provider.isValidIndex(index);}+ @Override+ public synchronized boolean isValidRange(long startIndex, int count) {+ return provider.isValidRange(startIndex, count);+ }+@Overridepublic synchronized void close() throws IOException {provider.close();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.javaindex eea4db74d0..7474fbd87d 100644--- 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.java@@ -82,6 +82,11 @@ public class UnlimitedByteProviderWrapper extends ByteProviderWrapper {return index >= 0;}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ return startIndex >= 0 && count >= 0;+ }+@Overridepublic byte readByte(long index) throws IOException {if (index < 0) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.javaindex 06e7420ac8..10ac8b8498 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java@@ -85,6 +85,11 @@ public class RefdByteProvider implements ByteProvider {return provider.isValidIndex(index);}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ return provider.isValidRange(startIndex, count);+ }+@Overridepublic byte readByte(long index) throws IOException {return provider.readByte(index);diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/opinion/XmlImportOpinionsTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/opinion/XmlImportOpinionsTest.javaindex 56b0862bc8..dcc898b2ef 100644--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/opinion/XmlImportOpinionsTest.java+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/opinion/XmlImportOpinionsTest.java@@ -217,6 +217,11 @@ public class XmlImportOpinionsTest extends AbstractGhidraHeadlessIntegrationTestthrow new UnsupportedOperationException();}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ throw new UnsupportedOperationException();+ }+@Overridepublic String getName() {return name;diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/BinaryReaderTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/BinaryReaderTest.javaindex 4804be26b0..41eb80a480 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/BinaryReaderTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/BinaryReaderTest.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,11 +15,11 @@*/package ghidra.app.util.bin;-import static org.junit.Assert.assertEquals;-import static org.junit.Assert.fail;+import static org.junit.Assert.*;import java.io.EOFException;import java.io.IOException;+import java.nio.charset.StandardCharsets;import org.junit.Assert;import org.junit.Test;@@ -36,6 +36,10 @@ public class BinaryReaderTest {return new BinaryReader(new ByteArrayProvider(bytes), isLE);}+ private BinaryReader staticValueBR(boolean isLE, long length, byte value) {+ return new BinaryReader(new StaticValueByteProvider(length, value, null), isLE);+ }+@Testpublic void testClone() throws Exception {BinaryReader reader = new BinaryReader(new ByteArrayProvider(new byte[1024]), true);@@ -122,6 +126,31 @@ public class BinaryReaderTest {}}+ @Test+ public void testReadByteArray_oversize() {+ BinaryReader br =+ staticValueBR(true, NumericUtilities.MAX_UNSIGNED_INT32_AS_LONG * 100, (byte) 0xaa);++ try {+ br.readNextByteArray(Integer.MAX_VALUE - 10);+ fail();+ }+ catch (IOException e) {+ // good+ }++ // commenting these next lines out as they will allocate a lot of ram+// try {+// byte[] bytes = br.readNextByteArray(Integer.MAX_VALUE - 1024);+// for (int i = 0; i < bytes.length; i++) {+// assertEquals((byte) 0xaa, bytes[i]);+// }+// }+// catch (IOException e) {+// fail();+// }+ }+// ------------------------------------------------------------------------------------// Shorts// ------------------------------------------------------------------------------------@@ -194,6 +223,20 @@ public class BinaryReaderTest {}}+ @Test+ public void testReadShortArray_oversize() {+ BinaryReader br =+ staticValueBR(true, NumericUtilities.MAX_UNSIGNED_INT32_AS_LONG * 100, (byte) 0xaa);++ try {+ br.readNextShortArray(Integer.MAX_VALUE - 10);+ fail();+ }+ catch (IOException e) {+ // good+ }+ }+// ------------------------------------------------------------------------------------// Ints// ------------------------------------------------------------------------------------@@ -287,6 +330,20 @@ public class BinaryReaderTest {Integer.toUnsignedString(value));}+ @Test+ public void testReadIntArray_oversize() {+ BinaryReader br =+ staticValueBR(true, NumericUtilities.MAX_UNSIGNED_INT32_AS_LONG * 100, (byte) 0xaa);++ try {+ br.readNextIntArray(Integer.MAX_VALUE - 10);+ fail();+ }+ catch (IOException e) {+ // good+ }+ }+// ------------------------------------------------------------------------------------// UTF-16 Unicode String// ------------------------------------------------------------------------------------@@ -538,6 +595,19 @@ public class BinaryReaderTest {br.readAsciiString(0);}+ @Test+ public void test_ReadAsciiString_oversize() {+ BinaryReader br =+ staticValueBR(true, NumericUtilities.MAX_UNSIGNED_INT32_AS_LONG * 100, (byte) 0xaa);+ try {+ br.readString(0, Integer.MAX_VALUE - 10, StandardCharsets.US_ASCII, 1);+ fail();+ }+ catch (IOException e) {+ // good+ }+ }+@Testpublic void test_ReadUtf8String() throws IOException {// tests variable length decodingdiff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/MemoryByteProviderTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/MemoryByteProviderTest.javaindex 3d5fef9d96..b4bec88310 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/MemoryByteProviderTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/MemoryByteProviderTest.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,10 +15,9 @@*/package ghidra.app.util.bin;-import static org.junit.Assert.assertEquals;+import static org.junit.Assert.*;import java.io.EOFException;-import java.io.IOException;import java.nio.charset.StandardCharsets;import org.junit.*;@@ -89,7 +88,7 @@ public class MemoryByteProviderTest extends AbstractGhidraHeadedIntegrationTest}@Test- public void testNoMemory() throws IOException {+ public void testNoMemory() {MemoryByteProvider mbp = MemoryByteProvider.createProgramHeaderByteProvider(program, false);assertEquals(0, mbp.length());@@ -237,4 +236,49 @@ public class MemoryByteProviderTest extends AbstractGhidraHeadedIntegrationTestsetBlockStartEndBytes(blk1, "blah", "fail");reader.readAsciiString(blk1.getEnd().getOffset() - 3);}++ @Test+ public void testIsValidIndex_IsRangeValid_Full64bitAddressSpace() throws Exception {+ addRamEnd();+ MemoryByteProvider mbp =+ MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false);++ assertEquals(Long.MAX_VALUE, mbp.length());+ assertTrue(mbp.isValidIndex(0xffffffffffffffb0L));+ assertTrue(mbp.isValidIndex(0xffffffffffffffffL));++ assertTrue(mbp.isValidRange(0xffffffffffffffb0L, 0x50));+ assertFalse(mbp.isValidRange(0xffffffffffffffb0L, 0x51));+ }++ @Test+ public void testIsValidIndex_IsRangeValid() throws Exception {+ addRam1();+ MemoryByteProvider mbp =+ MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false);++ assertTrue(mbp.isValidIndex(0x50));+ assertTrue(mbp.isValidIndex(0x50 + 0x50 - 1));+ assertFalse(mbp.isValidIndex(0x50 + 0x50));++ assertTrue(mbp.isValidRange(0x50, 0x50));+ assertFalse(mbp.isValidRange(0x50, 0x51));+ }++ @Test+ public void testIsValidIndex_IsRangeValid_adjacent_blocks() throws Exception {+ addRam1();+ addRam2();++ MemoryByteProvider mbp =+ MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false);++ assertTrue(mbp.isValidIndex(0x50));+ assertTrue(mbp.isValidIndex(0x50 + 0x50 - 1));+ assertTrue(mbp.isValidIndex(0x50 + 0x50));+ assertTrue(mbp.isValidIndex(0x50 + 0x50 + 0x50 - 1));++ assertTrue(mbp.isValidRange(0x50, 0x50 + 0x50));+ assertFalse(mbp.isValidRange(0x50, 0x50 + 0x50 + 1));+ }}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.javaindex d01fd6757f..6938a2d0ed 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.java@@ -70,6 +70,21 @@ public class OverlayByteProvider implements ByteProvider {return provider.isValidIndex(index);}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ if (count < 0) {+ return false;+ }+ long endIndexInclusive = startIndex + count - 1; // won't be used if count==0+ for (OverlayRange range : overlayList) {+ if (range.containsIndex(startIndex) &&+ (count == 0 || range.containsIndex(endIndexInclusive))) {+ return true;+ }+ }+ return provider.isValidRange(startIndex, count);+ }+@Overridepublic void close() throws IOException {provider.close();diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/BinaryPropertyListAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/BinaryPropertyListAnalyzer.javaindex c36ac99c08..f4dfc99909 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/BinaryPropertyListAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/BinaryPropertyListAnalyzer.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.@@ -18,8 +18,7 @@ package ghidra.file.formats.bplist;import java.util.HashMap;import java.util.Map;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.*;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;import ghidra.program.model.address.Address;@@ -78,7 +77,7 @@ public class BinaryPropertyListAnalyzer extends FileFormatAnalyzer {monitor.checkCancelled();if (BinaryPropertyListUtil.isBinaryPropertyList(memory, block.getStart())) {ByteProvider provider =- new ImmutableMemoryRangeByteProvider(memory, block.getStart(), block.getEnd());+ new MemoryByteProvider(memory, block.getStart(), block.getEnd());markup(block.getStart(), provider, program, monitor);}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/ImmutableMemoryRangeByteProvider.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/ImmutableMemoryRangeByteProvider.javadeleted file mode 100644index 0470d6ec1b..0000000000--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/bplist/ImmutableMemoryRangeByteProvider.java+++ /dev/null@@ -1,104 +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.file.formats.bplist;--import java.io.*;--import ghidra.app.util.bin.ByteProvider;-import ghidra.program.model.address.Address;-import ghidra.program.model.mem.Memory;-import ghidra.program.model.mem.MemoryBlock;--class ImmutableMemoryRangeByteProvider implements ByteProvider {-- private Memory memory;- private Address start;- private Address end;-- ImmutableMemoryRangeByteProvider(Memory memory, Address start, Address end) {- this.memory = memory;- this.start = start;- this.end = end;- }-- @Override- public File getFile() {- throw new UnsupportedOperationException();- }-- @Override- public String getName() {- MemoryBlock block = memory.getBlock(start);- if (block != null) {- return block.getName();- }- return memory.getProgram().getName() + "_" + start.toString();- }-- @Override- public String getAbsolutePath() {- throw new UnsupportedOperationException();- }-- @Override- public long length() {- return end.subtract(start) + 1;- }-- @Override- public boolean isValidIndex(long index) {- Address indexAddress = start.add(index);- return start.compareTo(indexAddress) >= 0 && end.compareTo(indexAddress) <= 0;- }-- @Override- public void close() throws IOException {- // nothing to close- }-- @Override- public byte readByte(long index) throws IOException {- Address indexAddress = start.add(index);- try {- return memory.getByte(indexAddress);- }- catch (Exception e) {- throw new IOException(e.getMessage());- }- }-- @Override- public byte[] readBytes(long index, long length) throws IOException {- try {- byte[] bytes = new byte[(int) length];- Address indexAddress = start.add(index);- int nRead = memory.getBytes(indexAddress, bytes);- if (nRead != length) {- throw new IOException("Unable to read " + length + " bytes at index " + index);- }- return bytes;- }- catch (Exception e) {- throw new IOException(e.getMessage());- }- }-- @Override- public InputStream getInputStream(long index) throws IOException {- throw new UnsupportedOperationException();- }--}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/ProgramInsertByteProvider.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/ProgramInsertByteProvider.javaindex 82895c54b2..f61f6b50b9 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/ProgramInsertByteProvider.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/cmd/ProgramInsertByteProvider.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.@@ -64,7 +64,7 @@ public class ProgramInsertByteProvider implements ByteProvider {@Overridepublic boolean isValidIndex(long index) {- if (index < 0 || index > len) {+ if (!ByteProvider.super.isValidIndex(index)) {return false;}try {@@ -76,6 +76,23 @@ public class ProgramInsertByteProvider implements ByteProvider {}}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ if (!ByteProvider.super.isValidRange(startIndex, count)) {+ return false;+ }+ try {+ buffer.getByte((int) startIndex);+ if (count > 1) {+ buffer.getByte((int) (startIndex + count - 1));+ }+ return true;+ }+ catch (MemoryAccessException e) {+ return false;+ }+ }+@Overridepublic void close() throws IOException {// not applicablediff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheSlidProvider.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheSlidProvider.javaindex 9c37cff173..f3ba02ace0 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheSlidProvider.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheSlidProvider.java@@ -123,6 +123,11 @@ public class DyldCacheSlidProvider implements ByteProvider {return origProvider.isValidIndex(i);}+ @Override+ public boolean isValidRange(long startIndex, int count) {+ return origProvider.isValidRange(startIndex, count);+ }+@Overridepublic void close() throws IOException {// This is a wrapper, so don't close