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,43 @@
/*
* Copyright (c) 2002, 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 4710771
* @summary Test RandomAccessFile.close
*/
import java.io.*;
import java.nio.channels.*;
public class Close {
public static void main(String[] args) throws Exception {
File f = File.createTempFile("blah", null);
f.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(f, "r");
FileChannel channel = raf.getChannel();
raf.close();
if (channel.isOpen()) {
throw new RuntimeException("Channel not closed");
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 1997, 2010, 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 4017497
@summary Check that read returns -1 on EOF, as specified
*/
import java.io.*;
public class EOF {
public static void main(String[] args) throws IOException {
byte buf[] = new byte[100];
int n;
String dir = System.getProperty("test.src", ".");
RandomAccessFile raf = new RandomAccessFile(new File(dir, "EOF.java"), "r");
try {
for (;;) {
n = raf.read(buf, 0, buf.length);
if (n <= 0) break;
}
if (n != -1)
throw new RuntimeException("Expected -1 for EOF, got " + n);
} finally {
raf.close();
}
}
}

View file

@ -0,0 +1,137 @@
/*
* Copyright (c) 2015, 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 4823133
* @summary optimize RandomAccessFile.length() and length() is thread safe now.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* @author vyom.tewari@oracle.com
*/
public class FileLengthTest {
private static final int BUF_SIZE = 4096;
private static RandomAccessFile randomAccessFile;
private static Thread fileLengthCaller;
private static Thread fileContentReader;
private static StringBuilder fileContents;
private static volatile boolean isFailed = false;
/**
* this thread will call length() in loop
*/
private static void startLengthThread() {
if (randomAccessFile == null) {
return;
}
fileLengthCaller = new Thread(() -> {
while (true) {
try {
long length = randomAccessFile.length();
if (length < 0) {
return;
}
} catch (IOException ex) {
return;
}
}
});
fileLengthCaller.setName("RandomAccessFile-length-caller");
fileLengthCaller.setDaemon(true);
fileLengthCaller.start();
}
/**
* this thread will call read() and store the content in internal buffer.
*/
private static void startReaderThread() {
if (randomAccessFile == null) {
return;
}
fileContentReader = new Thread(() -> {
StringBuilder sb = new StringBuilder(BUF_SIZE);
int i;
byte arr[] = new byte[8];
try {
while ((i = randomAccessFile.read(arr)) != -1) {
sb.append(new String(arr, 0, i));
}
if (!sb.toString().equals(fileContents.toString())) {
isFailed = true;
}
} catch (IOException ex) {
}
});
fileContentReader.setName("RandomAccessFile-content-reader");
fileContentReader.setDaemon(true);
fileContentReader.start();
}
public static void main(String args[]) {
byte arr[] = new byte[BUF_SIZE];
String testFile = "testfile.txt";
try {
createDummyFile(testFile);
File file = new File(testFile);
file.deleteOnExit();
randomAccessFile = new RandomAccessFile(file, "r");
int count = randomAccessFile.read(arr);
randomAccessFile.seek(0);
fileContents = new StringBuilder(BUF_SIZE);
fileContents.append(new String(arr, 0, count));
startLengthThread();
startReaderThread();
fileContentReader.join();
} catch (FileNotFoundException | InterruptedException ex) {
} catch (IOException ex) {
} finally {
try {
randomAccessFile.close();
} catch (IOException ex) {
}
}
if (isFailed) {
throw new RuntimeException("RandomAccessFile.length() changed the underlying file pointer.");
}
}
private static void createDummyFile(String fileName) throws FileNotFoundException, IOException {
try (FileOutputStream outputStream = new FileOutputStream(new File(fileName))) {
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int count = 0;
while ((count + str.length()) < BUF_SIZE) {
outputStream.write(str.getBytes());
count += str.length();
}
outputStream.flush();
}
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, 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
* @summary Unit test for RandomAccessFile open-sync modes
*/
import java.io.*;
public class OpenSync {
static PrintStream log = System.err;
public static void main(String[] args) throws Exception {
File blah = File.createTempFile("OpenSync", null);
blah.deleteOnExit();
String[] badModes = { "d", "s", "rd", "rs", "rwx", "foo" };
for (int i = 0; i < badModes.length; i++) {
String mode = badModes[i];
try {
new RandomAccessFile(blah, mode);
} catch (IllegalArgumentException x) {
log.println("Mode \"" + mode +"\": Thrown as expected: "
+ x.getClass().getName());
log.println(" " + x.getMessage());
continue;
}
throw new Exception("Exception not thrown for illegal mode "
+ mode);
}
new RandomAccessFile(blah, "rw").close();
new RandomAccessFile(blah, "r").close();
String hi = "Hello, world!";
RandomAccessFile raf = new RandomAccessFile(blah, "rws");
raf.writeUTF(hi);
raf.close();
raf = new RandomAccessFile(blah, "rwd");
if (!raf.readUTF().equals(hi))
throw new Exception("File content mismatch");
raf.close();
}
}

View file

@ -0,0 +1,181 @@
/*
* 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 RandomAccessFile methods will check if the stream
* has been closed.
*/
import java.io.*;
public enum OpsAfterClose {
READ { boolean check(RandomAccessFile r) {
try {
r.read();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_BUF { boolean check(RandomAccessFile 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(RandomAccessFile r) {
r.getChannel();
return true;
} },
GET_FD { boolean check(RandomAccessFile r) {
try {
r.getFD();
return true;
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return false;
}
} },
GET_FILE_PTR { boolean check(RandomAccessFile r) {
try {
r.getFilePointer();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
GET_LENGTH { boolean check(RandomAccessFile r) {
try {
r.length();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
SEEK { boolean check(RandomAccessFile r) {
try {
r.seek(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
SET_LENGTH { boolean check(RandomAccessFile r) {
try {
r.setLength(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
SKIP_BYTES { boolean check(RandomAccessFile r) {
try {
r.skipBytes(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
WRITE { boolean check(RandomAccessFile r) {
try {
r.write(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
WRITE_BUF { boolean check(RandomAccessFile r) {
try {
byte buf[] = new byte[2];
int len = 1;
r.write(buf, 0, len);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
CLOSE { boolean check(RandomAccessFile 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(RandomAccessFile r);
public static void main(String args[]) throws Exception {
boolean failed = false;
File f = new File(System.getProperty("test.dir", "."),
"raf.txt");
f.createNewFile();
f.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(f, "rw");
if (testRandomAccessFile(raf)) {
throw new Exception("Test failed for some of the operation{s}" +
" on RandomAccessFile, check the messages");
}
}
private static boolean testRandomAccessFile(RandomAccessFile 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 RandomAccessFile:" + r);
}
return failed;
}
}

View file

@ -0,0 +1,159 @@
/*
* Copyright (c) 1997, 2010, 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 4030253 4030278 4030243
@summary Test for correct parameter checking in read(byte[], int, int),
readFully(byte[], int, int) and write(byte[], int, int) of RandomAccessFile
*/
import java.io.*;
public class ParameterCheck {
static int off[] = {-1, -1, 0, 0, 33, 33, 0, 32,
32, 4, 1, 0, -1, Integer.MAX_VALUE, 1};
static int len[] = {-1, 0, -1, 33, 0, 4, 32,
0, 4, 16, 31, 0, Integer.MAX_VALUE,
Integer.MAX_VALUE, Integer.MAX_VALUE};
static boolean results[] = { false, false, false, false, false, false,
true, true, false, true, true, true, false,
false, false };
static int numBad = 0;
private static void doTest(String method) throws Exception {
File fn = new File("x.ParameterCheck");
RandomAccessFile raf = null;
try {
byte b[] = new byte[32];
int numCases = off.length;
int[] got = new int[numCases];
int numGood = 0;
FileOutputStream fout = new FileOutputStream(fn);
for (int i = 0; i < 32; i++) {
fout.write(i);
}
fout.close();
raf = new RandomAccessFile(fn , "rw");
System.err.println("-----------------------------" +
"-----------------------------");
System.err.println("\nRandomAccessFile." + method +
"\nTotal test cases = " + (off.length+1));
System.err.println("-----------------------------" +
"-----------------------------");
for(int i = 0; i < numCases; i++) {
try {
if (method.equals("readFully")) {
raf.readFully(b , off[i] , len[i]);
}
if (method.equals("read")) {
raf.read(b , off[i] , len[i]);
}
if (method.equals("write")) {
raf.write(b , off[i] , len[i]);
}
raf.seek(0);
} catch(IndexOutOfBoundsException aiobe) {
if (results[i]) {
printErr(method , numGood,
i, "java.lang.IndexOutOfBoundsException");
} else {
numGood++;
}
continue;
} catch(OutOfMemoryError ome) {
printErr(method, numGood,
i, "java.lang.OutOfMemoryError");
continue;
}
if (results[i]) {
numGood++;
}
else {
printErr(method, numGood,
i, "No java.lang.IndexOutOfBoundsException");
}
}
raf.seek(0);
boolean thrown = false;
try {
if (method.equals("readFully")) {
raf.readFully(null, 1, 2);
}
if (method.equals("read")) {
raf.read(null, 1, 2);
}
if (method.equals("write")) {
raf.write(null, 1, 2);
}
} catch(NullPointerException npe) {
numGood++;
thrown = true;
}
if (!thrown) {
printErr(method, numGood, -1,
"no NullPointerException for null b");
}
System.err.println("\nTotal passed = " + numGood);
System.err.println("-----------------------------" +
"-----------------------------");
} finally {
if (raf != null)
raf.close();
fn.delete();
}
}
private static void printErr(String method, int numGood,
int i, String expStr) {
numBad++;
System.err.println("\nNumber passed so far = " + numGood +
"\nUnexpected " + expStr);
if ( i < 0 ) {
System.err.println("for case : b = null");
} else {
System.err.println("for case : b.length = " + 32 +
" off = " + off[i] +
" len = " + len[i]);
}
}
public static void main(String argv[]) throws Exception{
doTest("read");
doTest("readFully");
doTest("write");
if (numBad > 0) {
throw new RuntimeException("Failed " + numBad + " tests");
}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 1997, 2010, 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 1238814
@summary check for correct implementation of RandomAccessFile.readLine
*/
import java.io.*;
public class ReadLine {
public static void main(String args[]) throws Exception {
File fn = new File("x.ReadLine");
RandomAccessFile raf = new RandomAccessFile(fn,"rw");
try {
String line;
int ctr = 1;
String expected;
raf.writeBytes
("ln1\rln2\r\nln3\nln4\rln5\r\nln6\n\rln8\r\rln10\n\nln12\r\r\nln14");
raf.seek(0);
while ((line=raf.readLine()) != null) {
if ((ctr == 7) || (ctr == 9) ||
(ctr == 11) || (ctr == 13)) {
expected = "";
} else {
expected = "ln" + ctr;
}
if (!line.equals(expected)) {
throw new Exception("Expected \"" + expected + "\"" +
", read \"" + line + "\"");
}
ctr++;
}
} finally {
raf.close();
}
System.err.println("Successfully completed test!");
}
}

View file

@ -0,0 +1,152 @@
/*
* 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 Verify that reads and writes of primitives are correct
*/
// The bug mentioned is actually a performance bug that prompted
// changes in the methods to write primitives
import java.io.*;
import java.io.*;
public class ReadWritePrimitives {
public static void main(String args[]) throws IOException {
long start, finish;
start = System.currentTimeMillis();
testShort();
finish = System.currentTimeMillis();
// System.err.println("Time taken="+(finish-start));
start = System.currentTimeMillis();
testChar();
finish = System.currentTimeMillis();
// System.err.println("Time taken="+(finish-start));
start = System.currentTimeMillis();
testInt();
finish = System.currentTimeMillis();
// System.err.println("Time taken="+(finish-start));
start = System.currentTimeMillis();
testLong();
finish = System.currentTimeMillis();
// System.err.println("Time taken="+(finish-start));
}
private static void testShort() throws IOException {
File fh = new File(System.getProperty("test.dir", "."),
"x.ReadWriteGenerated");
RandomAccessFile f = new RandomAccessFile(fh,"rw");
for(int i = 0; i < 10000; i++){
f.writeShort((short)i);
}
f.writeShort((short)65535);
f.close();
f = new RandomAccessFile(fh,"r");
for(int i = 0; i < 10000; i++) {
short r = f.readShort();
if (r != ((short)i)) {
System.err.println("An error occurred. Read:" + r
+ " i:" + ((short)i));
throw new IOException("Bad read from a writeShort");
}
}
short rmax = f.readShort();
if (rmax != ((short)65535)) {
System.err.println("An error occurred. Read:" + rmax);
throw new IOException("Bad read from a writeShort");
}
f.close();
}
private static void testChar() throws IOException {
File fh = new File(System.getProperty("test.dir", "."),
"x.ReadWriteGenerated");
RandomAccessFile f = new RandomAccessFile(fh,"rw");
for(int i = 0; i < 10000; i++){
f.writeChar((char)i);
}
f.close();
f = new RandomAccessFile(fh,"r");
for(int i = 0; i < 10000; i++) {
char r = f.readChar();
if (r != ((char)i)){
System.err.println("An error occurred. Read:" + r
+ " i:" + ((char) i));
throw new IOException("Bad read from a writeChar");
}
}
f.close();
}
private static void testInt() throws IOException {
File fh = new File(System.getProperty("test.dir", "."),
"x.ReadWriteGenerated");
RandomAccessFile f = new RandomAccessFile(fh,"rw");
for(int i = 0; i < 10000; i++){
f.writeInt((short)i);
}
f.writeInt(Integer.MAX_VALUE);
f.close();
f = new RandomAccessFile(fh, "r");
for(int i = 0; i < 10000; i++) {
int r = f.readInt();
if (r != i){
System.err.println("An error occurred. Read:" + r
+ " i:" + i);
throw new IOException("Bad read from a writeInt");
}
}
int rmax = f.readInt();
if (rmax != Integer.MAX_VALUE){
System.err.println("An error occurred. Read:" + rmax);
throw new IOException("Bad read from a writeInt");
}
f.close();
}
private static void testLong() throws IOException {
File fh = new File(System.getProperty("test.dir", "."),
"x.ReadWriteGenerated");
RandomAccessFile f = new RandomAccessFile(fh,"rw");
for(int i = 0; i < 10000; i++){
f.writeLong(123456789L * (long)i);
}
f.close();
f = new RandomAccessFile(fh,"r");
for(int i = 0; i < 10000; i++){
long r = f.readLong();
if (r != (((long) i) * 123456789L) ) {
System.err.println("An error occurred. Read:" + r
+ " i" + ((long) i));
throw new IOException("Bad read from a writeInt");
}
}
f.close();
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 1998, 2010, 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 4140804
@summary Test if seek will throw exception given a
negative offset.
*/
import java.io.*;
public class Seek
{
public static void main(String argv[]) throws Exception
{
String dir = System.getProperty("test.src", ".");
RandomAccessFile raf = new RandomAccessFile
(new File(dir, "Seek.java"), "r");
try {
raf.seek(-10);
throw new Exception
("Should have thrown an IOException when seek offset is < 0");
} catch (IOException e) {
} finally {
raf.close();
}
}
}

View file

@ -0,0 +1,165 @@
/*
* Copyright (c) 1997, 2018, 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 8204310
* @summary General tests of the setLength method
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main SetLength
* @key randomness
*/
import java.io.IOException;
import java.io.File;
import java.io.RandomAccessFile;
import jdk.test.lib.RandomFactory;
public class SetLength {
static void checkState(RandomAccessFile f, long expectedFilePointer,
long expectedLength)
throws IOException
{
long filePointer = f.getFilePointer();
long length = f.length();
if (length != expectedLength) {
throw new RuntimeException("File length " + length + " != expected "
+ expectedLength);
}
if (filePointer != expectedFilePointer) {
throw new RuntimeException("File pointer " + filePointer
+ " != expected " + expectedFilePointer);
}
}
static void test(RandomAccessFile f, long quarterLength)
throws IOException
{
long halfLength = 2 * quarterLength;
long threeQuarterLength = 3 * quarterLength;
long fullLength = 4 * quarterLength;
// initially, empty file
checkState(f, 0, 0);
// extending the file size
f.setLength(halfLength);
checkState(f, 0, halfLength);
// writing from the begining
f.write(new byte[(int)fullLength]);
checkState(f, fullLength, fullLength);
// setting to the same length
f.setLength(fullLength);
checkState(f, fullLength, fullLength);
// truncating the file
f.setLength(threeQuarterLength);
checkState(f, threeQuarterLength, threeQuarterLength);
// changing the file pointer
f.seek(quarterLength);
checkState(f, quarterLength, threeQuarterLength);
// truncating the file again
f.setLength(halfLength);
checkState(f, quarterLength, halfLength);
// writing from the middle with extending the file
f.write(new byte[(int)halfLength]);
checkState(f, threeQuarterLength, threeQuarterLength);
// changing the file pointer
f.seek(quarterLength);
checkState(f, quarterLength, threeQuarterLength);
// writing from the middle without extending the file
f.write(new byte[(int)quarterLength]);
checkState(f, halfLength, threeQuarterLength);
// changing the file pointer to the end of file
f.seek(threeQuarterLength);
checkState(f, threeQuarterLength, threeQuarterLength);
// writing to the end of file
f.write(new byte[(int)quarterLength]);
checkState(f, fullLength, fullLength);
// truncating the file to zero
f.setLength(0);
checkState(f, 0, 0);
// changing the file pointer beyond the end of file
f.seek(threeQuarterLength);
checkState(f, threeQuarterLength, 0);
// writing beyont the end of file
f.write(new byte[(int)quarterLength]);
checkState(f, fullLength, fullLength);
// negative file pointer
try {
f.seek(-1);
throw new RuntimeException("IOE not thrown");
} catch (IOException expected) {
}
checkState(f, fullLength, fullLength);
// truncating the file after failed seek
f.setLength(halfLength);
checkState(f, halfLength, halfLength);
// truncating after closing
f.close();
try {
f.setLength(halfLength);
throw new RuntimeException("IOE not thrown");
} catch (IOException expected) {
}
}
public static void main(String[] args) throws IOException {
File f28b = new File("f28b");
File f28K = new File("f28K");
File frnd = new File("frnd");
try (RandomAccessFile raf28b = new RandomAccessFile(f28b, "rw");
RandomAccessFile raf28K = new RandomAccessFile(f28K, "rw");
RandomAccessFile rafrnd = new RandomAccessFile(frnd, "rw")) {
test(raf28b, 7);
test(raf28K, 7 * 1024);
test(rafrnd, 1 + RandomFactory.getRandom().nextInt(16000));
}
// truncating read-only file
try (RandomAccessFile raf28b = new RandomAccessFile(f28b, "r")) {
raf28b.setLength(42);
throw new RuntimeException("IOE not thrown");
} catch (IOException expected) {
}
}
}

View file

@ -0,0 +1,126 @@
/*
* 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.
*/
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.ref.Cleaner;
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 com.sun.management.UnixOperatingSystemMXBean;
import jdk.test.lib.util.FileUtils;
/**
* @test
* @bug 8080225
* @library /test/lib
* @build jdk.test.lib.util.FileUtils UnreferencedRAFClosesFd
* @modules java.base/java.io:open
* @summary Test to ensure that an unclosed and unreferenced RandomAccessFile closes the fd
* @run main/othervm/timeout=480 UnreferencedRAFClosesFd
*/
public class UnreferencedRAFClosesFd {
static final String FILE_NAME = "empty.txt";
/* standalone interface */
public static void main(String argv[]) throws Exception {
File inFile= new File(System.getProperty("test.dir", "."), FILE_NAME);
inFile.createNewFile();
inFile.deleteOnExit();
FileUtils.listFileDescriptors(System.out);
long fdCount0 = getFdCount();
String name = inFile.getPath();
RandomAccessFile raf;
try {
// raf is explicitly *not* closed to allow cleaner to work
raf = new RandomAccessFile(name, "rw");
} catch (FileNotFoundException e) {
System.out.println("Unexpected exception " + e);
throw(e);
}
FileDescriptor fd = raf.getFD();
Field fdField = FileDescriptor.class.getDeclaredField("cleanup");
fdField.setAccessible(true);
Cleaner.Cleanable cleanup = (Cleaner.Cleanable)fdField.get(fd);
// Prepare to wait for FOS, FD, Cleanup to be reclaimed
ReferenceQueue<Object> queue = new ReferenceQueue<>();
HashSet<Reference<?>> pending = HashSet.newHashSet(3);
pending.add(new WeakReference<>(cleanup, queue));
pending.add(new WeakReference<>(raf, queue));
pending.add(new WeakReference<>(fd, queue));
Reference<?> r;
while (((r = queue.remove(10L)) != null)
|| !pending.isEmpty()) {
System.out.printf("r: %s, pending: %d%n", r, pending.size());
if (r != null) {
pending.remove(r);
} else {
cleanup = null;
raf = null;
fd = null;
System.gc(); // attempt to reclaim the RAF, cleanup, and fd
}
}
// Keep these variables in scope as gc roots
Reference.reachabilityFence(cleanup);
Reference.reachabilityFence(fd);
Reference.reachabilityFence(raf);
Reference.reachabilityFence(pending);
// 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;
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 1997, 2010, 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 4074388
@summary Check for correct implementation of RandomAccessFile.writeBytes
and writeChars.
*/
import java.io.*;
public class WriteBytesChars {
public static void main(String args[]) throws Exception {
String towrite;
char[] buf = new char[80];
byte[] b = new byte[80];
File fn = new File("x.WriteBytesChars");
RandomAccessFile raf = new RandomAccessFile(fn , "rw");
try {
for (int i = 0; i < 80; i++) {
buf[i] = 'a';
}
towrite = new String(buf);
raf.writeBytes(towrite);
raf.seek(0);
raf.read(b);
System.out.println("RandomAccessFile.writeBytes");
if (towrite.equals(new String(b))) {
System.err.println("Test succeeded.");
} else {
throw new
RuntimeException("RandomAccessFile.writeBytes, wrong result");
}
raf.seek(0);
raf.writeChars(towrite);
raf.seek(0);
for (int i = 0; i < 80; i++) {
buf[i] = raf.readChar();
}
System.out.println("RandomAccessFile.writeChars");
if (towrite.equals(new String(buf))) {
System.err.println("Test succeeded.");
} else {
throw new
RuntimeException("RandomAccessFile.writeChars, wrong result");
}
} finally {
raf.close();
fn.delete();
}
}
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 1997, 2010, 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 4018515
@summary Make sure that writeUTF throws a UTFDataFormatException when the
output string is too long
*/
import java.io.*;
public class WriteUTF {
public static void main(String[] args) throws IOException {
RandomAccessFile f;
File fn = new File("x.WriteUTF");
String s = "\uffff";
for (int i = 0; i < 16; i++)
s += s;
System.err.println("String length " + s.length());
f = new RandomAccessFile(fn, "rw");
try {
try {
f.writeUTF(s);
}
catch (UTFDataFormatException x) {
return;
}
throw new RuntimeException("UTFDataFormatException not thrown");
}
finally {
f.close();
fn.delete();
}
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (c) 1997, 2010, 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 4027717
@summary Check for correct implementation of RandomAccessFile.skipBytes
*/
import java.io.*;
public class SkipBytes{
/*
* doTest attempts to skip num_to_skip bytes in raf starting from position 0.
* It also does a read after the skip to check if EOF has been reached
* correctly or incorrectly.
*/
private static void doTest(RandomAccessFile raf, int start, int num_to_skip)
throws Exception
{
raf.seek(start);
long cur_ptr = raf.getFilePointer();
int length = (int) raf.length();
System.err.println("\nCurrent pointer = " + cur_ptr + " length = " +
length + " num_to_skip = " + num_to_skip);
//Do the Skip test
int num_skipped = raf.skipBytes(num_to_skip);
System.err.println("After skipBytes -- no. skipped = " + num_skipped);
// if num_to_skip is negative do the negative skip test
if (num_to_skip <= 0) {
if (num_skipped != 0){
System.err.println("Negative Skip Test Failed");
throw new RuntimeException("Negative Skip Test Failed");
}
else {
System.err.println("Negative Skip Test Succeeded");
}
}
cur_ptr = raf.getFilePointer();
System.err.println("Current pointer = " + cur_ptr);
// Check if skip has gone beyond EOF.
if (cur_ptr > length) {
System.err.println("Past EOF Skip Test Failed");
throw new RuntimeException("Past EOF Skip Test Failed");
}
else {
System.err.println("Past EOF Skip Test Succeeded");
}
// do read test
int byte_read = raf.read();
if ( (cur_ptr == length) &&
(byte_read != -1) ) {
System.err.println("byte_read = " + byte_read +
" Read Test Failed ......");
throw new RuntimeException("Read Test Failed");
}
else {
System.err.println("byte_read = " + byte_read +
" Read Test Succeeded");
}
}
public static void main(String[] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile("input.txt" , "rw");
try {
int length = (int)raf.length();
doTest(raf , 0 , 2*length);
doTest(raf , 0 , length);
doTest(raf , 0 , length/2);
doTest(raf , length/2 , -2);
doTest(raf , length , 0);
doTest(raf , 0 , -1);
} finally{
raf.close();
}
}
}

View file

@ -0,0 +1,3 @@
foo
goo
moo