undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 1998, 2024, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4129479 8342086
* @summary Test that available throws an IOException if the stream is
* closed, and that available works correctly with the NUL
* device on Windows
* @run junit Available
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.*;
public class Available {
@Test
void throwAfterClose() throws IOException {
File file = new File(System.getProperty("test.src", "."),
"Available.java");
FileInputStream fis = new FileInputStream(file);
fis.close();
assertThrows(IOException.class, () -> fis.available());
}
@Test
@EnabledOnOs(OS.WINDOWS)
void nulDevice() throws IOException {
File file = new File("nul");
FileInputStream fis = new FileInputStream(file);
int n = fis.available();
assertEquals(0, n, "available() returned non-zero value");
}
}

View file

@ -0,0 +1,128 @@
/*
* Copyright (c) 2010, 2017, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6402006 7030573 8011136
* @summary Test if available returns correct value when reading
* a large file.
* @run main/timeout=300 LargeFileAvailable
*/
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.*;
import java.util.concurrent.TimeUnit;
public class LargeFileAvailable {
public static void main(String args[]) throws Exception {
// Create a temporary file in the current directory.
// Use it to check if we have 7G available for
// a large sparse file test. As a fallback use whatever
// space is available, so the test can proceed.
File file = File.createTempFile("largefile", null, new File("."));
long spaceavailable = file.getUsableSpace();
long filesize = Math.min(spaceavailable, 7405576182L);
if (spaceavailable == 0L) {
// A full disk is considered fatal.
throw new RuntimeException("No space available for temp file.");
}
createLargeFile(filesize, file);
try (FileInputStream fis = new FileInputStream(file)) {
if (file.length() != filesize) {
throw new RuntimeException("unexpected file size = "
+ file.length());
}
long bigSkip = Math.min(filesize/2, 3110608882L);
long remaining = filesize;
remaining -= skipBytes(fis, bigSkip, remaining);
remaining -= skipBytes(fis, 10L, remaining);
remaining -= skipBytes(fis, bigSkip, remaining);
int expected = (remaining >= Integer.MAX_VALUE)
? Integer.MAX_VALUE
: (remaining > 0 ? (int) remaining : 0);
if (fis.available() != expected) {
throw new RuntimeException("available() returns "
+ fis.available() + " but expected " + expected);
}
} finally {
file.delete();
}
System.out.println("Test succeeded.");
System.out.flush();
}
// Skip toSkip number of bytes and expect that the available() method
// returns avail number of bytes.
private static long skipBytes(InputStream is, long toSkip, long avail)
throws IOException {
long skip = is.skip(toSkip);
if (skip != toSkip) {
throw new RuntimeException("skip() returns " + skip
+ " but expected " + toSkip);
}
long remaining = avail - skip;
int expected = (remaining >= Integer.MAX_VALUE)
? Integer.MAX_VALUE
: (remaining > 0 ? (int) remaining : 0);
System.out.println("Skipped " + skip + " bytes, available() returns "
+ expected + ", remaining " + remaining);
if (is.available() != expected) {
throw new RuntimeException("available() returns "
+ is.available() + " but expected " + expected);
}
return skip;
}
private static void createLargeFile(long filesize,
File file) throws Exception {
// Recreate a large file as a sparse file if possible
Files.delete(file.toPath());
try (FileChannel fc =
FileChannel.open(file.toPath(),
CREATE_NEW, WRITE, SPARSE)) {
ByteBuffer bb = ByteBuffer.allocate(1).put((byte)1);
bb.rewind();
System.out.println(" Writing large file...");
long t0 = System.nanoTime();
int rc = fc.write(bb, filesize - 1);
long t1 = System.nanoTime();
System.out.printf(" Wrote large file in %d ns (%d ms) %n",
t1 - t0, TimeUnit.NANOSECONDS.toMillis(t1 - t0));
if (rc != 1) {
throw new RuntimeException("Failed to write 1 byte"
+ " to the large file");
}
}
return;
}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2001, 2025, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4487368
* @summary Test, if FileInputStream can handle
* a leading slash in file name.
* @requires (os.family == "windows")
*/
import java.io.*;
public class LeadingSlash {
public static void main (String args[]) throws Exception {
File file = null;
try {
file = File.createTempFile("bug", "4487368");
new FileInputStream("\\" + file.getPath()).close();
new FileOutputStream("\\" + file.getPath()).close();
} finally {
if (file != null)
file.delete();
}
}
}

View file

@ -0,0 +1,98 @@
/*
* Copyright (c) 2013, 2024, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8010837 8011136
* @summary Test if available returns correct value when skipping beyond
* the end of a file.
* @author Dan Xu
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
public class NegativeAvailable {
public static void main(String[] args) throws IOException {
final int SIZE = 10;
final int SKIP = 5;
final int NEGATIVE_SKIP = -5;
// Create a temporary file with size of 10 bytes.
Path tmp = Files.createTempFile(null, null);
try {
try (BufferedWriter writer =
Files.newBufferedWriter(tmp, Charset.defaultCharset())) {
for (int i = 0; i < SIZE; i++) {
writer.write('1');
}
}
File tempFile = tmp.toFile();
try (FileInputStream fis = new FileInputStream(tempFile)) {
if (tempFile.length() != SIZE) {
throw new RuntimeException("unexpected file size = "
+ tempFile.length());
}
long space = skipBytes(fis, SKIP, SIZE);
space = skipBytes(fis, NEGATIVE_SKIP, space);
space = skipBytes(fis, SKIP, space);
space = skipBytes(fis, SKIP, space);
space = skipBytes(fis, SKIP, space);
space = skipBytes(fis, NEGATIVE_SKIP, space);
space = skipBytes(fis, NEGATIVE_SKIP, space);
}
} finally {
Files.deleteIfExists(tmp);
}
}
/**
* Skip toSkip number of bytes and return the remaining bytes of the file.
*/
private static long skipBytes(FileInputStream fis, int toSkip, long space)
throws IOException {
long skip = fis.skip(toSkip);
if (skip != toSkip) {
throw new RuntimeException("skip() returns " + skip
+ " but expected " + toSkip);
}
long newSpace = space - toSkip;
long remaining = newSpace > 0 ? newSpace : 0;
int avail = fis.available();
if (avail != remaining) {
throw new RuntimeException("available() returns " + avail
+ " but expected " + remaining);
}
System.out.println("Skipped " + skip + " bytes "
+ " available() returns " + avail);
return newSpace;
}
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 1998, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4092350
* @summary Attempting to open a stream on a directory should fail on
* all platforms.
*
*/
import java.io.*;
public class OpenDir {
public static void main(String args[]) throws Exception {
// Perform the same test for FileInputStream, FileOutputStream
// and RandomAccessFile.
FileInputStream fs = null;
// This test attempts to FileInputStream.open(".")
// This should fail since . is a directory.
try {
fs = new FileInputStream(".");
throw new
Exception("FileInputStream.open should not work on dirs");
} catch (IOException e) {
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(".");
throw new
Exception("FileOutputStream.open should'nt work on dirs");
} catch (IOException e) {
}
RandomAccessFile ras = null;
try {
ras = new RandomAccessFile(".","r");
throw new
Exception("RandomAccessFile.open should'nt work on dirs");
} catch (IOException e) {
}
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 2007, 2013, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6359397
* @summary Test if FileInputStream methods will check if the stream
* has been closed.
*/
import java.io.*;
public enum OpsAfterClose {
READ { boolean check(FileInputStream r) {
try {
r.read();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_BUF { boolean check(FileInputStream r) {
try {
byte buf[] = new byte[2];
r.read(buf);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_BUF_OFF { boolean check(FileInputStream r) {
try {
byte buf[] = new byte[2];
int len = 1;
r.read(buf, 0, len);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
GET_CHANNEL { boolean check(FileInputStream r) {
r.getChannel();
return true;
} },
GET_FD { boolean check(FileInputStream r) {
try {
r.getFD();
return true;
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return false;
}
} },
SKIP { boolean check(FileInputStream r) {
try {
r.skip(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
CLOSE { boolean check(FileInputStream r) {
try {
r.close();
return true; // No Exception thrown on windows
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true; // Exception thrown on solaris and linux
}
} };
abstract boolean check(FileInputStream r);
public static void main(String args[]) throws Exception {
boolean failed = false;
File f = new File(System.getProperty("test.dir", "."),
"f.txt");
f.createNewFile();
f.deleteOnExit();
FileInputStream fis = new FileInputStream(f);
if (testFileInputStream(fis)) {
throw new Exception("Test failed for some of the operation{s}" +
" on FileInputStream, check the messages");
}
}
private static boolean testFileInputStream(FileInputStream r)
throws Exception {
r.close();
boolean failed = false;
boolean result;
System.out.println("Testing File:" + r);
for (OpsAfterClose op : OpsAfterClose.values()) {
result = op.check(r);
if (!result) {
failed = true;
}
System.out.println(op + ":" + result);
}
if (failed) {
System.out.println("Test failed for the failed operation{s}" +
" above for the FileInputStream:" + r);
}
return failed;
}
}

View file

@ -0,0 +1,210 @@
/*
* Copyright (c) 2024, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8341666
* @summary Test of FileInputStream reading from stdin and a named pipe
* @requires os.family != "windows"
* @library .. /test/lib
* @build jdk.test.lib.Platform
* @run junit/othervm --enable-native-access=ALL-UNNAMED PseudoDevice
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import jdk.test.lib.Platform;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.*;
public class PseudoDevice {
private static final String PIPE = "pipe";
private static final File PIPE_FILE = new File(PIPE);
private static final String SENTENCE =
"Rien n'est permis mais tout est possible";
private static class mkfifo {
public static final FunctionDescriptor DESC = FunctionDescriptor.of(
ValueLayout.JAVA_INT,
ValueLayout.ADDRESS,
ValueLayout.JAVA_SHORT
);
public static final MemorySegment ADDR;
static {
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
ADDR = stdlib.find("mkfifo").orElseThrow();
}
public static final MethodHandle HANDLE =
Linker.nativeLinker().downcallHandle(ADDR, DESC);
}
public static int mkfifo(MemorySegment x0, short x1) {
var mh$ = mkfifo.HANDLE;
try {
return (int)mh$.invokeExact(x0, x1);
} catch (Throwable ex$) {
throw new AssertionError("should not reach here", ex$);
}
}
private static Thread createWriteThread() {
Thread t = new Thread(
new Runnable() {
public void run() {
try (FileOutputStream fos = new FileOutputStream(PIPE);) {
fos.write(SENTENCE.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
);
t.start();
return t;
}
@BeforeAll
static void before() throws InterruptedException, IOException {
if (Platform.isWindows())
return;
PIPE_FILE.delete();
try (var newArena = Arena.ofConfined()) {
var addr = newArena.allocateFrom(PIPE);
short mode = 0666;
assertEquals(0, mkfifo(addr, mode));
}
if (!PIPE_FILE.exists())
throw new RuntimeException("Failed to create " + PIPE);
}
@AfterAll
static void after() throws IOException {
if (Platform.isWindows())
return;
PIPE_FILE.delete();
}
/**
* Tests that new FileInputStream(File).available() does not throw
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void availableStdin() throws IOException {
File stdin = new File("/dev", "stdin");
if (stdin.exists()) {
try (InputStream s = new FileInputStream(stdin);) {
s.available();
}
}
}
/**
* Tests that new FileInputStream(File).skip(0) does not throw
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void skipStdin() throws IOException {
File stdin = new File("/dev", "stdin");
if (stdin.exists()) {
try (InputStream s = new FileInputStream(stdin);) {
s.skip(0);
}
}
}
/**
* Tests new FileInputStream(File).readAllBytes().
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void readAllBytes() throws InterruptedException, IOException {
Thread t = createWriteThread();
try (InputStream in = new FileInputStream(PIPE)) {
String s = new String(in.readAllBytes());
System.out.println(s);
assertEquals(SENTENCE, s);
} finally {
t.join();
}
}
/**
* Tests new FileInputStream(File).readNBytes(byte[],int,int).
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void readNBytesNoOverride() throws InterruptedException, IOException {
Thread t = createWriteThread();
try (InputStream in = new FileInputStream(PIPE)) {
final int offset = 11;
final int length = 17;
assert length <= SENTENCE.length();
byte[] b = new byte[offset + length];
int n = in.readNBytes(b, offset, length);
String s = new String(b, offset, length);
System.out.println(s);
assertEquals(SENTENCE.substring(0, length), s);
} finally {
t.join();
}
}
/**
* Tests new FileInputStream(File).readNBytes(int).
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void readNBytesOverride() throws InterruptedException, IOException {
Thread t = createWriteThread();
try (InputStream in = new FileInputStream(PIPE)) {
final int length = 17;
assert length <= SENTENCE.length();
byte[] b = in.readNBytes(length);
String s = new String(b);
System.out.println(s);
assertEquals(SENTENCE.substring(0, length), s);
} finally {
t.join();
}
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2021, 2024, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main ReadXBytes
* @bug 8264777
* @summary Test read{All,N}Bytes overrides (use -Dseed=X to set PRNG seed)
* @key randomness
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Random;
import jdk.test.lib.RandomFactory;
public class ReadXBytes {
private static final int ITERATIONS = 10;
private static final int MAX_FILE_SIZE = 1_000_000;
private static final Random RND = RandomFactory.getRandom();
public static void main(String args[]) throws IOException {
File dir = new File(".");
dir.deleteOnExit();
File empty = File.createTempFile("foo", "bar", dir);
empty.deleteOnExit();
try (FileInputStream fis = new FileInputStream(empty)) {
try {
fis.readNBytes(-1);
throw new RuntimeException("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
byte[] nbytes = fis.readNBytes(0);
if (nbytes.length != 0)
throw new RuntimeException("readNBytes() zero length for empty");
byte[] b = fis.readNBytes(1);
if (b.length != 0)
throw new RuntimeException("readNBytes: zero-length byte[] expected");
b = fis.readAllBytes();
if (b.length != 0)
throw new RuntimeException("readAllBytes: zero-length byte[] expected");
}
for (int i = 0; i < ITERATIONS; i++) {
File file = File.createTempFile("foo", "bar", dir);
file.deleteOnExit();
int size = 1 + RND.nextInt(MAX_FILE_SIZE);
System.out.printf("size %d%n", size);
byte[] bytes = new byte[size];
RND.nextBytes(bytes);
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
raf.write(bytes);
}
try (FileInputStream fis = new FileInputStream(file)) {
int pos = RND.nextInt(size);
int len = RND.nextInt(size - pos);
fis.getChannel().position(pos);
byte[] nbytes = fis.readNBytes(0);
if (nbytes.length != 0)
throw new RuntimeException("readNBytes() zero length");
nbytes = fis.readNBytes(len);
if (nbytes.length != len)
throw new RuntimeException("readNBytes() length");
if (!Arrays.equals(nbytes, 0, len, bytes, pos, pos + len))
throw new RuntimeException("readNBytes() content");
}
try (FileInputStream fis = new FileInputStream(file)) {
int pos = RND.nextInt(size);
fis.getChannel().position(pos);
byte[] allbytes = fis.readAllBytes();
if (allbytes.length != size - pos)
throw new RuntimeException("readAllBytes() length");
if (!Arrays.equals(allbytes, 0, allbytes.length,
bytes, pos, pos + allbytes.length))
throw new RuntimeException("readAllBytes() content");
}
file.delete();
}
dir.delete();
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main TransferTo
* @bug 8272297
* @summary Test FileInputStream.transferTo(FileOutputStream)
* @key randomness
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Random;
import jdk.test.lib.RandomFactory;
public class TransferTo {
private static int MIN_SIZE = 10_000;
private static int MAX_SIZE_INCR = 100_000_000 - MIN_SIZE;
private static int ITERATIONS = 10;
private static final Random RND = RandomFactory.getRandom();
public static void main(String[] args) throws IOException {
File dir = new File(".");
File in = File.createTempFile("src", ".dat", dir);
in.deleteOnExit();
int length = MIN_SIZE + RND.nextInt(MAX_SIZE_INCR);
byte[] bytes = new byte[length];
try (RandomAccessFile rafi = new RandomAccessFile(in, "rw")) {
rafi.write(bytes);
}
File out = File.createTempFile("dst", ".dat", dir);
out.deleteOnExit();
for (int i = 0; i < ITERATIONS; i++) {
int posIn = RND.nextInt(length);
int posOut = RND.nextInt(MIN_SIZE);
try (RandomAccessFile rafo = new RandomAccessFile(out, "rw")) {
rafo.setLength(posOut);
}
test(in, posIn, out, posOut);
out.delete();
out = File.createTempFile("dst", ".dat", dir);
out.deleteOnExit();
}
}
private static void test(File in, int posIn, File out, int posOut)
throws IOException {
try (FileInputStream fis = new FileInputStream(in)) {
try (FileChannel fci = fis.getChannel()) {
fci.position(posIn);
long size = fci.size();
long length = size - posIn;
int count = Math.toIntExact(length);
try (FileOutputStream fos = new FileOutputStream(out)) {
try (FileChannel fco = fos.getChannel()) {
fco.position(posOut);
long transferred = fis.transferTo(fos);
if (transferred != count)
fail(posIn, size, posOut,
"Transferred " + transferred +
", expected " + count);
if (fci.position() != posIn + count)
fail(posIn, size, posOut,
"Input position " + fci.position() +
", expected " + posIn + count);
if (fco.position() != posOut + count)
fail(posIn, size, posOut,
"Output position " + fco.position() +
", expected " + posOut + count);
byte[] bytesIn = Files.readAllBytes(in.toPath());
byte[] bytesOut = Files.readAllBytes(out.toPath());
if (!Arrays.equals(bytesIn, posIn, posIn + count,
bytesOut, posOut, posOut + count))
fail(posIn, size, posOut, "Contents unequal");
}
}
}
}
}
private static void fail(int posIn, long size, int posOut,
String msg) {
System.out.printf("Failure for posIn %s, size %d, posOut %d%n",
posIn, size, posOut);
throw new RuntimeException(msg);
}
}

View file

@ -0,0 +1,242 @@
/*
* Copyright (c) 2007, 2025, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @test
* @modules java.base/java.io:open
* @library /test/lib
* @build jdk.test.lib.util.FileUtils UnreferencedFISClosesFd
* @bug 6524062
* @summary Test to ensure that FIS.finalize() invokes the close() method as per
* the specification.
* @run main/othervm/timeout=480 UnreferencedFISClosesFd
*/
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.management.UnixOperatingSystemMXBean;
import jdk.test.lib.util.FileUtils;
/**
* Tests for FIS unreferenced.
* - Not subclassed - cleaner cleanup
* - Subclassed no finalize or close - cleaner cleanup
* - Subclassed close overridden - AltFinalizer cleanup
* - Subclasses finalize overridden - cleaner cleanup
* - Subclasses finalize and close overridden - AltFinalizer cleanup
*/
public class UnreferencedFISClosesFd {
static final String FILE_NAME = "empty.txt";
/**
* Subclass w/ no overrides; not finalize or close.
* Cleanup should be via the Cleaner.
*/
public static class StreamOverrides extends FileInputStream {
protected final AtomicInteger closeCounter;
public StreamOverrides(String name) throws FileNotFoundException {
super(name);
closeCounter = new AtomicInteger(0);
}
final AtomicInteger closeCounter() {
return closeCounter;
}
}
/**
* Subclass overrides close.
* Cleanup should be via the Cleaner.
*/
public static class StreamOverridesClose extends StreamOverrides {
public StreamOverridesClose(String name) throws FileNotFoundException {
super(name);
}
public void close() throws IOException {
closeCounter.incrementAndGet();
super.close();
}
}
/**
* Subclass overrides finalize.
* Cleanup should be via the Cleaner.
*/
public static class StreamOverridesFinalize extends StreamOverrides {
public StreamOverridesFinalize(String name) throws FileNotFoundException {
super(name);
}
@SuppressWarnings({"deprecation","removal"})
protected void finalize() throws IOException, Throwable {
super.finalize();
}
}
/**
* Subclass overrides finalize and close.
* Cleanup should be via AltFinalizer calling close().
*/
public static class StreamOverridesFinalizeClose extends StreamOverridesClose {
public StreamOverridesFinalizeClose(String name) throws FileNotFoundException {
super(name);
}
@SuppressWarnings({"deprecation","removal"})
protected void finalize() throws IOException, Throwable {
super.finalize();
}
}
/**
* Main runs each test case and reports number of failures.
*/
public static void main(String argv[]) throws Exception {
File inFile = new File(System.getProperty("test.dir", "."), FILE_NAME);
inFile.createNewFile();
inFile.deleteOnExit();
String name = inFile.getPath();
FileUtils.listFileDescriptors(System.out);
long fdCount0 = getFdCount();
int failCount = 0;
failCount += test(new FileInputStream(name));
failCount += test(new StreamOverrides(name));
failCount += test(new StreamOverridesClose(name));
failCount += test(new StreamOverridesFinalize(name));
failCount += test(new StreamOverridesFinalizeClose(name));
if (failCount > 0) {
throw new AssertionError("Failed test count: " + failCount);
}
// Check the final count of open file descriptors
long fdCount = getFdCount();
if (fdCount != fdCount0) {
System.out.printf("initial count of open file descriptors: %d%n", fdCount0);
System.out.printf("final count of open file descriptors: %d%n", fdCount);
FileUtils.listFileDescriptors(System.out);
}
}
// Get the count of open file descriptors, or -1 if not available
private static long getFdCount() {
OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
return (mxBean instanceof UnixOperatingSystemMXBean)
? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount()
: -1L;
}
private static int test(FileInputStream fis) throws Exception {
try {
System.out.printf("%nTesting %s%n", fis.getClass().getName());
// Prepare to wait for FIS to be reclaimed
ReferenceQueue<Object> queue = new ReferenceQueue<>();
HashSet<Reference<?>> pending = new HashSet<>();
WeakReference<FileInputStream> msWeak = new WeakReference<>(fis, queue);
pending.add(msWeak);
FileDescriptor fd = fis.getFD();
WeakReference<FileDescriptor> fdWeak = new WeakReference<>(fd, queue);
pending.add(fdWeak);
Field fdField = FileDescriptor.class.getDeclaredField("fd");
fdField.setAccessible(true);
int ffd = fdField.getInt(fd);
Field cleanupField = FileDescriptor.class.getDeclaredField("cleanup");
cleanupField.setAccessible(true);
Object cleanup = cleanupField.get(fd);
System.out.printf(" cleanup: %s, ffd: %d, cf: %s%n", cleanup, ffd, cleanupField);
if (cleanup == null) {
throw new RuntimeException("cleanup should not be null");
}
WeakReference<Object> cleanupWeak = new WeakReference<>(cleanup, queue);
pending.add(cleanupWeak);
System.out.printf(" fdWeak: %s%n msWeak: %s%n cleanupWeak: %s%n",
fdWeak, msWeak, cleanupWeak);
AtomicInteger closeCounter = fis instanceof StreamOverrides
? ((StreamOverrides)fis).closeCounter() : null;
Reference<?> r;
while (((r = queue.remove(1000L)) != null)
|| !pending.isEmpty()) {
System.out.printf(" r: %s, pending: %d%n",
r, pending.size());
if (r != null) {
pending.remove(r);
} else {
fis = null;
fd = null;
cleanup = null;
System.gc(); // attempt to reclaim them
}
}
Reference.reachabilityFence(fd);
Reference.reachabilityFence(fis);
Reference.reachabilityFence(cleanup);
// Confirm the correct number of calls to close depending on the cleanup type
if (closeCounter != null && closeCounter.get() > 0) {
throw new RuntimeException("Close should not have been called: count: " + closeCounter);
}
} catch (Exception ex) {
ex.printStackTrace(System.out);
return 1;
}
return 0;
}
}