From 34bb351b522e7331ee5c44b832f7b1a90205341a Mon Sep 17 00:00:00 2001 From: Arpit Jain Date: Mon, 28 Sep 2026 03:16:02 -0400 Subject: [PATCH] Stop reading past the end of the file in BinaryFileReader Signed-off-by: Arpit Jain --- .../portalmedia/embarc/cli/JsonWriterDpx.java | 4 ++++ .../embarc/parser/BinaryFileReader.java | 18 +++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/com/portalmedia/embarc/cli/JsonWriterDpx.java b/src/main/com/portalmedia/embarc/cli/JsonWriterDpx.java index 5b9013f..4a7f86a 100644 --- a/src/main/com/portalmedia/embarc/cli/JsonWriterDpx.java +++ b/src/main/com/portalmedia/embarc/cli/JsonWriterDpx.java @@ -37,6 +37,10 @@ public static void writeJsonDPXFiles(String outputPath, TreeMap metadata = data.getMetadataHashMap(); String currentSection = null; diff --git a/src/main/com/portalmedia/embarc/parser/BinaryFileReader.java b/src/main/com/portalmedia/embarc/parser/BinaryFileReader.java index 2a07239..3d01397 100644 --- a/src/main/com/portalmedia/embarc/parser/BinaryFileReader.java +++ b/src/main/com/portalmedia/embarc/parser/BinaryFileReader.java @@ -49,7 +49,7 @@ private void Initialize(String inputFilePath) throws FileNotFoundException public void skip(int position) { try { - inputStream.skip(position); + bytesRead += inputStream.skip(position); } catch (IOException e) { System.out.println("Error skipping to " + position); } @@ -66,7 +66,7 @@ public boolean hasMoreData() { } public boolean canRead(int length) { - return bytesRead + length < fileSizeBytes; + return length >= 0 && bytesRead + length <= fileSizeBytes; } public String readAscii(int length) { @@ -168,10 +168,22 @@ public Date readDate(String format, int length) { public byte[] readBytes(int length) throws IOException { + // The length often comes from a header field, so it can ask for more + // than the file holds. Reading anyway filled the array with the -1 + // returned at end of file, reported back as 0xFF bytes of content. + if (!canRead(length)) { + throw new IOException("Cannot read " + length + " bytes at offset " + + bytesRead + ", the file is " + fileSizeBytes + " bytes"); + } byte [] bytes = new byte[length]; for(int bp =0; bp < length; bp++) { - bytes[bp] = (byte) inputStream.read(); + int value = inputStream.read(); + if (value == -1) { + throw new IOException("Unexpected end of file after " + bp + + " of " + length + " bytes"); + } + bytes[bp] = (byte) value; bytesRead++; } return bytes;