8272255: Completely handle MIDI files
Reviewed-by: mbaesken
Backport-of: 6efdd1870e7ddb77a04d8c8183ced385039d0913
diff --git a/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java b/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java
index de9d124..eac3037 100644
--- a/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java
+++ b/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -78,12 +78,26 @@
public Soundbank getSoundbank(AudioInputStream ais)
throws InvalidMidiDataException, IOException {
+ int MEGABYTE = 1048576;
+ int DEFAULT_BUFFER_SIZE = 65536;
+ int MAX_FRAME_SIZE = 1024;
try {
byte[] buffer;
- if (ais.getFrameLength() == -1) {
+ int frameSize = ais.getFormat().getFrameSize();
+ if (frameSize <= 0 || frameSize > MAX_FRAME_SIZE) {
+ throw new InvalidMidiDataException("Formats with frame size "
+ + frameSize + " are not supported");
+ }
+
+ long totalSize = ais.getFrameLength() * frameSize;
+ if (totalSize >= Integer.MAX_VALUE - 2) {
+ throw new InvalidMidiDataException(
+ "Can not allocate enough memory to read audio data.");
+ }
+
+ if (ais.getFrameLength() == -1 || totalSize > MEGABYTE) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buff = new byte[1024
- - (1024 % ais.getFormat().getFrameSize())];
+ byte[] buff = new byte[DEFAULT_BUFFER_SIZE - (DEFAULT_BUFFER_SIZE % frameSize)];
int ret;
while ((ret = ais.read(buff)) != -1) {
baos.write(buff, 0, ret);
@@ -91,8 +105,7 @@
ais.close();
buffer = baos.toByteArray();
} else {
- buffer = new byte[(int) (ais.getFrameLength()
- * ais.getFormat().getFrameSize())];
+ buffer = new byte[(int) totalSize];
new DataInputStream(ais).readFully(buffer);
}
ModelByteBufferWavetable osc = new ModelByteBufferWavetable(