This commit is contained in:
Alejandro Murillo 2015-01-27 10:11:22 -08:00
commit 1f33087085
171 changed files with 11236 additions and 1853 deletions
.hgtags.hgtags-top-repo
corba
hotspot
.hgtags
make/aix/makefiles
src/os/aix/vm
jaxp
jaxws
.hgtags
src
java.xml.bind/share/classes/com/sun/xml/internal/bind
java.xml.ws/share/classes/com/sun/xml/internal/ws
jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/model/nav
jdk
.hgtags
make
gendata
lib
src/classes/build/tools/module
src
java.base
java.desktop
java.naming/share/classes/com/sun/jndi/ldap
java.rmi/share/classes/sun/rmi/transport
java.security.jgss/share/classes/sun/security
jdk.httpserver/share/classes/sun/net/httpserver
jdk.zipfs/share/classes/jdk/nio/zipfs
test

@ -289,3 +289,4 @@ b409bc51bc23cfd51f2bd04ea919ec83535af9d0 jdk9-b37
abbfccd659b91a7bb815d5e36fed635dcdd40f31 jdk9-b44
bfc24ae2b900187585079bb11e66e459d1e525fe jdk9-b45
722378bc599e38d9a1dd484de30f10dfd7b21438 jdk9-b46
8327024a99559982b848e9c2191da9c0bf8838fd jdk9-b47

@ -289,3 +289,4 @@ f7c11da0b0481d49cc7a65a453336c108191e821 jdk9-b42
8994f5d87b3bb5e8d317d4e8ccb326da1a73684a jdk9-b44
3dd628fde2086218d548841022ee8436b6b88185 jdk9-b45
12f1e276447bcc81516e85367d53e4f08897049d jdk9-b46
b6cca3e6175a69f39e5799b7349ddb0176630291 jdk9-b47

@ -289,3 +289,4 @@ e27c725d6c9d155667b35255f442d4ceb8c3c084 jdk9-b40
1f57bd728c9e6865ccb9d43ccd80a1c11230a32f jdk9-b44
9e3f2bed80c0e5a84a256ce41f1d10c5ade48466 jdk9-b45
326f2068b4a4c05e2fa27d6acf93eba7b54b090d jdk9-b46
ee8447ca632e1d39180b4767c749db101bff7314 jdk9-b47

@ -449,3 +449,4 @@ c363a8b87e477ee45d6d3cb2a36cb365141bc596 jdk9-b38
43a44b56dca61a4d766a20f0528fdd8b5ceff873 jdk9-b44
5dc8184af1e2bb30b0103113d1f1a58a21a80c37 jdk9-b45
a184ee1d717297bd35b7c3e35393e137921a3ed2 jdk9-b46
3b241fb72b8925b75941d612db762a6d5da66d02 jdk9-b47

@ -74,6 +74,12 @@ CFLAGS += -D_REENTRANT
# no xlc counterpart for -fcheck-new
# CFLAGS += -fcheck-new
# We need to define this on the command line if we want to use the the
# predefined format specifiers from "inttypes.h". Otherwise system headrs
# can indirectly include inttypes.h before we define __STDC_FORMAT_MACROS
# in globalDefinitions.hpp
CFLAGS += -D__STDC_FORMAT_MACROS
ARCHFLAG = -q64
CFLAGS += $(ARCHFLAG)

@ -31,6 +31,7 @@
#include "os_aix.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/perfMemory.hpp"
#include "services/memTracker.hpp"
#include "utilities/exceptions.hpp"
// put OS-includes here
@ -196,12 +197,37 @@ static pid_t filename_to_pid(const char* filename) {
return pid;
}
// Check if the given statbuf is considered a secure directory for
// the backing store files. Returns true if the directory is considered
// a secure location. Returns false if the statbuf is a symbolic link or
// if an error occurred.
static bool is_statbuf_secure(struct stat *statp) {
if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {
// The path represents a link or some non-directory file type,
// which is not what we expected. Declare it insecure.
//
return false;
}
// We have an existing directory, check if the permissions are safe.
if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {
// The directory is open for writing and could be subjected
// to a symlink or a hard link attack. Declare it insecure.
return false;
}
// See if the uid of the directory matches the effective uid of the process.
//
if (statp->st_uid != geteuid()) {
// The directory was not created by this user, declare it insecure.
return false;
}
return true;
}
// check if the given path is considered a secure directory for
// Check if the given path is considered a secure directory for
// the backing store files. Returns true if the directory exists
// and is considered a secure location. Returns false if the path
// is a symbolic link or if an error occurred.
//
static bool is_directory_secure(const char* path) {
struct stat statbuf;
int result = 0;
@ -211,38 +237,276 @@ static bool is_directory_secure(const char* path) {
return false;
}
// the path exists, now check it's mode
if (S_ISLNK(statbuf.st_mode) || !S_ISDIR(statbuf.st_mode)) {
// the path represents a link or some non-directory file type,
// which is not what we expected. declare it insecure.
//
// The path exists, see if it is secure.
return is_statbuf_secure(&statbuf);
}
// (Taken over from Solaris to support the O_NOFOLLOW case on AIX.)
// Check if the given directory file descriptor is considered a secure
// directory for the backing store files. Returns true if the directory
// exists and is considered a secure location. Returns false if the path
// is a symbolic link or if an error occurred.
static bool is_dirfd_secure(int dir_fd) {
struct stat statbuf;
int result = 0;
RESTARTABLE(::fstat(dir_fd, &statbuf), result);
if (result == OS_ERR) {
return false;
}
else {
// we have an existing directory, check if the permissions are safe.
//
if ((statbuf.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
// the directory is open for writing and could be subjected
// to a symlnk attack. declare it insecure.
//
return false;
// The path exists, now check its mode.
return is_statbuf_secure(&statbuf);
}
// Check to make sure fd1 and fd2 are referencing the same file system object.
static bool is_same_fsobject(int fd1, int fd2) {
struct stat statbuf1;
struct stat statbuf2;
int result = 0;
RESTARTABLE(::fstat(fd1, &statbuf1), result);
if (result == OS_ERR) {
return false;
}
RESTARTABLE(::fstat(fd2, &statbuf2), result);
if (result == OS_ERR) {
return false;
}
if ((statbuf1.st_ino == statbuf2.st_ino) &&
(statbuf1.st_dev == statbuf2.st_dev)) {
return true;
} else {
return false;
}
}
// Helper functions for open without O_NOFOLLOW which is not present on AIX 5.3/6.1.
// We use the jdk6 implementation here.
#ifndef O_NOFOLLOW
// The O_NOFOLLOW oflag doesn't exist before solaris 5.10, this is to simulate that behaviour
// was done in jdk 5/6 hotspot by Oracle this way
static int open_o_nofollow_impl(const char* path, int oflag, mode_t mode, bool use_mode) {
struct stat orig_st;
struct stat new_st;
bool create;
int error;
int fd;
create = false;
if (lstat(path, &orig_st) != 0) {
if (errno == ENOENT && (oflag & O_CREAT) != 0) {
// File doesn't exist, but_we want to create it, add O_EXCL flag
// to make sure no-one creates it (or a symlink) before us
// This works as we expect with symlinks, from posix man page:
// 'If O_EXCL and O_CREAT are set, and path names a symbolic
// link, open() shall fail and set errno to [EEXIST]'.
oflag |= O_EXCL;
create = true;
} else {
// File doesn't exist, and we are not creating it.
return OS_ERR;
}
} else {
// Lstat success, check if existing file is a link.
if ((orig_st.st_mode & S_IFMT) == S_IFLNK) {
// File is a symlink.
errno = ELOOP;
return OS_ERR;
}
}
if (use_mode == true) {
fd = open(path, oflag, mode);
} else {
fd = open(path, oflag);
}
if (fd == OS_ERR) {
return fd;
}
// Can't do inode checks on before/after if we created the file.
if (create == false) {
if (fstat(fd, &new_st) != 0) {
// Keep errno from fstat, in case close also fails.
error = errno;
::close(fd);
errno = error;
return OS_ERR;
}
if (orig_st.st_dev != new_st.st_dev || orig_st.st_ino != new_st.st_ino) {
// File was tampered with during race window.
::close(fd);
errno = EEXIST;
if (PrintMiscellaneous && Verbose) {
warning("possible file tampering attempt detected when opening %s", path);
}
return OS_ERR;
}
}
return fd;
}
static int open_o_nofollow(const char* path, int oflag, mode_t mode) {
return open_o_nofollow_impl(path, oflag, mode, true);
}
static int open_o_nofollow(const char* path, int oflag) {
return open_o_nofollow_impl(path, oflag, 0, false);
}
#endif
// Open the directory of the given path and validate it.
// Return a DIR * of the open directory.
static DIR *open_directory_secure(const char* dirname) {
// Open the directory using open() so that it can be verified
// to be secure by calling is_dirfd_secure(), opendir() and then check
// to see if they are the same file system object. This method does not
// introduce a window of opportunity for the directory to be attacked that
// calling opendir() and is_directory_secure() does.
int result;
DIR *dirp = NULL;
// No O_NOFOLLOW defined at buildtime, and it is not documented for open;
// so provide a workaround in this case.
#ifdef O_NOFOLLOW
RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);
#else
// workaround (jdk6 coding)
RESTARTABLE(::open_o_nofollow(dirname, O_RDONLY), result);
#endif
if (result == OS_ERR) {
// Directory doesn't exist or is a symlink, so there is nothing to cleanup.
if (PrintMiscellaneous && Verbose) {
if (errno == ELOOP) {
warning("directory %s is a symlink and is not secure\n", dirname);
} else {
warning("could not open directory %s: %s\n", dirname, strerror(errno));
}
}
return dirp;
}
int fd = result;
// Determine if the open directory is secure.
if (!is_dirfd_secure(fd)) {
// The directory is not a secure directory.
os::close(fd);
return dirp;
}
// Open the directory.
dirp = ::opendir(dirname);
if (dirp == NULL) {
// The directory doesn't exist, close fd and return.
os::close(fd);
return dirp;
}
// Check to make sure fd and dirp are referencing the same file system object.
if (!is_same_fsobject(fd, dirp->dd_fd)) {
// The directory is not secure.
os::close(fd);
os::closedir(dirp);
dirp = NULL;
return dirp;
}
// Close initial open now that we know directory is secure
os::close(fd);
return dirp;
}
// NOTE: The code below uses fchdir(), open() and unlink() because
// fdopendir(), openat() and unlinkat() are not supported on all
// versions. Once the support for fdopendir(), openat() and unlinkat()
// is available on all supported versions the code can be changed
// to use these functions.
// Open the directory of the given path, validate it and set the
// current working directory to it.
// Return a DIR * of the open directory and the saved cwd fd.
//
static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {
// Open the directory.
DIR* dirp = open_directory_secure(dirname);
if (dirp == NULL) {
// Directory doesn't exist or is insecure, so there is nothing to cleanup.
return dirp;
}
int fd = dirp->dd_fd;
// Open a fd to the cwd and save it off.
int result;
RESTARTABLE(::open(".", O_RDONLY), result);
if (result == OS_ERR) {
*saved_cwd_fd = -1;
} else {
*saved_cwd_fd = result;
}
// Set the current directory to dirname by using the fd of the directory.
result = fchdir(fd);
return dirp;
}
// Close the directory and restore the current working directory.
static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {
int result;
// If we have a saved cwd change back to it and close the fd.
if (saved_cwd_fd != -1) {
result = fchdir(saved_cwd_fd);
::close(saved_cwd_fd);
}
// Close the directory.
os::closedir(dirp);
}
// Check if the given file descriptor is considered a secure.
static bool is_file_secure(int fd, const char *filename) {
int result;
struct stat statbuf;
// Determine if the file is secure.
RESTARTABLE(::fstat(fd, &statbuf), result);
if (result == OS_ERR) {
if (PrintMiscellaneous && Verbose) {
warning("fstat failed on %s: %s\n", filename, strerror(errno));
}
return false;
}
if (statbuf.st_nlink > 1) {
// A file with multiple links is not expected.
if (PrintMiscellaneous && Verbose) {
warning("file %s has multiple links\n", filename);
}
return false;
}
return true;
}
// return the user name for the given user id
//
// the caller is expected to free the allocated memory.
// Return the user name for the given user id.
//
// The caller is expected to free the allocated memory.
static char* get_user_name(uid_t uid) {
struct passwd pwent;
// determine the max pwbuf size from sysconf, and hardcode
// Determine the max pwbuf size from sysconf, and hardcode
// a default if this not available through sysconf.
//
long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1)
bufsize = 1024;
@ -344,7 +608,8 @@ static char* get_user_name_slow(int vmid, TRAPS) {
strcat(usrdir_name, "/");
strcat(usrdir_name, dentry->d_name);
DIR* subdirp = os::opendir(usrdir_name);
// Open the user directory.
DIR* subdirp = open_directory_secure(usrdir_name);
if (subdirp == NULL) {
FREE_C_HEAP_ARRAY(char, usrdir_name);
@ -464,28 +729,7 @@ static void remove_file(const char* path) {
}
}
// remove file
//
// this method removes the file with the given file name in the
// named directory.
//
static void remove_file(const char* dirname, const char* filename) {
size_t nbytes = strlen(dirname) + strlen(filename) + 2;
char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
strcpy(path, dirname);
strcat(path, "/");
strcat(path, filename);
remove_file(path);
FREE_C_HEAP_ARRAY(char, path);
}
// cleanup stale shared memory resources
// Cleanup stale shared memory resources
//
// This method attempts to remove all stale shared memory files in
// the named user temporary directory. It scans the named directory
@ -493,33 +737,26 @@ static void remove_file(const char* dirname, const char* filename) {
// process id is extracted from the file name and a test is run to
// determine if the process is alive. If the process is not alive,
// any stale file resources are removed.
//
static void cleanup_sharedmem_resources(const char* dirname) {
// open the user temp directory
DIR* dirp = os::opendir(dirname);
int saved_cwd_fd;
// Open the directory.
DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
if (dirp == NULL) {
// directory doesn't exist, so there is nothing to cleanup
// Directory doesn't exist or is insecure, so there is nothing to cleanup.
return;
}
if (!is_directory_secure(dirname)) {
// the directory is not a secure directory
os::closedir(dirp);
return;
}
// for each entry in the directory that matches the expected file
// For each entry in the directory that matches the expected file
// name pattern, determine if the file resources are stale and if
// so, remove the file resources. Note, instrumented HotSpot processes
// for this user may start and/or terminate during this search and
// remove or create new files in this directory. The behavior of this
// loop under these conditions is dependent upon the implementation of
// opendir/readdir.
//
struct dirent* entry;
char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
errno = 0;
while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
@ -529,56 +766,55 @@ static void cleanup_sharedmem_resources(const char* dirname) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
// attempt to remove all unexpected files, except "." and ".."
remove_file(dirname, entry->d_name);
// Attempt to remove all unexpected files, except "." and "..".
unlink(entry->d_name);
}
errno = 0;
continue;
}
// we now have a file name that converts to a valid integer
// We now have a file name that converts to a valid integer
// that could represent a process id . if this process id
// matches the current process id or the process is not running,
// then remove the stale file resources.
//
// process liveness is detected by sending signal number 0 to
// Process liveness is detected by sending signal number 0 to
// the process id (see kill(2)). if kill determines that the
// process does not exist, then the file resources are removed.
// if kill determines that that we don't have permission to
// signal the process, then the file resources are assumed to
// be stale and are removed because the resources for such a
// process should be in a different user specific directory.
//
if ((pid == os::current_process_id()) ||
(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
remove_file(dirname, entry->d_name);
unlink(entry->d_name);
}
errno = 0;
}
os::closedir(dirp);
FREE_C_HEAP_ARRAY(char, dbuf);
// Close the directory and reset the current working directory.
close_directory_secure_cwd(dirp, saved_cwd_fd);
FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
}
// make the user specific temporary directory. Returns true if
// Make the user specific temporary directory. Returns true if
// the directory exists and is secure upon return. Returns false
// if the directory exists but is either a symlink, is otherwise
// insecure, or if an error occurred.
//
static bool make_user_tmp_dir(const char* dirname) {
// create the directory with 0755 permissions. note that the directory
// Create the directory with 0755 permissions. note that the directory
// will be owned by euid::egid, which may not be the same as uid::gid.
//
if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
if (errno == EEXIST) {
// The directory already exists and was probably created by another
// JVM instance. However, this could also be the result of a
// deliberate symlink. Verify that the existing directory is safe.
//
if (!is_directory_secure(dirname)) {
// directory is not secure
// Directory is not secure.
if (PrintMiscellaneous && Verbose) {
warning("%s directory is insecure\n", dirname);
}
@ -614,19 +850,63 @@ static int create_sharedmem_resources(const char* dirname, const char* filename,
return -1;
}
int result;
RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE), result);
if (result == OS_ERR) {
if (PrintMiscellaneous && Verbose) {
warning("could not create file %s: %s\n", filename, strerror(errno));
}
int saved_cwd_fd;
// Open the directory and set the current working directory to it.
DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
if (dirp == NULL) {
// Directory doesn't exist or is insecure, so cannot create shared
// memory file.
return -1;
}
// Open the filename in the current directory.
// Cannot use O_TRUNC here; truncation of an existing file has to happen
// after the is_file_secure() check below.
int result;
// No O_NOFOLLOW defined at buildtime, and it is not documented for open;
// so provide a workaround in this case.
#ifdef O_NOFOLLOW
RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);
#else
// workaround function (jdk6 code)
RESTARTABLE(::open_o_nofollow(filename, O_RDWR|O_CREAT, S_IREAD|S_IWRITE), result);
#endif
if (result == OS_ERR) {
if (PrintMiscellaneous && Verbose) {
if (errno == ELOOP) {
warning("file %s is a symlink and is not secure\n", filename);
} else {
warning("could not create file %s: %s\n", filename, strerror(errno));
}
}
// Close the directory and reset the current working directory.
close_directory_secure_cwd(dirp, saved_cwd_fd);
return -1;
}
// Close the directory and reset the current working directory.
close_directory_secure_cwd(dirp, saved_cwd_fd);
// save the file descriptor
int fd = result;
// Check to see if the file is secure.
if (!is_file_secure(fd, filename)) {
::close(fd);
return -1;
}
// Truncate the file to get rid of any existing data.
RESTARTABLE(::ftruncate(fd, (off_t)0), result);
if (result == OS_ERR) {
if (PrintMiscellaneous && Verbose) {
warning("could not truncate shared memory file: %s\n", strerror(errno));
}
::close(fd);
return -1;
}
// set the file size
RESTARTABLE(::ftruncate(fd, (off_t)size), result);
if (result == OS_ERR) {
@ -648,7 +928,14 @@ static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
// open the file
int result;
// No O_NOFOLLOW defined at buildtime, and it is not documented for open;
// so provide a workaround in this case
#ifdef O_NOFOLLOW
RESTARTABLE(::open(filename, oflags), result);
#else
RESTARTABLE(::open_o_nofollow(filename, oflags), result);
#endif
if (result == OS_ERR) {
if (errno == ENOENT) {
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
@ -662,8 +949,15 @@ static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
}
}
int fd = result;
return result;
// Check to see if the file is secure.
if (!is_file_secure(fd, filename)) {
::close(fd);
return -1;
}
return fd;
}
// create a named shared memory region. returns the address of the
@ -695,13 +989,21 @@ static char* mmap_create_shared(size_t size) {
char* dirname = get_user_tmp_dir(user_name);
char* filename = get_sharedmem_filename(dirname, vmid);
// Get the short filename.
char* short_filename = strrchr(filename, '/');
if (short_filename == NULL) {
short_filename = filename;
} else {
short_filename++;
}
// cleanup any stale shared memory files
cleanup_sharedmem_resources(dirname);
assert(((size > 0) && (size % os::vm_page_size() == 0)),
"unexpected PerfMemory region size");
fd = create_sharedmem_resources(dirname, filename, size);
fd = create_sharedmem_resources(dirname, short_filename, size);
FREE_C_HEAP_ARRAY(char, user_name);
FREE_C_HEAP_ARRAY(char, dirname);
@ -733,6 +1035,9 @@ static char* mmap_create_shared(size_t size) {
// clear the shared memory region
(void)::memset((void*) mapAddress, 0, size);
// It does not go through os api, the operation has to record from here.
MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);
return mapAddress;
}
@ -807,7 +1112,7 @@ static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemor
char* mapAddress;
int result;
int fd;
size_t size;
size_t size = 0;
const char* luser = NULL;
int mmap_prot;
@ -819,12 +1124,18 @@ static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemor
// constructs for the file and the shared memory mapping.
if (mode == PerfMemory::PERF_MODE_RO) {
mmap_prot = PROT_READ;
// No O_NOFOLLOW defined at buildtime, and it is not documented for open.
#ifdef O_NOFOLLOW
file_flags = O_RDONLY | O_NOFOLLOW;
#else
file_flags = O_RDONLY;
#endif
}
else if (mode == PerfMemory::PERF_MODE_RW) {
#ifdef LATER
mmap_prot = PROT_READ | PROT_WRITE;
file_flags = O_RDWR;
file_flags = O_RDWR | O_NOFOLLOW;
#else
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"Unsupported access mode");
@ -853,9 +1164,9 @@ static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemor
// store file, we don't follow them when attaching either.
//
if (!is_directory_secure(dirname)) {
FREE_C_HEAP_ARRAY(char, dirname);
FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
if (luser != user) {
FREE_C_HEAP_ARRAY(char, luser);
FREE_C_HEAP_ARRAY(char, luser, mtInternal);
}
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"Process not found");
@ -901,6 +1212,9 @@ static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemor
"Could not map PerfMemory");
}
// It does not go through os api, the operation has to record from here.
MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);
*addr = mapAddress;
*sizep = size;

@ -289,3 +289,4 @@ a12d347f84176200593999f4da91ae2bb86865b2 jdk9-b39
0cb0844b58924d6086d2850c22087d06679d5eef jdk9-b44
0dab3e848229127c7aca4c58b98e2d90ba70372f jdk9-b45
74eaf7ad986576c792df4dbff05eed63e5727695 jdk9-b46
e391de88e69b59d7c618387e3cf91032f6991ce9 jdk9-b47

@ -292,3 +292,4 @@ edc13d27dc871be57d7ca77eef77e6d04972fee2 jdk9-b43
2a03baa4d849818ff6d635f110c2813b12fc2326 jdk9-b44
e529374fbe526dbd668e5e98fc047b42b3bc6d33 jdk9-b45
64ca52b0bda8028636e4ccafbe1107befcdda47d jdk9-b46
6c17d648d03e4bf4729c3645f8db55d34115e0b7 jdk9-b47

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -205,7 +205,15 @@ public abstract class RuntimeBuiltinLeafInfoImpl<T> extends BuiltinLeafInfoImpl<
static {
QName[] qnames = (System.getProperty(MAP_ANYURI_TO_URI) == null) ? new QName[] {
String MAP_ANYURI_TO_URI_VALUE = AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(MAP_ANYURI_TO_URI);
}
}
);
QName[] qnames = (MAP_ANYURI_TO_URI_VALUE == null) ? new QName[] {
createXS("string"),
createXS("anySimpleType"),
createXS("normalizedString"),
@ -318,7 +326,7 @@ public abstract class RuntimeBuiltinLeafInfoImpl<T> extends BuiltinLeafInfoImpl<
return v.toExternalForm();
}
});
if (System.getProperty(MAP_ANYURI_TO_URI) == null) {
if (MAP_ANYURI_TO_URI_VALUE == null) {
secondaryList.add(
new StringImpl<URI>(URI.class, createXS("string")) {
public URI parse(CharSequence text) throws SAXException {
@ -782,17 +790,18 @@ public abstract class RuntimeBuiltinLeafInfoImpl<T> extends BuiltinLeafInfoImpl<
}
});
primaryList.add(
new StringImpl<BigDecimal>(BigDecimal.class,
createXS("decimal")
new StringImpl<BigDecimal>(BigDecimal.class,
createXS("decimal")
) {
public BigDecimal parse(CharSequence text) {
return DatatypeConverterImpl._parseDecimal(text.toString());
}
public BigDecimal parse(CharSequence text) {
return DatatypeConverterImpl._parseDecimal(text.toString());
}
public String print(BigDecimal v) {
return DatatypeConverterImpl._printDecimal(v);
public String print(BigDecimal v) {
return DatatypeConverterImpl._printDecimal(v);
}
}
});
);
primaryList.add(
new StringImpl<QName>(QName.class,
createXS("QName")
@ -820,7 +829,7 @@ public abstract class RuntimeBuiltinLeafInfoImpl<T> extends BuiltinLeafInfoImpl<
w.getNamespaceContext().declareNamespace(v.getNamespaceURI(),v.getPrefix(),false);
}
});
if (System.getProperty(MAP_ANYURI_TO_URI) != null) {
if (MAP_ANYURI_TO_URI_VALUE != null) {
primaryList.add(
new StringImpl<URI>(URI.class, createXS("anyURI")) {
public URI parse(CharSequence text) throws SAXException {
@ -838,16 +847,17 @@ public abstract class RuntimeBuiltinLeafInfoImpl<T> extends BuiltinLeafInfoImpl<
});
}
primaryList.add(
new StringImpl<Duration>(Duration.class, createXS("duration")) {
public String print(Duration duration) {
return duration.toString();
}
new StringImpl<Duration>(Duration.class, createXS("duration")) {
public String print(Duration duration) {
return duration.toString();
}
public Duration parse(CharSequence lexical) {
TODO.checkSpec("JSR222 Issue #42");
return DatatypeConverterImpl.getDatatypeFactory().newDuration(lexical.toString());
public Duration parse(CharSequence lexical) {
TODO.checkSpec("JSR222 Issue #42");
return DatatypeConverterImpl.getDatatypeFactory().newDuration(lexical.toString());
}
}
});
);
primaryList.add(
new StringImpl<Void>(Void.class) {
// 'void' binding isn't defined by the spec, but when the JAX-RPC processes user-defined

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2014 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
@ -25,8 +25,10 @@
package com.sun.xml.internal.bind.v2.util;
import com.sun.xml.internal.bind.Util;
import com.sun.xml.internal.bind.v2.Messages;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
@ -43,8 +45,6 @@ import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import static com.sun.xml.internal.bind.Util.getSystemProperty;
/**
* Provides helper methods for creating properly configured XML parser
* factory instances with namespace support turned on and configured for
@ -68,7 +68,14 @@ public class XmlFactory {
*/
private static final String DISABLE_XML_SECURITY = "com.sun.xml.internal.bind.disableXmlSecurity";
public static final boolean XML_SECURITY_DISABLED = Boolean.parseBoolean(getSystemProperty(DISABLE_XML_SECURITY));
private static final boolean XML_SECURITY_DISABLED = AccessController.doPrivileged(
new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return Boolean.getBoolean(DISABLE_XML_SECURITY);
}
}
);
private static boolean isXMLSecurityDisabled(boolean runtimeSetting) {
return XML_SECURITY_DISABLED || runtimeSetting;

@ -54,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -72,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -147,19 +147,12 @@ public class ProviderImpl extends Provider {
}
public EndpointReference readEndpointReference(final Source eprInfoset) {
// EPR constructors are private, so we need privilege escalation.
// this unmarshalling can only access instances of a fixed, known set of classes,
// so doing that shouldn't introduce security vulnerability.
return AccessController.doPrivileged(new PrivilegedAction<EndpointReference>() {
public EndpointReference run() {
try {
Unmarshaller unmarshaller = eprjc.get().createUnmarshaller();
return (EndpointReference) unmarshaller.unmarshal(eprInfoset);
} catch (JAXBException e) {
throw new WebServiceException("Error creating Marshaller or marshalling.", e);
}
}
});
try {
Unmarshaller unmarshaller = eprjc.get().createUnmarshaller();
return (EndpointReference) unmarshaller.unmarshal(eprInfoset);
} catch (JAXBException e) {
throw new WebServiceException("Error creating Marshaller or marshalling.", e);
}
}
public <T> T getPort(EndpointReference endpointReference, Class<T> clazz, WebServiceFeature... webServiceFeatures) {

@ -54,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -72,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -63,6 +63,8 @@ import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
@ -84,12 +86,16 @@ public class XmlUtil {
private static final Logger LOGGER = Logger.getLogger(XmlUtil.class.getName());
private static boolean XML_SECURITY_DISABLED;
private static final String DISABLE_XML_SECURITY = "com.sun.xml.internal.ws.disableXmlSecurity";
static {
String disableXmlSecurity = System.getProperty("com.sun.xml.internal.ws.disableXmlSecurity");
XML_SECURITY_DISABLED = disableXmlSecurity == null || !Boolean.valueOf(disableXmlSecurity);
}
private static boolean XML_SECURITY_DISABLED = AccessController.doPrivileged(
new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return Boolean.getBoolean(DISABLE_XML_SECURITY);
}
}
);
public static String getPrefix(String s) {
int i = s.indexOf(':');

@ -38,6 +38,9 @@ import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
@ -51,17 +54,20 @@ final class Utils {
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
//noinspection unchecked
final Method getInstance = refNav.getDeclaredMethod("getInstance");
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Object run() {
getInstance.setAccessible(true);
return null;
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
@ -69,16 +75,10 @@ final class Utils {
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);

@ -289,3 +289,4 @@ e336cbd8b15e959e70ed02f0f5e93fa76ebd4c07 jdk9-b41
8cc4dc300041eb70a7a40e4b2431a8f4d4965ea4 jdk9-b44
9acaa4f57b0b9e3757a7b4576ca9418a75ea8287 jdk9-b45
efedac7f44ed41cea2b1038138047271f55aacba jdk9-b46
b641c14730ac05d9ec8b4f66e6fca3dc21adb403 jdk9-b47

@ -35,65 +35,62 @@ include JavaCompilation.gmk
US_EXPORT_POLICY_JAR_DST := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/US_export_policy.jar
ifneq ($(BUILD_CRYPTO), no)
US_EXPORT_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/US_export_policy.jar
US_EXPORT_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy.jar
ifndef OPENJDK
#
# In past releases, Oracle JDK has had a separately downloadable set of
# policy files which has been a nightmare for deployment.
#
# Now if we're closed and limited (default for Oracle JDK), create
# an "unlimited_policy" directory that contains the unlimited policy
# files. It will be up to the user/deployer to make an informed choice
# as to whether they are legally entitled to use the unlimited policy
# file in their environment. Users/deployers simply need to overwrite
# the files. Consult README.txt (below) for more info.
#
UNLIMITED_POLICY_DIR := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/unlimited_policy
endif
US_EXPORT_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/US_export_policy.jar
US_EXPORT_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy.jar
ifndef OPENJDK
#
# TODO fix so that SetupArchive does not write files into SRCS
# then we don't need this extra copying
# In past releases, Oracle JDK has had a separately downloadable set of
# policy files which has been a nightmare for deployment.
#
# NOTE: We currently do not place restrictions on our limited export
# policy. This was not a typo. This means we are shipping the same file
# for both limited and unlimited US_export_policy.jar. Only the local
# policy file currently has restrictions.
# Now if we're closed and limited (default for Oracle JDK), create
# an "unlimited_policy" directory that contains the unlimited policy
# files. It will be up to the user/deployer to make an informed choice
# as to whether they are legally entitled to use the unlimited policy
# file in their environment. Users/deployers simply need to overwrite
# the files. Consult README.txt (below) for more info.
#
US_EXPORT_POLICY_JAR_SRC_DIR := \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited
US_EXPORT_POLICY_JAR_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy_jar.tmp
UNLIMITED_POLICY_DIR := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/unlimited_policy
endif
$(US_EXPORT_POLICY_JAR_TMP)/%: $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
#
# TODO fix so that SetupArchive does not write files into SRCS
# then we don't need this extra copying
#
# NOTE: We currently do not place restrictions on our limited export
# policy. This was not a typo. This means we are shipping the same file
# for both limited and unlimited US_export_policy.jar. Only the local
# policy file currently has restrictions.
#
US_EXPORT_POLICY_JAR_SRC_DIR := \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited
US_EXPORT_POLICY_JAR_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy_jar.tmp
$(US_EXPORT_POLICY_JAR_TMP)/%: $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
$(install-file)
US_EXPORT_POLICY_JAR_DEPS := \
$(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
US_EXPORT_POLICY_JAR_DEPS := \
$(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
$(eval $(call SetupArchive,BUILD_US_EXPORT_POLICY_JAR, \
$(US_EXPORT_POLICY_JAR_DEPS), \
SRCS := $(US_EXPORT_POLICY_JAR_TMP), \
SUFFIXES := .policy, \
JAR := $(US_EXPORT_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true))
$(eval $(call SetupArchive,BUILD_US_EXPORT_POLICY_JAR, \
$(US_EXPORT_POLICY_JAR_DEPS), \
SRCS := $(US_EXPORT_POLICY_JAR_TMP), \
SUFFIXES := .policy, \
JAR := $(US_EXPORT_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true))
$(US_EXPORT_POLICY_JAR_LIMITED): \
$(US_EXPORT_POLICY_JAR_UNLIMITED)
$(ECHO) $(LOG_INFO) \
Copying unlimited $(patsubst $(OUTPUT_ROOT)/%,%,$@)
$(install-file)
$(US_EXPORT_POLICY_JAR_LIMITED): \
$(US_EXPORT_POLICY_JAR_UNLIMITED)
$(ECHO) $(LOG_INFO) \
Copying unlimited $(patsubst $(OUTPUT_ROOT)/%,%,$@)
$(install-file)
TARGETS += $(US_EXPORT_POLICY_JAR_LIMITED) $(US_EXPORT_POLICY_JAR_UNLIMITED)
endif
TARGETS += $(US_EXPORT_POLICY_JAR_LIMITED) $(US_EXPORT_POLICY_JAR_UNLIMITED)
ifeq ($(UNLIMITED_CRYPTO), true)
$(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED)
@ -119,57 +116,54 @@ POLICY_JARS += $(US_EXPORT_POLICY_JAR_DST)
LOCAL_POLICY_JAR_DST := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/local_policy.jar
ifneq ($(BUILD_CRYPTO), no)
LOCAL_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy.jar
LOCAL_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy.jar
LOCAL_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy.jar
LOCAL_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy.jar
#
# TODO fix so that SetupArchive does not write files into SRCS
# then we don't need this extra copying
#
LOCAL_POLICY_JAR_LIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy_jar.tmp
LOCAL_POLICY_JAR_UNLIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy_jar.tmp
#
# TODO fix so that SetupArchive does not write files into SRCS
# then we don't need this extra copying
#
LOCAL_POLICY_JAR_LIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy_jar.tmp
LOCAL_POLICY_JAR_UNLIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy_jar.tmp
$(LOCAL_POLICY_JAR_LIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/limited/%
$(install-file)
$(LOCAL_POLICY_JAR_LIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/limited/%
$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited/%
$(install-file)
$(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR_LIMITED, \
$(LOCAL_POLICY_JAR_LIMITED_TMP)/exempt_local.policy \
$(LOCAL_POLICY_JAR_LIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_LIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_LIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: limited, \
SKIP_METAINF := true))
$(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR_UNLIMITED, \
$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_UNLIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true))
TARGETS += $(LOCAL_POLICY_JAR_LIMITED) $(LOCAL_POLICY_JAR_UNLIMITED)
ifndef OPENJDK
ifneq ($(UNLIMITED_CRYPTO), true)
$(UNLIMITED_POLICY_DIR)/README.txt: \
$(JDK_TOPDIR)/make/closed/data/cryptopolicy/README.txt
$(install-file)
$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited/%
$(install-file)
$(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR_LIMITED, \
$(LOCAL_POLICY_JAR_LIMITED_TMP)/exempt_local.policy \
$(LOCAL_POLICY_JAR_LIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_LIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_LIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: limited, \
SKIP_METAINF := true))
$(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR_UNLIMITED, \
$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_UNLIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true))
TARGETS += $(LOCAL_POLICY_JAR_LIMITED) $(LOCAL_POLICY_JAR_UNLIMITED)
ifndef OPENJDK
ifneq ($(UNLIMITED_CRYPTO), true)
$(UNLIMITED_POLICY_DIR)/README.txt: \
$(JDK_TOPDIR)/make/closed/data/cryptopolicy/README.txt
$(install-file)
TARGETS += $(UNLIMITED_POLICY_DIR)/README.txt
endif
TARGETS += $(UNLIMITED_POLICY_DIR)/README.txt
endif
endif

@ -300,7 +300,6 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),)
LIBAWT_XAWT_DIRS := \
$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/libawt_xawt \
$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/libjawt \
$(JDK_TOPDIR)/src/java.desktop/share/native/common/awt/debug \
$(JDK_TOPDIR)/src/java.desktop/share/native/common/awt/utility \
$(JDK_TOPDIR)/src/java.desktop/share/native/common/font \

@ -6,4 +6,4 @@ jdk.localedata
jdk.naming.dns
jdk.scripting.nashorn
jdk.zipfs
oracle.accessbridge
jdk.accessbridge

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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
@ -30,6 +30,11 @@ class ClassLoaderHelper {
private ClassLoaderHelper() {}
/**
* Indicates, whether PATH env variable is allowed to contain quoted entries.
*/
static final boolean allowsQuotedPathElements = false;
/**
* Returns an alternate path name for the given file
* such that if the original pathname did not exist, then the

@ -149,7 +149,8 @@ public final class Class<T> implements java.io.Serializable,
* {@code getName}. If this {@code Class} object represents a
* primitive type, this method returns the name of the primitive type. If
* this {@code Class} object represents void this method returns
* "void".
* "void". If this {@code Class} object represents an array type,
* this method returns "class " followed by {@code getName}.
*
* @return a string representation of this class object.
*/
@ -174,6 +175,12 @@ public final class Class<T> implements java.io.Serializable,
* occur in canonical order. If there are no type parameters, the
* type parameter list is elided.
*
* For an array type, the string starts with the type name,
* followed by an angle-bracketed comma-separated list of the
* type's type parameters, if any, followed by a sequence of
* {@code []} characters, one set of brackets per dimension of
* the array.
*
* <p>Note that since information about the runtime representation
* of a type is being generated, modifiers not present on the
* originating source code or illegal on the originating source
@ -189,29 +196,39 @@ public final class Class<T> implements java.io.Serializable,
return toString();
} else {
StringBuilder sb = new StringBuilder();
Class<?> component = this;
int arrayDepth = 0;
// Class modifiers are a superset of interface modifiers
int modifiers = getModifiers() & Modifier.classModifiers();
if (modifiers != 0) {
sb.append(Modifier.toString(modifiers));
sb.append(' ');
}
if (isAnnotation()) {
sb.append('@');
}
if (isInterface()) { // Note: all annotation types are interfaces
sb.append("interface");
if (isArray()) {
do {
arrayDepth++;
component = component.getComponentType();
} while (component.isArray());
sb.append(component.getName());
} else {
if (isEnum())
sb.append("enum");
else
sb.append("class");
}
sb.append(' ');
sb.append(getName());
// Class modifiers are a superset of interface modifiers
int modifiers = getModifiers() & Modifier.classModifiers();
if (modifiers != 0) {
sb.append(Modifier.toString(modifiers));
sb.append(' ');
}
TypeVariable<?>[] typeparms = getTypeParameters();
if (isAnnotation()) {
sb.append('@');
}
if (isInterface()) { // Note: all annotation types are interfaces
sb.append("interface");
} else {
if (isEnum())
sb.append("enum");
else
sb.append("class");
}
sb.append(' ');
sb.append(getName());
}
TypeVariable<?>[] typeparms = component.getTypeParameters();
if (typeparms.length > 0) {
boolean first = true;
sb.append('<');
@ -224,6 +241,9 @@ public final class Class<T> implements java.io.Serializable,
sb.append('>');
}
for (int i = 0; i < arrayDepth; i++)
sb.append("[]");
return sb.toString();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -1360,7 +1360,10 @@ public abstract class ClassLoader {
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkClassLoaderPermission(this, Reflection.getCallerClass());
// Check access to the parent class loader
// If the caller's class loader is same as this class loader,
// permission check is performed.
checkClassLoaderPermission(parent, Reflection.getCallerClass());
}
return parent;
}
@ -1503,6 +1506,11 @@ public abstract class ClassLoader {
return caller.getClassLoader0();
}
/*
* Checks RuntimePermission("getClassLoader") permission
* if caller's class loader is not null and caller's class loader
* is not the same as or an ancestor of the given cl argument.
*/
static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
@ -1747,35 +1755,54 @@ public abstract class ClassLoader {
private static String usr_paths[];
private static String sys_paths[];
private static String[] initializePath(String propname) {
String ldpath = System.getProperty(propname, "");
String ps = File.pathSeparator;
int ldlen = ldpath.length();
int i, j, n;
// Count the separators in the path
i = ldpath.indexOf(ps);
n = 0;
while (i >= 0) {
n++;
i = ldpath.indexOf(ps, i + 1);
}
private static String[] initializePath(String propName) {
String ldPath = System.getProperty(propName, "");
int ldLen = ldPath.length();
char ps = File.pathSeparatorChar;
int psCount = 0;
// allocate the array of paths - n :'s = n + 1 path elements
String[] paths = new String[n + 1];
// Fill the array with paths from the ldpath
n = i = 0;
j = ldpath.indexOf(ps);
while (j >= 0) {
if (j - i > 0) {
paths[n++] = ldpath.substring(i, j);
} else if (j - i == 0) {
paths[n++] = ".";
if (ClassLoaderHelper.allowsQuotedPathElements &&
ldPath.indexOf('\"') >= 0) {
// First, remove quotes put around quoted parts of paths.
// Second, use a quotation mark as a new path separator.
// This will preserve any quoted old path separators.
char[] buf = new char[ldLen];
int bufLen = 0;
for (int i = 0; i < ldLen; ++i) {
char ch = ldPath.charAt(i);
if (ch == '\"') {
while (++i < ldLen &&
(ch = ldPath.charAt(i)) != '\"') {
buf[bufLen++] = ch;
}
} else {
if (ch == ps) {
psCount++;
ch = '\"';
}
buf[bufLen++] = ch;
}
}
ldPath = new String(buf, 0, bufLen);
ldLen = bufLen;
ps = '\"';
} else {
for (int i = ldPath.indexOf(ps); i >= 0;
i = ldPath.indexOf(ps, i + 1)) {
psCount++;
}
i = j + 1;
j = ldpath.indexOf(ps, i);
}
paths[n] = ldpath.substring(i, ldlen);
String[] paths = new String[psCount + 1];
int pathStart = 0;
for (int j = 0; j < psCount; ++j) {
int pathEnd = ldPath.indexOf(ps, pathStart);
paths[j] = (pathStart < pathEnd) ?
ldPath.substring(pathStart, pathEnd) : ".";
pathStart = pathEnd + 1;
}
paths[psCount] = (pathStart < ldLen) ?
ldPath.substring(pathStart, ldLen) : ".";
return paths;
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, 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
@ -569,7 +569,7 @@ class MulticastSocket extends DatagramSocket {
public NetworkInterface getNetworkInterface() throws SocketException {
NetworkInterface ni
= (NetworkInterface)getImpl().getOption(SocketOptions.IP_MULTICAST_IF2);
if (ni.getIndex() == 0) {
if ((ni.getIndex() == 0) || (ni.getIndex() == -1)) {
InetAddress[] addrs = new InetAddress[1];
addrs[0] = InetAddress.anyLocalAddress();
return new NetworkInterface(addrs[0].getHostName(), 0, addrs);

@ -2637,6 +2637,11 @@ public final class URI
private static final long H_URIC_NO_SLASH
= H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,");
// scope_id = alpha | digit | "_" | "."
private static final long L_SCOPE_ID
= L_ALPHANUM | lowMask("_.");
private static final long H_SCOPE_ID
= H_ALPHANUM | highMask("_.");
// -- Escaping and encoding --
@ -3226,7 +3231,7 @@ public final class URI
if (r+1 == q) {
fail ("scope id expected");
}
checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM,
checkChars (r+1, q, L_SCOPE_ID, H_SCOPE_ID,
"scope id");
} else {
parseIPv6Reference(p, q);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 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
@ -579,12 +579,13 @@ public final class Channels {
* charset and writes the resulting bytes to the given channel.
*
* <p> An invocation of this method of the form
* <p>
*
* <pre> {@code
* Channels.newWriter(ch, csname)
* } </pre>
*
* behaves in exactly the same way as the expression
* <p>
*
* <pre> {@code
* Channels.newWriter(ch, Charset.forName(csName).newEncoder(), -1)
* } </pre>

@ -1835,7 +1835,7 @@ import sun.misc.FormattedFloatingDecimal;
* <p> The maximum number of arguments is limited by the maximum dimension of a
* Java array as defined by
* <cite>The Java&trade; Virtual Machine Specification</cite>.
* If the argument index is does not correspond to an
* If the argument index does not correspond to an
* available argument, then a {@link MissingFormatArgumentException} is thrown.
*
* <p> If there are more arguments than format specifiers, the extra arguments

@ -1137,10 +1137,10 @@ public class Hashtable<K,V>
Entry<Object, Object> entryStack = null;
synchronized (this) {
// Write out the length, threshold, loadfactor
// Write out the threshold and loadFactor
s.defaultWriteObject();
// Write out length, count of elements
// Write out the length and count of elements
s.writeInt(table.length);
s.writeInt(count);
@ -1169,22 +1169,33 @@ public class Hashtable<K,V>
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the length, threshold, and loadfactor
// Read in the threshold and loadFactor
s.defaultReadObject();
// Validate loadFactor (ignore threshold - it will be re-computed)
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new StreamCorruptedException("Illegal Load: " + loadFactor);
// Read the original length of the array and number of elements
int origlength = s.readInt();
int elements = s.readInt();
// Compute new size with a bit of room 5% to grow but
// no larger than the original size. Make the length
// Validate # of elements
if (elements < 0)
throw new StreamCorruptedException("Illegal # of Elements: " + elements);
// Clamp original length to be more than elements / loadFactor
// (this is the invariant enforced with auto-growth)
origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);
// Compute new length with a bit of room 5% + 3 to grow but
// no larger than the clamped original length. Make the length
// odd if it's large enough, this helps distribute the entries.
// Guard against the length ending up zero, that's not valid.
int length = (int)(elements * loadFactor) + (elements / 20) + 3;
int length = (int)((elements + elements / 20) / loadFactor) + 3;
if (length > elements && (length & 1) == 0)
length--;
if (origlength > 0 && length > origlength)
length = origlength;
length = Math.min(length, origlength);
table = new Entry<?,?>[length];
threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
count = 0;
@ -1195,7 +1206,7 @@ public class Hashtable<K,V>
K key = (K)s.readObject();
@SuppressWarnings("unchecked")
V value = (V)s.readObject();
// synch could be eliminated for performance
// sync is eliminated for performance
reconstitutionPut(table, key, value);
}
}
@ -1207,9 +1218,9 @@ public class Hashtable<K,V>
*
* <p>This differs from the regular put method in several ways. No
* checking for rehashing is necessary since the number of elements
* initially in the table is known. The modCount is not incremented
* because we are creating a new instance. Also, no return value
* is needed.
* initially in the table is known. The modCount is not incremented and
* there's no synchronization because we are creating a new instance.
* Also, no return value is needed.
*/
private void reconstitutionPut(Entry<?,?>[] tab, K key, V value)
throws StreamCorruptedException

@ -125,7 +125,7 @@ import java.util.function.LongConsumer;
* are encountered.
*
* @apiNote
* <p>Spliterators, like {@code Iterators}s, are for traversing the elements of
* <p>Spliterators, like {@code Iterator}s, are for traversing the elements of
* a source. The {@code Spliterator} API was designed to support efficient
* parallel traversal in addition to sequential traversal, by supporting
* decomposition as well as single-element iteration. In addition, the

@ -978,7 +978,15 @@ public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
}
try {
@SuppressWarnings("unchecked") T t = (T) r;
return f.apply(t).toCompletableFuture();
CompletableFuture<V> g = f.apply(t).toCompletableFuture();
Object s = g.result;
if (s != null)
return new CompletableFuture<V>(encodeRelay(s));
CompletableFuture<V> d = new CompletableFuture<V>();
UniRelay<V> copy = new UniRelay<V>(d, g);
g.push(copy);
copy.tryFire(SYNC);
return d;
} catch (Throwable ex) {
return new CompletableFuture<V>(encodeThrowable(ex));
}

@ -337,6 +337,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
/* try auth without calling Authenticator. Used for transparent NTLM authentication */
private boolean tryTransparentNTLMServer = true;
private boolean tryTransparentNTLMProxy = true;
private boolean useProxyResponseCode = false;
/* Used by Windows specific code */
private Object authObj;
@ -2239,6 +2240,15 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (tryTransparentNTLMProxy) {
tryTransparentNTLMProxy =
NTLMAuthenticationProxy.supportsTransparentAuth;
/* If the platform supports transparent authentication
* then normally it's ok to do transparent auth to a proxy
* because we generally trust proxies (chosen by the user)
* But not in the case of 305 response where the server
* chose it. */
if (tryTransparentNTLMProxy && useProxyResponseCode) {
tryTransparentNTLMProxy = false;
}
}
a = null;
if (tryTransparentNTLMProxy) {
@ -2610,6 +2620,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
requests.set(0, method + " " + getRequestURI()+" " +
httpVersion, null);
connected = true;
// need to remember this in case NTLM proxy authentication gets
// used. We can't use transparent authentication when user
// doesn't know about proxy.
useProxyResponseCode = true;
} else {
// maintain previous headers, just change the name
// of the file we're getting

@ -192,22 +192,6 @@ final class HttpsClient extends HttpClient
return userAgent;
}
// should remove once HttpClient.newHttpProxy is putback
private static Proxy newHttpProxy(String proxyHost, int proxyPort) {
InetSocketAddress saddr = null;
final String phost = proxyHost;
final int pport = proxyPort < 0 ? httpsPortNumber : proxyPort;
try {
saddr = java.security.AccessController.doPrivileged(new
java.security.PrivilegedExceptionAction<InetSocketAddress>() {
public InetSocketAddress run() {
return new InetSocketAddress(phost, pport);
}});
} catch (java.security.PrivilegedActionException pae) {
}
return new Proxy(Proxy.Type.HTTP, saddr);
}
// CONSTRUCTOR, FACTORY
@ -251,7 +235,7 @@ final class HttpsClient extends HttpClient
throws IOException {
this(sf, url,
(proxyHost == null? null:
HttpsClient.newHttpProxy(proxyHost, proxyPort)),
HttpClient.newHttpProxy(proxyHost, proxyPort, "https")),
connectTimeout);
}
@ -261,6 +245,11 @@ final class HttpsClient extends HttpClient
HttpsClient(SSLSocketFactory sf, URL url, Proxy proxy,
int connectTimeout)
throws IOException {
PlatformLogger logger = HttpURLConnection.getHttpLogger();
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Creating new HttpsClient with url:" + url + " and proxy:" + proxy +
" with connect timeout:" + connectTimeout);
}
this.proxy = proxy;
setSSLSocketFactory(sf);
this.proxyDisabled = true;
@ -317,7 +306,7 @@ final class HttpsClient extends HttpClient
return HttpsClient.New(sf, url, hv,
(proxyHost == null? null :
HttpsClient.newHttpProxy(proxyHost, proxyPort)),
HttpClient.newHttpProxy(proxyHost, proxyPort, "https")),
useCache, connectTimeout, httpuc);
}
@ -329,6 +318,11 @@ final class HttpsClient extends HttpClient
if (p == null) {
p = Proxy.NO_PROXY;
}
PlatformLogger logger = HttpURLConnection.getHttpLogger();
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Looking for HttpClient for URL " + url +
" and proxy value of " + p);
}
HttpsClient ret = null;
if (useCache) {
/* see if one's already around */
@ -342,14 +336,13 @@ final class HttpsClient extends HttpClient
if (ret != null) {
if ((ret.proxy != null && ret.proxy.equals(p)) ||
(ret.proxy == null && p == null)) {
(ret.proxy == null && p == Proxy.NO_PROXY)) {
synchronized (ret) {
ret.cachedHttpClient = true;
assert ret.inCache;
ret.inCache = false;
if (httpuc != null && ret.needsTunneling())
httpuc.setTunnelState(TUNNELING);
PlatformLogger logger = HttpURLConnection.getHttpLogger();
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("KeepAlive stream retrieved from the cache, " + ret);
}
@ -360,6 +353,9 @@ final class HttpsClient extends HttpClient
// This should be fine as it is very rare that a connection
// to the same host will not use the same proxy.
synchronized(ret) {
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Not returning this connection to cache: " + ret);
}
ret.inCache = false;
ret.closeServer();
}

@ -0,0 +1,159 @@
/*
* Copyright (c) 2014, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package sun.security.provider;
import java.io.*;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A pool of {@code InputStream}s opened from distinct files. Only a single
* instance is ever opened from the same file. This is used to read special
* infinite files like {@code /dev/random} where the current file pointer is not
* relevant, so multiple readers can share the same file descriptor and
* consequently the same {@code InputStream}.
*/
class FileInputStreamPool {
/**
* a pool of: StreamRef -> UnclosableInputStream -> FileInputStream(s)
*/
private static final ConcurrentMap<File, StreamRef> pool =
new ConcurrentHashMap<>();
/**
* a reference queue of cleared StreamRef(s)
*/
private static final ReferenceQueue<UnclosableInputStream> refQueue =
new ReferenceQueue<>();
/**
* This method opens an underlying {@link java.io.FileInputStream} for a
* given {@code file} and returns a wrapper over it. The wrapper is shared
* among multiple readers of the same {@code file} and ignores
* {@link java.io.InputStream#close()} requests. The underlying stream is
* closed when all references to the wrapper are relinquished.
*
* @param file the file to be opened for reading.
* @return a shared {@link java.io.InputStream} instance opened from given
* file.
* @throws FileNotFoundException if the file does not exist, is a directory
* rather than a regular file, or for some
* other reason cannot be opened for reading.
* @throws SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read
* access to the file.
*/
static InputStream getInputStream(File file) throws IOException {
// expunge any cleared references
StreamRef oldRref;
while ((oldRref = (StreamRef) refQueue.poll()) != null) {
pool.remove(oldRref.file, oldRref);
}
// canonicalize the path
// (this also checks the read permission on the file if SecurityManager
// is present, so no checking is needed later when we just return the
// already opened stream)
File cfile = file.getCanonicalFile();
// check if it exists in pool
oldRref = pool.get(cfile);
UnclosableInputStream oldStream = (oldRref == null)
? null
: oldRref.get();
StreamRef newRef = null;
UnclosableInputStream newStream = null;
// retry loop
while (true) {
if (oldStream != null) {
// close our optimistically opened stream 1st (if we opened it)
if (newStream != null) {
try {
newStream.getWrappedStream().close();
} catch (IOException ignore) {
// can't do anything here
}
}
// return it
return oldStream;
} else {
// we need to open new stream optimistically (if not already)
if (newStream == null) {
newStream = new UnclosableInputStream(
new FileInputStream(cfile));
newRef = new StreamRef(cfile, newStream, refQueue);
}
// either try to install newRef or replace oldRef with newRef
if (oldRref == null) {
oldRref = pool.putIfAbsent(cfile, newRef);
} else {
oldRref = pool.replace(cfile, oldRref, newRef)
? null
: pool.get(cfile);
}
if (oldRref == null) {
// success
return newStream;
} else {
// lost race
oldStream = oldRref.get();
// another loop
}
}
}
}
private static class StreamRef extends WeakReference<UnclosableInputStream> {
final File file;
StreamRef(File file,
UnclosableInputStream stream,
ReferenceQueue<UnclosableInputStream> refQueue) {
super(stream, refQueue);
this.file = file;
}
}
private static final class UnclosableInputStream extends FilterInputStream {
UnclosableInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
// Ignore close attempts since underlying InputStream is shared.
}
InputStream getWrappedStream() {
return in;
}
}
}

@ -504,9 +504,10 @@ abstract class SeedGenerator {
@Override
public InputStream run() throws IOException {
/*
* return a FileInputStream for file URLs and
* avoid buffering. The openStream() call wraps
* InputStream in a BufferedInputStream which
* return a shared InputStream for file URLs and
* avoid buffering.
* The URL.openStream() call wraps InputStream in a
* BufferedInputStream which
* can buffer up to 8K bytes. This read is a
* performance issue for entropy sources which
* can be slow to replenish.
@ -514,7 +515,8 @@ abstract class SeedGenerator {
if (device.getProtocol().equalsIgnoreCase("file")) {
File deviceFile =
SunEntries.getDeviceFile(device);
return new FileInputStream(deviceFile);
return FileInputStreamPool
.getInputStream(deviceFile);
} else {
return device.openStream();
}

@ -345,6 +345,13 @@ final class ClientHandshaker extends Handshaker {
break;
case HandshakeMessage.ht_finished:
// A ChangeCipherSpec record must have been received prior to
// reception of the Finished message (RFC 5246, 7.4.9).
if (!receivedChangeCipherSpec()) {
fatalSE(Alerts.alert_handshake_failure,
"Received Finished message before ChangeCipherSpec");
}
this.serverFinished(
new Finished(protocolVersion, input, cipherSuite));
break;

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 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
@ -243,6 +243,7 @@ static final class ClientHello extends HandshakeMessage {
protocolVersion = ProtocolVersion.valueOf(s.getInt8(), s.getInt8());
clnt_random = new RandomCookie(s);
sessionId = new SessionId(s.getBytes8());
sessionId.checkLength(protocolVersion);
cipherSuites = new CipherSuiteList(s);
compression_methods = s.getBytes8();
if (messageLength() != messageLength) {
@ -355,6 +356,7 @@ class ServerHello extends HandshakeMessage
input.getInt8());
svr_random = new RandomCookie(input);
sessionId = new SessionId(input.getBytes8());
sessionId.checkLength(protocolVersion);
cipherSuite = CipherSuite.valueOf(input.getInt8(), input.getInt8());
compression_method = (byte)input.getInt8();
if (messageLength() != messageLength) {

@ -94,8 +94,6 @@ abstract class Handshaker {
// Peer supported signature and algorithms
Collection<SignatureAndHashAlgorithm> peerSupportedSignAlgs;
/*
/*
* List of active protocols
*
@ -114,10 +112,8 @@ abstract class Handshaker {
private CipherSuiteList activeCipherSuites;
// The server name indication and matchers
List<SNIServerName> serverNames =
Collections.<SNIServerName>emptyList();
Collection<SNIMatcher> sniMatchers =
Collections.<SNIMatcher>emptyList();
List<SNIServerName> serverNames = Collections.<SNIServerName>emptyList();
Collection<SNIMatcher> sniMatchers = Collections.<SNIMatcher>emptyList();
private boolean isClient;
private boolean needCertVerify;
@ -139,12 +135,16 @@ abstract class Handshaker {
// current key exchange. Never null, initially K_NULL
KeyExchange keyExchange;
/* True if this session is being resumed (fast handshake) */
// True if this session is being resumed (fast handshake)
boolean resumingSession;
/* True if it's OK to start a new SSL session */
// True if it's OK to start a new SSL session
boolean enableNewSession;
// True if session keys have been calculated and the caller may receive
// and process a ChangeCipherSpec message
private boolean sessKeysCalculated;
// Whether local cipher suites preference should be honored during
// handshaking?
//
@ -253,6 +253,7 @@ abstract class Handshaker {
this.serverVerifyData = serverVerifyData;
enableNewSession = true;
invalidated = false;
sessKeysCalculated = false;
setCipherSuite(CipherSuite.C_NULL);
setEnabledProtocols(enabledProtocols);
@ -359,6 +360,14 @@ abstract class Handshaker {
}
}
final boolean receivedChangeCipherSpec() {
if (conn != null) {
return conn.receivedChangeCipherSpec();
} else {
return engine.receivedChangeCipherSpec();
}
}
String getEndpointIdentificationAlgorithmSE() {
SSLParameters paras;
if (conn != null) {
@ -491,7 +500,9 @@ abstract class Handshaker {
if (activeProtocols.collection().isEmpty() ||
activeProtocols.max.v == ProtocolVersion.NONE.v) {
throw new SSLHandshakeException("No appropriate protocol");
throw new SSLHandshakeException(
"No appropriate protocol (protocol is disabled or " +
"cipher suites are inappropriate)");
}
if (activeCipherSuites == null) {
@ -676,6 +687,17 @@ abstract class Handshaker {
continue;
}
if (!algorithmConstraints.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
protocol.name, null)) {
if (debug != null && Debug.isOn("verbose")) {
System.out.println(
"Ignoring disabled protocol: " + protocol);
}
continue;
}
boolean found = false;
for (CipherSuite suite : enabledCipherSuites.collection()) {
if (suite.isAvailable() && suite.obsoleted > protocol.v &&
@ -1081,7 +1103,6 @@ abstract class Handshaker {
calculateConnectionKeys(master);
}
/*
* Calculate the master secret from its various components. This is
* used for key exchange by all cipher suites.
@ -1226,6 +1247,10 @@ abstract class Handshaker {
throw new ProviderException(e);
}
// Mark a flag that allows outside entities (like SSLSocket/SSLEngine)
// determine if a ChangeCipherSpec message could be processed.
sessKeysCalculated = true;
//
// Dump the connection keys as they're generated.
//
@ -1280,6 +1305,15 @@ abstract class Handshaker {
}
}
/**
* Return whether or not the Handshaker has derived session keys for
* this handshake. This is used for determining readiness to process
* an incoming ChangeCipherSpec message.
*/
boolean sessionKeysCalculated() {
return sessKeysCalculated;
}
private static void printHex(HexDumpEncoder dump, byte[] bytes) {
if (bytes == null) {
System.out.println("(key bytes not available)");

@ -25,6 +25,9 @@
package sun.security.ssl;
import java.util.*;
import java.security.CryptoPrimitive;
/**
* Type safe enum for an SSL/TLS protocol version. Instances are obtained
* using the static factory methods or by referencing the static members
@ -86,6 +89,11 @@ public final class ProtocolVersion implements Comparable<ProtocolVersion> {
// Default version for hello messages (SSLv2Hello)
final static ProtocolVersion DEFAULT_HELLO = FIPS ? TLS10 : SSL30;
// Available protocols
//
// Including all supported protocols except the disabled ones.
final static Set<ProtocolVersion> availableProtocols;
// version in 16 bit MSB format as it appears in records and
// messages, i.e. 0x0301 for TLS 1.0
public final int v;
@ -96,6 +104,25 @@ public final class ProtocolVersion implements Comparable<ProtocolVersion> {
// name used in JSSE (e.g. TLSv1 for TLS 1.0)
final String name;
// Initialize the available protocols.
static {
Set<ProtocolVersion> protocols = new HashSet<>(5);
ProtocolVersion[] pvs = new ProtocolVersion[] {
SSL20Hello, SSL30, TLS10, TLS11, TLS12};
EnumSet<CryptoPrimitive> cryptoPrimitives =
EnumSet.<CryptoPrimitive>of(CryptoPrimitive.KEY_AGREEMENT);
for (ProtocolVersion p : pvs) {
if (SSLAlgorithmConstraints.DEFAULT_SSL_ONLY.permits(
cryptoPrimitives, p.name, null)) {
protocols.add(p);
}
}
availableProtocols =
Collections.<ProtocolVersion>unmodifiableSet(protocols);
}
// private
private ProtocolVersion(int v, String name) {
this.v = v;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2014, 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
@ -55,6 +55,14 @@ final class SSLAlgorithmConstraints implements AlgorithmConstraints {
private boolean enabledX509DisabledAlgConstraints = true;
// the default algorithm constraints
final static AlgorithmConstraints DEFAULT =
new SSLAlgorithmConstraints(null);
// the default SSL only algorithm constraints
final static AlgorithmConstraints DEFAULT_SSL_ONLY =
new SSLAlgorithmConstraints((SSLSocket)null, false);
SSLAlgorithmConstraints(AlgorithmConstraints algorithmConstraints) {
userAlgConstraints = algorithmConstraints;
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2014, 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
@ -52,10 +52,6 @@ public abstract class SSLContextImpl extends SSLContextSpi {
private X509TrustManager trustManager;
private SecureRandom secureRandom;
// The default algrithm constraints
private AlgorithmConstraints defaultAlgorithmConstraints =
new SSLAlgorithmConstraints(null);
// supported and default protocols
private ProtocolList defaultServerProtocolList;
private ProtocolList defaultClientProtocolList;
@ -350,7 +346,7 @@ public abstract class SSLContextImpl extends SSLContextSpi {
if (suite.isAvailable() &&
suite.obsoleted > protocols.min.v &&
suite.supported <= protocols.max.v) {
if (defaultAlgorithmConstraints.permits(
if (SSLAlgorithmConstraints.DEFAULT.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
suite.name, null)) {
suites.add(suite);
@ -431,11 +427,16 @@ public abstract class SSLContextImpl extends SSLContextSpi {
*/
private abstract static class AbstractSSLContext extends SSLContextImpl {
// parameters
private final static SSLParameters defaultServerSSLParams;
private final static SSLParameters supportedSSLParams;
private static final SSLParameters defaultServerSSLParams;
private static final SSLParameters supportedSSLParams;
static {
// supported SSL parameters
supportedSSLParams = new SSLParameters();
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
supportedSSLParams.setProtocols(new String[] {
ProtocolVersion.TLS10.name,
@ -443,7 +444,11 @@ public abstract class SSLContextImpl extends SSLContextSpi {
ProtocolVersion.TLS12.name
});
defaultServerSSLParams = supportedSSLParams;
candidates = new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
} else {
supportedSSLParams.setProtocols(new String[] {
ProtocolVersion.SSL20Hello.name,
@ -453,8 +458,18 @@ public abstract class SSLContextImpl extends SSLContextSpi {
ProtocolVersion.TLS12.name
});
defaultServerSSLParams = supportedSSLParams;
candidates = new ProtocolVersion[] {
ProtocolVersion.SSL20Hello,
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}
defaultServerSSLParams = new SSLParameters();
defaultServerSSLParams.setProtocols(
getAvailableProtocols(candidates));
}
@Override
@ -466,6 +481,22 @@ public abstract class SSLContextImpl extends SSLContextSpi {
SSLParameters getSupportedSSLParams() {
return supportedSSLParams;
}
static String[] getAvailableProtocols(
ProtocolVersion[] protocolCandidates) {
List<String> availableProtocols = Collections.<String>emptyList();
if (protocolCandidates != null && protocolCandidates.length != 0) {
availableProtocols = new ArrayList<>(protocolCandidates.length);
for (ProtocolVersion p : protocolCandidates) {
if (ProtocolVersion.availableProtocols.contains(p)) {
availableProtocols.add(p.name);
}
}
}
return availableProtocols.toArray(new String[0]);
}
}
/*
@ -474,21 +505,25 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS10Context extends AbstractSSLContext {
private final static SSLParameters defaultClientSSLParams;
private static final SSLParameters defaultClientSSLParams;
static {
defaultClientSSLParams = new SSLParameters();
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.TLS10.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.TLS10
};
} else {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.SSL30.name,
ProtocolVersion.TLS10.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10
};
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
}
@Override
@ -503,23 +538,27 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS11Context extends AbstractSSLContext {
private final static SSLParameters defaultClientSSLParams;
private static final SSLParameters defaultClientSSLParams;
static {
defaultClientSSLParams = new SSLParameters();
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11
};
} else {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.SSL30.name,
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11
};
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
}
@Override
@ -534,25 +573,29 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS12Context extends AbstractSSLContext {
private final static SSLParameters defaultClientSSLParams;
private static final SSLParameters defaultClientSSLParams;
static {
defaultClientSSLParams = new SSLParameters();
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name,
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
} else {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.SSL30.name,
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name,
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
}
@Override
@ -567,8 +610,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
private static class CustomizedSSLContext extends AbstractSSLContext {
private final static String PROPERTY_NAME = "jdk.tls.client.protocols";
private final static SSLParameters defaultClientSSLParams;
private static final String PROPERTY_NAME = "jdk.tls.client.protocols";
private static final SSLParameters defaultClientSSLParams;
private static IllegalArgumentException reservedException = null;
// Don't want a java.lang.LinkageError for illegal system property.
@ -578,60 +621,74 @@ public abstract class SSLContextImpl extends SSLContextSpi {
// the provider service. Instead, let's handle the initialization
// exception in constructor.
static {
// candidates for available protocols
ProtocolVersion[] candidates;
String property = AccessController.doPrivileged(
new GetPropertyAction(PROPERTY_NAME));
defaultClientSSLParams = new SSLParameters();
if (property == null || property.length() == 0) {
// the default enabled client TLS protocols
if (SunJSSE.isFIPS()) {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name,
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
} else {
defaultClientSSLParams.setProtocols(new String[] {
ProtocolVersion.SSL30.name,
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name,
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}
} else {
// remove double quote marks from beginning/end of the property
if (property.charAt(0) == '"' &&
if (property.length() > 1 && property.charAt(0) == '"' &&
property.charAt(property.length() - 1) == '"') {
property = property.substring(1, property.length() - 1);
}
String[] protocols = property.split(",");
String[] protocols = null;
if (property != null && property.length() != 0) {
protocols = property.split(",");
} else {
reservedException = new IllegalArgumentException(
"No protocol specified in " +
PROPERTY_NAME + " system property");
protocols = new String[0];
}
candidates = new ProtocolVersion[protocols.length];
for (int i = 0; i < protocols.length; i++) {
protocols[i] = protocols[i].trim();
// Is it a supported protocol name?
try {
ProtocolVersion.valueOf(protocols[i]);
candidates[i] = ProtocolVersion.valueOf(protocols[i]);
} catch (IllegalArgumentException iae) {
reservedException = new IllegalArgumentException(
PROPERTY_NAME + ": " + protocols[i] +
" is not a standard SSL protocol name", iae);
PROPERTY_NAME + ": " + protocols[i] +
" is not a standard SSL/TLS protocol name", iae);
break;
}
}
if ((reservedException == null) && SunJSSE.isFIPS()) {
for (String protocol : protocols) {
if (ProtocolVersion.SSL20Hello.name.equals(protocol) ||
ProtocolVersion.SSL30.name.equals(protocol)) {
for (ProtocolVersion protocolVersion : candidates) {
if (ProtocolVersion.SSL20Hello.v == protocolVersion.v ||
ProtocolVersion.SSL30.v == protocolVersion.v) {
reservedException = new IllegalArgumentException(
PROPERTY_NAME + ": " + protocol +
PROPERTY_NAME + ": " + protocolVersion +
" is not FIPS compliant");
}
}
}
}
if (reservedException == null) {
defaultClientSSLParams.setProtocols(protocols);
}
defaultClientSSLParams = new SSLParameters();
if (reservedException == null) {
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, 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
@ -211,6 +211,11 @@ final public class SSLEngineImpl extends SSLEngine {
static final byte clauth_requested = 1;
static final byte clauth_required = 2;
/*
* Flag indicating that the engine has received a ChangeCipherSpec message.
*/
private boolean receivedCCS;
/*
* Flag indicating if the next record we receive MUST be a Finished
* message. Temporarily set during the handshake to ensure that
@ -372,6 +377,7 @@ final public class SSLEngineImpl extends SSLEngine {
*/
roleIsServer = true;
connectionState = cs_START;
receivedCCS = false;
// default server name indication
serverNames =
@ -1021,6 +1027,7 @@ final public class SSLEngineImpl extends SSLEngine {
if (handshaker.invalidated) {
handshaker = null;
receivedCCS = false;
// if state is cs_RENEGOTIATE, revert it to cs_DATA
if (connectionState == cs_RENEGOTIATE) {
connectionState = cs_DATA;
@ -1039,6 +1046,7 @@ final public class SSLEngineImpl extends SSLEngine {
}
handshaker = null;
connectionState = cs_DATA;
receivedCCS = false;
// No handshakeListeners here. That's a
// SSLSocket thing.
@ -1078,13 +1086,25 @@ final public class SSLEngineImpl extends SSLEngine {
case Record.ct_change_cipher_spec:
if ((connectionState != cs_HANDSHAKE
&& connectionState != cs_RENEGOTIATE)
|| inputRecord.available() != 1
|| inputRecord.read() != 1) {
|| !handshaker.sessionKeysCalculated()
|| receivedCCS) {
// For the CCS message arriving in the wrong state
fatal(Alerts.alert_unexpected_message,
"illegal change cipher spec msg, state = "
+ connectionState);
"illegal change cipher spec msg, conn state = "
+ connectionState + ", handshake state = "
+ handshaker.state);
} else if (inputRecord.available() != 1
|| inputRecord.read() != 1) {
// For structural/content issues with the CCS
fatal(Alerts.alert_unexpected_message,
"Malformed change cipher spec msg");
}
// Once we've received CCS, update the flag.
// If the remote endpoint sends it again in this handshake
// we won't process it.
receivedCCS = true;
//
// The first message after a change_cipher_spec
// record MUST be a "Finished" handshake record,
@ -2120,6 +2140,14 @@ final public class SSLEngineImpl extends SSLEngine {
}
}
/**
* Returns a boolean indicating whether the ChangeCipherSpec message
* has been received for this handshake.
*/
boolean receivedChangeCipherSpec() {
return receivedCCS;
}
/**
* Returns a printable representation of this end of the connection.
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, 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
@ -171,6 +171,12 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
*/
private volatile int connectionState;
/*
* Flag indicating that the engine's handshaker has done the necessary
* steps so the engine may process a ChangeCipherSpec message.
*/
private boolean receivedCCS;
/*
* Flag indicating if the next record we receive MUST be a Finished
* message. Temporarily set during the handshake to ensure that
@ -587,6 +593,7 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
*/
roleIsServer = isServer;
connectionState = cs_START;
receivedCCS = false;
/*
* default read and write side cipher and MAC support
@ -1045,6 +1052,7 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
if (handshaker.invalidated) {
handshaker = null;
receivedCCS = false;
// if state is cs_RENEGOTIATE, revert it to cs_DATA
if (connectionState == cs_RENEGOTIATE) {
connectionState = cs_DATA;
@ -1060,6 +1068,7 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
handshakeSession = null;
handshaker = null;
connectionState = cs_DATA;
receivedCCS = false;
//
// Tell folk about handshake completion, but do
@ -1107,13 +1116,24 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
case Record.ct_change_cipher_spec:
if ((connectionState != cs_HANDSHAKE
&& connectionState != cs_RENEGOTIATE)
|| r.available() != 1
|| r.read() != 1) {
|| !handshaker.sessionKeysCalculated()
|| receivedCCS) {
// For the CCS message arriving in the wrong state
fatal(Alerts.alert_unexpected_message,
"illegal change cipher spec msg, state = "
+ connectionState);
"illegal change cipher spec msg, conn state = "
+ connectionState + ", handshake state = "
+ handshaker.state);
} else if (r.available() != 1 || r.read() != 1) {
// For structural/content issues with the CCS
fatal(Alerts.alert_unexpected_message,
"Malformed change cipher spec msg");
}
// Once we've received CCS, update the flag.
// If the remote endpoint sends it again in this handshake
// we won't process it.
receivedCCS = true;
//
// The first message after a change_cipher_spec
// record MUST be a "Finished" handshake record,
@ -2589,6 +2609,14 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl {
}
}
/**
* Returns a boolean indicating whether the ChangeCipherSpec message
* has been received for this handshake.
*/
boolean receivedChangeCipherSpec() {
return receivedCCS;
}
/**
* Returns a printable representation of this end of the connection.
*/

@ -287,6 +287,13 @@ final class ServerHandshaker extends Handshaker {
break;
case HandshakeMessage.ht_finished:
// A ChangeCipherSpec record must have been received prior to
// reception of the Finished message (RFC 5246, 7.4.9).
if (!receivedChangeCipherSpec()) {
fatalSE(Alerts.alert_handshake_failure,
"Received Finished message before ChangeCipherSpec");
}
this.clientFinished(
new Finished(protocolVersion, input, cipherSuite));
break;

@ -27,6 +27,7 @@
package sun.security.ssl;
import java.security.SecureRandom;
import javax.net.ssl.SSLProtocolException;
/**
* Encapsulates an SSL session ID. SSL Session IDs are not reused by
@ -41,6 +42,7 @@ import java.security.SecureRandom;
final
class SessionId
{
static int MAX_LENGTH = 32;
private byte sessionId []; // max 32 bytes
/** Constructs a new session ID ... perhaps for a rejoinable session */
@ -114,4 +116,19 @@ class SessionId
}
return true;
}
/**
* Checks the length of the session ID to make sure it sits within
* the range called out in the specification
*/
void checkLength(ProtocolVersion pv) throws SSLProtocolException {
// As of today all versions of TLS have a 32-byte maximum length.
// In the future we can do more here to support protocol versions
// that may have longer max lengths.
if (sessionId.length > MAX_LENGTH) {
throw new SSLProtocolException("Invalid session ID length (" +
sessionId.length + " bytes)");
}
}
}

@ -156,12 +156,18 @@ class DerIndefLenConverter {
}
if (isLongForm(lenByte)) {
lenByte &= LEN_MASK;
if (lenByte > 4)
if (lenByte > 4) {
throw new IOException("Too much data");
if ((dataSize - dataPos) < (lenByte + 1))
}
if ((dataSize - dataPos) < (lenByte + 1)) {
throw new IOException("Too little data");
for (int i = 0; i < lenByte; i++)
}
for (int i = 0; i < lenByte; i++) {
curLen = (curLen << 8) + (data[dataPos++] & 0xff);
}
if (curLen < 0) {
throw new IOException("Invalid length bytes");
}
} else {
curLen = (lenByte & LEN_MASK);
}
@ -188,10 +194,15 @@ class DerIndefLenConverter {
}
if (isLongForm(lenByte)) {
lenByte &= LEN_MASK;
for (int i = 0; i < lenByte; i++)
for (int i = 0; i < lenByte; i++) {
curLen = (curLen << 8) + (data[dataPos++] & 0xff);
} else
}
if (curLen < 0) {
throw new IOException("Invalid length bytes");
}
} else {
curLen = (lenByte & LEN_MASK);
}
writeLength(curLen);
writeValue(curLen);
}

@ -577,6 +577,10 @@ public class DerInputStream {
value <<= 8;
value += 0x0ff & in.read();
}
if (value < 0) {
throw new IOException("DerInputStream.getLength(): "
+ "Invalid length bytes");
}
}
return value;
}

@ -512,8 +512,12 @@ jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
#
# In some environments, certain algorithms or key lengths may be undesirable
# when using SSL/TLS. This section describes the mechanism for disabling
# algorithms during SSL/TLS security parameters negotiation, including cipher
# suites selection, peer authentication and key exchange mechanisms.
# algorithms during SSL/TLS security parameters negotiation, including
# protocol version negotiation, cipher suites selection, peer authentication
# and key exchange mechanisms.
#
# Disabled algorithms will not be negotiated for SSL/TLS connections, even
# if they are enabled explicitly in an application.
#
# For PKI-based peer authentication and key exchange mechanisms, this list
# of disabled algorithms will also be checked during certification path
@ -528,4 +532,5 @@ jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
# It is not guaranteed to be examined and used by other implementations.
#
# Example:
# jdk.tls.disabledAlgorithms=MD5, SHA1, DSA, RSA keySize < 2048
# jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
jdk.tls.disabledAlgorithms=SSLv3

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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
@ -30,6 +30,11 @@ class ClassLoaderHelper {
private ClassLoaderHelper() {}
/**
* Indicates, whether PATH env variable is allowed to contain quoted entries.
*/
static final boolean allowsQuotedPathElements = false;
/**
* Returns an alternate path name for the given file
* such that if the original pathname did not exist, then the

@ -371,8 +371,8 @@ public final class NativePRNG extends SecureRandomSpi {
// constructor, called only once from initIO()
private RandomIO(File seedFile, File nextFile) throws IOException {
this.seedFile = seedFile;
seedIn = new FileInputStream(seedFile);
nextIn = new FileInputStream(nextFile);
seedIn = FileInputStreamPool.getInputStream(seedFile);
nextIn = FileInputStreamPool.getInputStream(nextFile);
nextBuffer = new byte[BUFFER_SIZE];
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2014, 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
@ -274,7 +274,6 @@ JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
if (index <= 0) {
return NULL;
}
ifs = enumInterfaces(env);
if (ifs == NULL) {
return NULL;
@ -551,9 +550,14 @@ JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0(JNIEnv *env, jclas
jboolean isCopy;
int ret = -1;
int sock;
const char* name_utf;
const char* name_utf = NULL;
name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
if (name != NULL) {
name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
} else {
JNU_ThrowNullPointerException(env, "network interface name is NULL");
return ret;
}
if (name_utf == NULL) {
if (!(*env)->ExceptionCheck(env))
JNU_ThrowOutOfMemoryError(env, NULL);
@ -581,7 +585,13 @@ static int getFlags0(JNIEnv *env, jstring name) {
const char* name_utf;
int flags = 0;
name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
if (name != NULL) {
name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
} else {
JNU_ThrowNullPointerException(env, "network interface name is NULL");
return -1;
}
if (name_utf == NULL) {
if (!(*env)->ExceptionCheck(env))
JNU_ThrowOutOfMemoryError(env, NULL);
@ -1063,6 +1073,7 @@ static int openSocket(JNIEnv *env, int proto){
*/
#ifdef AF_INET6
// unused arg ifname and struct if2
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
int sock;
struct ifreq if2;
@ -1453,9 +1464,14 @@ static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct
static int getMTU(JNIEnv *env, int sock, const char *ifname) {
struct ifreq if2;
memset((char *) &if2, 0, sizeof(if2));
strcpy(if2.ifr_name, ifname);
if (ifname != NULL) {
strcpy(if2.ifr_name, ifname);
} else {
JNU_ThrowNullPointerException(env, "network interface name is NULL");
return -1;
}
if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, 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
@ -62,7 +62,6 @@
#include "jvm.h"
#include "jni_util.h"
#include "net_util.h"
#include "java_net_SocketOptions.h"
#include "java_net_PlainDatagramSocketImpl.h"
#include "java_net_NetworkInterface.h"
@ -83,6 +82,7 @@ static jfieldID pdsi_connectedPort;
extern void setDefaultScopeID(JNIEnv *env, struct sockaddr *him);
extern int getDefaultScopeID(JNIEnv *env);
/*
* Returns a java.lang.Integer based on 'i'
*/
@ -1447,10 +1447,12 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
static jmethodID ni_ctrID;
static jfieldID ni_indexID;
static jfieldID ni_addrsID;
static jfieldID ni_nameID;
jobjectArray addrArray;
jobject addr;
jobject ni;
jobject ni_name;
struct in_addr in;
struct in_addr *inP = &in;
@ -1500,6 +1502,8 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
ni_addrsID = (*env)->GetFieldID(env, c, "addrs",
"[Ljava/net/InetAddress;");
CHECK_NULL_RETURN(ni_addrsID, NULL);
ni_nameID = (*env)->GetFieldID(env, c,"name", "Ljava/lang/String;");
CHECK_NULL_RETURN(ni_nameID, NULL);
ni_class = (*env)->NewGlobalRef(env, c);
CHECK_NULL_RETURN(ni_class, NULL);
}
@ -1521,6 +1525,10 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
CHECK_NULL_RETURN(addrArray, NULL);
(*env)->SetObjectArrayElement(env, addrArray, 0, addr);
(*env)->SetObjectField(env, ni, ni_addrsID, addrArray);
ni_name = (*env)->NewStringUTF(env, "");
if (ni_name != NULL) {
(*env)->SetObjectField(env, ni, ni_nameID, ni_name);
}
return ni;
}
@ -1537,14 +1545,16 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
static jfieldID ni_indexID;
static jfieldID ni_addrsID;
static jclass ia_class;
static jfieldID ni_nameID;
static jmethodID ia_anyLocalAddressID;
int index;
int index = 0;
socklen_t len = sizeof(index);
jobjectArray addrArray;
jobject addr;
jobject ni;
jobject ni_name;
if (getsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
(char*)&index, &len) < 0) {
@ -1573,6 +1583,8 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
"anyLocalAddress",
"()Ljava/net/InetAddress;");
CHECK_NULL_RETURN(ia_anyLocalAddressID, NULL);
ni_nameID = (*env)->GetFieldID(env, c,"name", "Ljava/lang/String;");
CHECK_NULL_RETURN(ni_nameID, NULL);
ni_class = (*env)->NewGlobalRef(env, c);
CHECK_NULL_RETURN(ni_class, NULL);
}
@ -1633,6 +1645,10 @@ jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
CHECK_NULL_RETURN(addrArray, NULL);
(*env)->SetObjectArrayElement(env, addrArray, 0, addr);
(*env)->SetObjectField(env, ni, ni_addrsID, addrArray);
ni_name = (*env)->NewStringUTF(env, "");
if (ni_name != NULL) {
(*env)->SetObjectField(env, ni, ni_nameID, ni_name);
}
return ni;
}
#endif

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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
@ -30,6 +30,11 @@ class ClassLoaderHelper {
private ClassLoaderHelper() {}
/**
* Indicates, whether PATH env variable is allowed to contain quoted entries.
*/
static final boolean allowsQuotedPathElements = true;
/**
* Returns an alternate path name for the given file
* such that if the original pathname did not exist, then the

@ -283,14 +283,10 @@ static jlong processCreate(
FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE};
{
/* Extraction of current process standard IOE handles */
DWORD idsIOE[3] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE};
int i;
for (i = 0; i < 3; ++i)
/* Should not be closed by CloseHandle! */
stdIOE[i] = GetStdHandle(idsIOE[i]);
}
/* These three should not be closed by CloseHandle! */
stdIOE[0] = GetStdHandle(STD_INPUT_HANDLE);
stdIOE[1] = GetStdHandle(STD_OUTPUT_HANDLE);
stdIOE[2] = GetStdHandle(STD_ERROR_HANDLE);
prepareIOEHandleState(stdIOE, inherit);
{
@ -319,11 +315,16 @@ static jlong processCreate(
if (success) {
PROCESS_INFORMATION pi;
DWORD processFlag = CREATE_UNICODE_ENVIRONMENT;
DWORD processFlag = CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT;
/* Suppress popping-up of a console window for non-console applications */
if (GetConsoleWindow() == NULL)
processFlag |= CREATE_NO_WINDOW;
/* If the standard I/O is inherited, CREATE_NO_WINDOW must not be used. */
if (GetConsoleWindow() != NULL &&
(si.hStdInput == stdIOE[0] ||
si.hStdOutput == stdIOE[1] ||
si.hStdError == (redirectErrorStream ? stdIOE[1] : stdIOE[2])))
{
processFlag &= ~CREATE_NO_WINDOW;
}
si.dwFlags = STARTF_USESTDHANDLES;
if (!CreateProcessW(

@ -248,7 +248,8 @@ public class WindowsButtonUI extends BasicButtonUI
Part part = getXPButtonType(b);
if (b.isContentAreaFilled() && xp != null) {
if (b.isContentAreaFilled() && b.getBorder() != null
&& b.isBorderPainted() && xp != null) {
Skin skin = xp.getSkin(b, part);

@ -1081,16 +1081,9 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
directories.clear();
File[] baseFolders;
if (useShellFolder) {
baseFolders = AccessController.doPrivileged(new PrivilegedAction<File[]>() {
public File[] run() {
return (File[]) ShellFolder.get("fileChooserComboBoxFolders");
}
});
} else {
baseFolders = fsv.getRoots();
}
File[] baseFolders = (useShellFolder)
? (File[]) ShellFolder.get("fileChooserComboBoxFolders")
: fsv.getRoots();
directories.addAll(Arrays.asList(baseFolders));
// Get the canonical (full) path. This has the side

@ -1,5 +1,5 @@
<!--
Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
Copyright (c) 1998, 2014, 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
@ -147,8 +147,8 @@ you register it using the
For overview, architecture, and tutorial documentation, please see:
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/javabeans/">JavaBeans</a>, a trail in <em>The Java Tutorial</em>.
<li><a href="http://java.sun.com/products/jfc/tsc/articles/persistence2/">Long-Term Persistence</a>, an article in <em>The Swing Connection</em>.
<li><a href="http://docs.oracle.com/javase/tutorial/javabeans/">JavaBeans</a>, a trail in <em>The Java Tutorial</em>.
<li><a href="http://www.oracle.com/technetwork/java/persistence2-141443.html">Long-Term Persistence</a>, an article in <em>The Swing Connection</em>.
</ul>
</body>

@ -28,6 +28,7 @@ package javax.swing;
import java.awt.event.*;
import java.awt.*;
import java.util.Objects;
/**
* Manages all the <code>ToolTips</code> in the system.
@ -476,8 +477,8 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener
preferredLocation.equals(newPreferredLocation) :
(newPreferredLocation == null);
if (!sameComponent || !toolTipText.equals(newToolTipText) ||
!sameLoc) {
if (!sameComponent || !Objects.equals(toolTipText, newToolTipText)
|| !sameLoc) {
toolTipText = newToolTipText;
preferredLocation = newPreferredLocation;
showTipWindow();

@ -44,9 +44,7 @@ import java.awt.Font;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Dimension;
import java.lang.reflect.Method;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
@ -76,7 +74,7 @@ import sun.util.CoreResourceBundleControl;
@SuppressWarnings("serial") // Same-version serialization only
public class UIDefaults extends Hashtable<Object,Object>
{
private static final Object PENDING = "Pending";
private static final Object PENDING = new Object();
private SwingPropertyChangeSupport changeSupport;
@ -170,7 +168,7 @@ public class UIDefaults extends Hashtable<Object,Object>
* Looks up the given key in our Hashtable and resolves LazyValues
* or ActiveValues.
*/
private Object getFromHashtable(Object key) {
private Object getFromHashtable(final Object key) {
/* Quickly handle the common case, without grabbing
* a lock.
*/

@ -1020,16 +1020,9 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
directories.clear();
File[] baseFolders;
if (useShellFolder) {
baseFolders = AccessController.doPrivileged(new PrivilegedAction<File[]>() {
public File[] run() {
return (File[]) ShellFolder.get("fileChooserComboBoxFolders");
}
});
} else {
baseFolders = fsv.getRoots();
}
File[] baseFolders = (useShellFolder)
? (File[]) ShellFolder.get("fileChooserComboBoxFolders")
: fsv.getRoots();
directories.addAll(Arrays.asList(baseFolders));
// Get the canonical (full) path. This has the side

@ -1993,20 +1993,24 @@ public class FilePane extends JPanel implements PropertyChangeListener {
return false;
}
if (f instanceof ShellFolder) {
return f.canWrite();
} else {
if (usesShellFolder(getFileChooser())) {
try {
return ShellFolder.getShellFolder(f).canWrite();
} catch (FileNotFoundException ex) {
// File doesn't exist
return false;
}
} else {
// Ordinary file
try {
if (f instanceof ShellFolder) {
return f.canWrite();
} else {
if (usesShellFolder(getFileChooser())) {
try {
return ShellFolder.getShellFolder(f).canWrite();
} catch (FileNotFoundException ex) {
// File doesn't exist
return false;
}
} else {
// Ordinary file
return f.canWrite();
}
}
} catch (SecurityException e) {
return false;
}
}

@ -82,11 +82,7 @@ public class WindowsPlacesBar extends JToolBar
setBackground(bgColor);
FileSystemView fsv = fc.getFileSystemView();
files = AccessController.doPrivileged(new PrivilegedAction<File[]>() {
public File[] run() {
return (File[]) ShellFolder.get("fileChooserShortcutPanelFolders");
}
});
files = (File[]) ShellFolder.get("fileChooserShortcutPanelFolders");
buttons = new JToggleButton[files.length];
buttonGroup = new ButtonGroup();

@ -28,7 +28,6 @@ import javax.swing.plaf.synth.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
/**
@ -44,7 +43,8 @@ import javax.swing.plaf.*;
* @author Scott Violet
*/
public class DefaultSynthStyle extends SynthStyle implements Cloneable {
private static final String PENDING = "Pending";
private static final Object PENDING = new Object();
/**
* Should the component be opaque?

@ -771,16 +771,9 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI {
fireIntervalRemoved(this, 0, oldSize);
}
File[] baseFolders;
if (useShellFolder) {
baseFolders = AccessController.doPrivileged(new PrivilegedAction<File[]>() {
public File[] run() {
return (File[]) ShellFolder.get("fileChooserComboBoxFolders");
}
});
} else {
baseFolders = fsv.getRoots();
}
File[] baseFolders = (useShellFolder)
? (File[]) ShellFolder.get("fileChooserComboBoxFolders")
: fsv.getRoots();
directories.addAll(Arrays.asList(baseFolders));
// Get the canonical (full) path. This has the side

@ -583,6 +583,8 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
LEReferenceTo<ChainSubClassRuleTable>
chainSubClassRuleTable(chainSubClassSetTable, success, chainSubClassRuleTableOffset);
le_uint16 backtrackGlyphCount = SWAPW(chainSubClassRuleTable->backtrackGlyphCount);
LEReferenceToArrayOf<le_uint16> backtrackClassArray(base, success, chainSubClassRuleTable->backtrackClassArray, backtrackGlyphCount);
if( LE_FAILURE(success) ) { return 0; }
le_uint16 inputGlyphCount = SWAPW(chainSubClassRuleTable->backtrackClassArray[backtrackGlyphCount]) - 1;
LEReferenceToArrayOf<le_uint16> inputClassArray(base, success, &chainSubClassRuleTable->backtrackClassArray[backtrackGlyphCount + 1],inputGlyphCount+2); // +2 for the lookaheadGlyphCount count
le_uint16 lookaheadGlyphCount = SWAPW(inputClassArray.getObject(inputGlyphCount, success));
@ -599,8 +601,6 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
}
tempIterator.prev();
LEReferenceToArrayOf<le_uint16> backtrackClassArray(base, success, chainSubClassRuleTable->backtrackClassArray, backtrackGlyphCount);
if( LE_FAILURE(success) ) { return 0; }
if (! matchGlyphClasses(backtrackClassArray, backtrackGlyphCount,
&tempIterator, backtrackClassDefinitionTable, success, TRUE)) {
continue;

@ -45,6 +45,9 @@ le_uint32 CursiveAttachmentSubtable::process(const LEReferenceTo<CursiveAttachme
le_int32 coverageIndex = getGlyphCoverage(base, glyphID, success);
le_uint16 eeCount = SWAPW(entryExitCount);
LEReferenceToArrayOf<EntryExitRecord>
entryExitRecordsArrayRef(base, success, entryExitRecords, coverageIndex);
if (coverageIndex < 0 || coverageIndex >= eeCount || LE_FAILURE(success)) {
glyphIterator->setCursiveGlyph();
return 0;

@ -40,6 +40,9 @@ U_NAMESPACE_BEGIN
LEReferenceTo<FeatureTable> FeatureListTable::getFeatureTable(const LETableReference &base, le_uint16 featureIndex, LETag *featureTag, LEErrorCode &success) const
{
LEReferenceToArrayOf<FeatureRecord>
featureRecordArrayRef(base, success, featureRecordArray, featureIndex);
if (featureIndex >= SWAPW(featureCount) || LE_FAILURE(success)) {
return LEReferenceTo<FeatureTable>();
}

@ -470,7 +470,12 @@ _TRTRACE("INFO: new RTAO")
#endif
const T& getObject(le_uint32 i, LEErrorCode &success) const {
return *getAlias(i,success);
const T *ret = getAlias(i, success);
if (LE_FAILURE(success) || ret==NULL) {
return *(new T(0));
} else {
return *ret;
}
}
/**

@ -64,6 +64,9 @@ le_uint32 LigatureSubstitutionSubtable::process(const LETableReference &base, Gl
LEReferenceTo<LigatureTable> ligTable(ligSetTable, success, ligTableOffset);
if(LE_FAILURE(success)) { return 0; }
le_uint16 compCount = SWAPW(ligTable->compCount) - 1;
LEReferenceToArrayOf<TTGlyphID>
componentArrayRef(base, success, ligTable->componentArray, compCount);
if (LE_FAILURE(success)) { return 0; }
le_int32 startPosition = glyphIterator->getCurrStreamPosition();
TTGlyphID ligGlyph = SWAPW(ligTable->ligGlyph);
le_uint16 comp;

@ -61,6 +61,8 @@ le_uint32 MultipleSubstitutionSubtable::process(const LETableReference &base, Gl
le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
le_uint16 seqCount = SWAPW(sequenceCount);
LEReferenceToArrayOf<Offset>
sequenceTableOffsetArrayRef(base, success, sequenceTableOffsetArray, seqCount);
if (LE_FAILURE(success)) {
return 0;

@ -36,6 +36,7 @@ import java.security.PrivilegedAction;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Stream;
import static sun.awt.shell.Win32ShellFolder2.*;
import sun.awt.OSInfo;
@ -251,7 +252,7 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
if (file == null) {
file = getDesktop();
}
return file;
return checkFile(file);
} else if (key.equals("roots")) {
// Should be "History" and "Desktop" ?
if (roots == null) {
@ -262,11 +263,11 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
roots = (File[])super.get(key);
}
}
return roots;
return checkFiles(roots);
} else if (key.equals("fileChooserComboBoxFolders")) {
Win32ShellFolder2 desktop = getDesktop();
if (desktop != null) {
if (desktop != null && checkFile(desktop) != null) {
ArrayList<File> folders = new ArrayList<File>();
Win32ShellFolder2 drives = getDrives();
@ -277,7 +278,7 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
folders.add(desktop);
// Add all second level folders
File[] secondLevelFolders = desktop.listFiles();
File[] secondLevelFolders = checkFiles(desktop.listFiles());
Arrays.sort(secondLevelFolders);
for (File secondLevelFolder : secondLevelFolders) {
Win32ShellFolder2 folder = (Win32ShellFolder2) secondLevelFolder;
@ -285,7 +286,7 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
folders.add(folder);
// Add third level for "My Computer"
if (folder.equals(drives)) {
File[] thirdLevelFolders = folder.listFiles();
File[] thirdLevelFolders = checkFiles(folder.listFiles());
if (thirdLevelFolders != null && thirdLevelFolders.length > 0) {
List<File> thirdLevelFoldersList = Arrays.asList(thirdLevelFolders);
@ -295,7 +296,7 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
}
}
}
return folders.toArray(new File[folders.size()]);
return checkFiles(folders);
} else {
return super.get(key);
}
@ -332,7 +333,7 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
}
}
}
return folders.toArray(new File[folders.size()]);
return checkFiles(folders);
} else if (key.startsWith("fileChooserIcon ")) {
String name = key.substring(key.indexOf(" ") + 1);
@ -378,6 +379,41 @@ final class Win32ShellFolderManager2 extends ShellFolderManager {
return null;
}
private File checkFile(File file) {
SecurityManager sm = System.getSecurityManager();
return (sm == null || file == null) ? file : checkFile(file, sm);
}
private File checkFile(File file, SecurityManager sm) {
try {
sm.checkRead(file.getPath());
return file;
} catch (SecurityException se) {
return null;
}
}
private File[] checkFiles(File[] files) {
SecurityManager sm = System.getSecurityManager();
if (sm == null || files == null || files.length == 0) {
return files;
}
return checkFiles(Arrays.stream(files), sm);
}
private File[] checkFiles(List<File> files) {
SecurityManager sm = System.getSecurityManager();
if (sm == null || files.isEmpty()) {
return files.toArray(new File[files.size()]);
}
return checkFiles(files.stream(), sm);
}
private File[] checkFiles(Stream<File> filesStream, SecurityManager sm) {
return filesStream.filter((file) -> checkFile(file, sm) != null)
.toArray(File[]::new);
}
/**
* Does <code>dir</code> represent a "computer" such as a node on the network, or
* "My Computer" on the desktop.

@ -95,6 +95,9 @@ public final class BerDecoder extends Ber {
for( int i = 0; i < lengthbyte; i++) {
retval = (retval << 8) + (buf[offset++] & 0xff);
}
if (retval < 0) {
throw new DecodeException("Invalid length bytes");
}
return retval;
} else {
return lengthbyte;

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, 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
@ -37,7 +37,10 @@ import java.rmi.server.RemoteCall;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import sun.rmi.runtime.Log;
import sun.rmi.server.Dispatcher;
import sun.rmi.server.UnicastServerRef;
@ -69,6 +72,15 @@ public abstract class Transport {
/** ObjID for DGCImpl */
private static final ObjID dgcID = new ObjID(ObjID.DGC_ID);
/** AccessControlContext for setting context ClassLoader */
private static final AccessControlContext SETCCL_ACC;
static {
Permissions perms = new Permissions();
perms.add(new RuntimePermission("setContextClassLoader"));
ProtectionDomain[] pd = { new ProtectionDomain(null, perms) };
SETCCL_ACC = new AccessControlContext(pd);
}
/**
* Returns a <I>Channel</I> that generates connections to the
* endpoint <I>ep</I>. A Channel is an object that creates and
@ -117,6 +129,16 @@ public abstract class Transport {
*/
protected abstract void checkAcceptPermission(AccessControlContext acc);
/**
* Sets the context class loader for the current thread.
*/
private static void setContextClassLoader(ClassLoader ccl) {
AccessController.doPrivileged((PrivilegedAction<Void>)() -> {
Thread.currentThread().setContextClassLoader(ccl);
return null;
}, SETCCL_ACC);
}
/**
* Service an incoming remote call. When a message arrives on the
* connection indicating the beginning of a remote call, the
@ -165,11 +187,10 @@ public abstract class Transport {
target.getAccessControlContext();
ClassLoader ccl = target.getContextClassLoader();
Thread t = Thread.currentThread();
ClassLoader savedCcl = t.getContextClassLoader();
ClassLoader savedCcl = Thread.currentThread().getContextClassLoader();
try {
t.setContextClassLoader(ccl);
setContextClassLoader(ccl);
currentTransport.set(this);
try {
java.security.AccessController.doPrivileged(
@ -184,7 +205,7 @@ public abstract class Transport {
throw (IOException) pae.getException();
}
} finally {
t.setContextClassLoader(savedCcl);
setContextClassLoader(savedCcl);
currentTransport.set(null);
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, 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
@ -49,7 +49,9 @@ import java.rmi.server.ServerNotActiveException;
import java.rmi.server.UID;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@ -120,6 +122,14 @@ public class TCPTransport extends Transport {
private static final ThreadLocal<ConnectionHandler>
threadConnectionHandler = new ThreadLocal<>();
/** an AccessControlContext with no permissions */
private static final AccessControlContext NOPERMS_ACC;
static {
Permissions perms = new Permissions();
ProtectionDomain[] pd = { new ProtectionDomain(null, perms) };
NOPERMS_ACC = new AccessControlContext(pd);
}
/** endpoints for this transport */
private final LinkedList<TCPEndpoint> epList;
/** number of objects exported on this transport */
@ -664,7 +674,10 @@ public class TCPTransport extends Transport {
t.setName("RMI TCP Connection(" +
connectionCount.incrementAndGet() +
")-" + remoteHost);
run0();
AccessController.doPrivileged((PrivilegedAction<Void>)() -> {
run0();
return null;
}, NOPERMS_ACC);
} finally {
t.setName(name);
}

@ -270,6 +270,9 @@ public class GSSHeader {
value <<= 8;
value += 0x0ff & in.read();
}
if (value < 0) {
throw new IOException("Invalid length bytes");
}
}
return value;
}

@ -257,7 +257,8 @@ public class GSSNameImpl implements GSSName {
((0xFF & bytes[pos++]) << 16) |
((0xFF & bytes[pos++]) << 8) |
(0xFF & bytes[pos++]));
if (pos > bytes.length - mechPortionLen) {
if (mechPortionLen < 0 || pos > bytes.length - mechPortionLen) {
throw new GSSExceptionImpl(GSSException.BAD_NAME,
"Exported name mech name is corrupted!");
}

@ -233,6 +233,9 @@ public class GSSNameElement implements GSSNameSpi {
((0xFF & nameVal[pos++]) << 16) |
((0xFF & nameVal[pos++]) << 8) |
(0xFF & nameVal[pos++]));
if (mechPortionLen < 0) {
throw new GSSException(GSSException.BAD_NAME);
}
byte[] mechPortion = new byte[mechPortionLen];
System.arraycopy(nameVal, pos, mechPortion, 0, mechPortionLen);
return mechPortion;

@ -113,15 +113,17 @@ public class SCDynamicStoreConfig {
@SuppressWarnings("unchecked")
private static Hashtable<String, Object> convertNativeConfig(
Hashtable<String, Object> stanzaTable) {
Hashtable<String, Object> stanzaTable) throws IOException {
// convert SCDynamicStore realm structure to Java realm structure
Hashtable<String, ?> realms =
(Hashtable<String, ?>) stanzaTable.get("realms");
if (realms != null) {
stanzaTable.remove("realms");
Hashtable<String, Object> realmsTable = convertRealmConfigs(realms);
stanzaTable.put("realms", realmsTable);
if (realms == null || realms.isEmpty()) {
throw new IOException(
"SCDynamicStore contains an empty Kerberos setting");
}
stanzaTable.remove("realms");
Hashtable<String, Object> realmsTable = convertRealmConfigs(realms);
stanzaTable.put("realms", realmsTable);
WrapAllStringInVector(stanzaTable);
if (DEBUG) System.out.println("stanzaTable : " + stanzaTable);
return stanzaTable;

@ -118,7 +118,7 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
} else {
type = read(4);
}
length = read(4);
length = readLength4();
List<String> result = new ArrayList<String>();
/*
* DCE includes the principal's realm in the count; the new format
@ -127,7 +127,7 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
if (version == KRB5_FCC_FVNO_1)
length--;
for (int i = 0; i <= length; i++) {
namelength = read(4);
namelength = readLength4();
byte[] bytes = IOUtils.readFully(this, namelength, true);
result.add(new String(bytes));
}
@ -184,7 +184,7 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
keyType = read(2);
if (version == KRB5_FCC_FVNO_3)
read(2); /* keytype recorded twice in fvno 3 */
keyLen = read(4);
keyLen = readLength4();
byte[] bytes = IOUtils.readFully(this, keyLen, true);
return new EncryptionKey(bytes, keyType, version);
}
@ -207,12 +207,12 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
HostAddress[] readAddr() throws IOException, KrbApErrException {
int numAddrs, addrType, addrLength;
numAddrs = read(4);
numAddrs = readLength4();
if (numAddrs > 0) {
List<HostAddress> addrs = new ArrayList<>();
for (int i = 0; i < numAddrs; i++) {
addrType = read(2);
addrLength = read(4);
addrLength = readLength4();
if (!(addrLength == 4 || addrLength == 16)) {
if (DEBUG) {
System.out.println("Incorrect address format.");
@ -231,13 +231,13 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
AuthorizationDataEntry[] readAuth() throws IOException {
int num, adtype, adlength;
num = read(4);
num = readLength4();
if (num > 0) {
List<AuthorizationDataEntry> auData = new ArrayList<>();
byte[] data = null;
for (int i = 0; i < num; i++) {
adtype = read(2);
adlength = read(4);
adlength = readLength4();
data = IOUtils.readFully(this, adlength, true);
auData.add(new AuthorizationDataEntry(adtype, data));
}
@ -248,7 +248,7 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC
byte[] readData() throws IOException {
int length;
length = read(4);
length = readLength4();
if (length == 0) {
return null;
} else {

@ -150,43 +150,43 @@ public class FileCredentialsCache extends CredentialsCache
synchronized void init(PrincipalName principal, String name)
throws IOException, KrbException {
primaryPrincipal = principal;
CCacheOutputStream cos =
new CCacheOutputStream(new FileOutputStream(name));
version = KRB5_FCC_FVNO_3;
cos.writeHeader(primaryPrincipal, version);
cos.close();
try (FileOutputStream fos = new FileOutputStream(name);
CCacheOutputStream cos = new CCacheOutputStream(fos)) {
version = KRB5_FCC_FVNO_3;
cos.writeHeader(primaryPrincipal, version);
}
load(name);
}
synchronized void load(String name) throws IOException, KrbException {
PrincipalName p;
CCacheInputStream cis =
new CCacheInputStream(new FileInputStream(name));
version = cis.readVersion();
if (version == KRB5_FCC_FVNO_4) {
tag = cis.readTag();
} else {
tag = null;
if (version == KRB5_FCC_FVNO_1 || version == KRB5_FCC_FVNO_2) {
cis.setNativeByteOrder();
try (FileInputStream fis = new FileInputStream(name);
CCacheInputStream cis = new CCacheInputStream(fis)) {
version = cis.readVersion();
if (version == KRB5_FCC_FVNO_4) {
tag = cis.readTag();
} else {
tag = null;
if (version == KRB5_FCC_FVNO_1 || version == KRB5_FCC_FVNO_2) {
cis.setNativeByteOrder();
}
}
}
p = cis.readPrincipal(version);
p = cis.readPrincipal(version);
if (primaryPrincipal != null) {
if (!(primaryPrincipal.match(p))) {
throw new IOException("Primary principals don't match.");
}
} else
primaryPrincipal = p;
credentialsList = new Vector<Credentials> ();
while (cis.available() > 0) {
Credentials cred = cis.readCred(version);
if (cred != null) {
credentialsList.addElement(cred);
if (primaryPrincipal != null) {
if (!(primaryPrincipal.match(p))) {
throw new IOException("Primary principals don't match.");
}
} else
primaryPrincipal = p;
credentialsList = new Vector<Credentials>();
while (cis.available() > 0) {
Credentials cred = cis.readCred(version);
if (cred != null) {
credentialsList.addElement(cred);
}
}
}
cis.close();
}
@ -245,16 +245,16 @@ public class FileCredentialsCache extends CredentialsCache
* Saves the credentials cache file to the disk.
*/
public synchronized void save() throws IOException, Asn1Exception {
CCacheOutputStream cos
= new CCacheOutputStream(new FileOutputStream(cacheName));
cos.writeHeader(primaryPrincipal, version);
Credentials[] tmp = null;
if ((tmp = getCredsList()) != null) {
for (int i = 0; i < tmp.length; i++) {
cos.addCreds(tmp[i]);
try (FileOutputStream fos = new FileOutputStream(cacheName);
CCacheOutputStream cos = new CCacheOutputStream(fos)) {
cos.writeHeader(primaryPrincipal, version);
Credentials[] tmp = null;
if ((tmp = getCredsList()) != null) {
for (int i = 0; i < tmp.length; i++) {
cos.addCreds(tmp[i]);
}
}
}
cos.close();
}
boolean match(String[] s1, String[] s2) {

@ -56,15 +56,33 @@ public class KrbDataInputStream extends BufferedInputStream{
public KrbDataInputStream(InputStream is){
super(is);
}
/**
* Reads a length value which is represented in 4 bytes from
* this input stream. The value must be positive.
* @return the length value represented by this byte array.
* @throws IOException if there are not enough bytes or it represents
* a negative value
*/
final public int readLength4() throws IOException {
int len = read(4);
if (len < 0) {
throw new IOException("Invalid encoding");
}
return len;
}
/**
* Reads up to the specific number of bytes from this input stream.
* @param num the number of bytes to be read.
* @return the int value of this byte array.
* @exception IOException.
* @throws IOException if there are not enough bytes
*/
public int read(int num) throws IOException{
public int read(int num) throws IOException {
byte[] bytes = new byte[num];
read(bytes, 0, num);
if (read(bytes, 0, num) != num) {
throw new IOException("Premature end of stream reached");
}
int result = 0;
for (int i = 0; i < num; i++) {
if (bigEndian) {

@ -103,7 +103,7 @@ class Code {
case HTTP_UNAVAILABLE: return " Service Unavailable";
case HTTP_GATEWAY_TIMEOUT: return " Gateway Timeout";
case HTTP_VERSION: return " HTTP Version Not Supported";
default: return "";
default: return " ";
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 201, 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
@ -53,7 +53,6 @@ import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.ZipException;
import java.util.zip.ZipError;
import static java.lang.Boolean.*;
import static jdk.nio.zipfs.ZipConstants.*;
import static jdk.nio.zipfs.ZipUtils.*;
@ -119,7 +118,16 @@ class ZipFileSystem extends FileSystem {
this.zc = ZipCoder.get(nameEncoding);
this.defaultdir = new ZipPath(this, getBytes(defaultDir));
this.ch = Files.newByteChannel(zfpath, READ);
this.cen = initCEN();
try {
this.cen = initCEN();
} catch (IOException x) {
try {
this.ch.close();
} catch (IOException xx) {
x.addSuppressed(xx);
}
throw x;
}
}
@Override
@ -1058,12 +1066,15 @@ class ZipFileSystem extends FileSystem {
int nlen = CENNAM(cen, pos);
int elen = CENEXT(cen, pos);
int clen = CENCOM(cen, pos);
if ((CENFLG(cen, pos) & 1) != 0)
if ((CENFLG(cen, pos) & 1) != 0) {
zerror("invalid CEN header (encrypted entry)");
if (method != METHOD_STORED && method != METHOD_DEFLATED)
}
if (method != METHOD_STORED && method != METHOD_DEFLATED) {
zerror("invalid CEN header (unsupported compression method: " + method + ")");
if (pos + CENHDR + nlen > limit)
}
if (pos + CENHDR + nlen > limit) {
zerror("invalid CEN header (bad header size)");
}
byte[] name = Arrays.copyOfRange(cen, pos + CENHDR, pos + CENHDR + nlen);
IndexNode inode = new IndexNode(name, pos);
inodes.put(inode, inode);
@ -1533,6 +1544,7 @@ class ZipFileSystem extends FileSystem {
private CRC32 crc;
private Entry e;
private long written;
private boolean isClosed = false;
EntryOutputStream(Entry e, OutputStream os)
throws IOException
@ -1545,9 +1557,14 @@ class ZipFileSystem extends FileSystem {
}
@Override
public void write(byte b[], int off, int len) throws IOException {
public synchronized void write(byte b[], int off, int len)
throws IOException
{
if (e.type != Entry.FILECH) // only from sync
ensureOpen();
if (isClosed) {
throw new IOException("Stream closed");
}
if (off < 0 || len < 0 || off > b.length - len) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
@ -1568,7 +1585,11 @@ class ZipFileSystem extends FileSystem {
}
@Override
public void close() throws IOException {
public synchronized void close() throws IOException {
if (isClosed) {
return;
}
isClosed = true;
// TBD ensureOpen();
switch (e.method) {
case METHOD_DEFLATED:
@ -1599,8 +1620,8 @@ class ZipFileSystem extends FileSystem {
}
}
static void zerror(String msg) {
throw new ZipError(msg);
static void zerror(String msg) throws ZipException {
throw new ZipException(msg);
}
// Maxmum number of de/inflater we cache

@ -36,7 +36,7 @@ import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipError;
import java.util.zip.ZipException;
import java.util.concurrent.ExecutorService;
/*
@ -100,7 +100,7 @@ public class ZipFileSystemProvider extends FileSystemProvider {
ZipFileSystem zipfs = null;
try {
zipfs = new ZipFileSystem(this, path, env);
} catch (ZipError ze) {
} catch (ZipException ze) {
String pname = path.toString();
if (pname.endsWith(".zip") || pname.endsWith(".jar"))
throw ze;
@ -122,7 +122,7 @@ public class ZipFileSystemProvider extends FileSystemProvider {
ensureFile(path);
try {
return new ZipFileSystem(this, path, env);
} catch (ZipError ze) {
} catch (ZipException ze) {
String pname = path.toString();
if (pname.endsWith(".zip") || pname.endsWith(".jar"))
throw ze;

@ -296,6 +296,9 @@ com/sun/jdi/JdbReadTwiceTest.sh generic-all
# 8058616
com/sun/jdi/RedefinePop.sh generic-all
# 8068645
com/sun/jdi/CatchPatternTest.sh generic-all
############################################################################
# jdk_util
@ -332,6 +335,9 @@ sun/tools/jinfo/JInfoRunningProcessFlagTest.java generic-all
# 8057732
sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java generic-all
# 8064572 8060736 8062938
sun/jvmstat/monitor/MonitoredVm/CR6672135.java generic-all
# 8060088
com/sun/tracing/BasicWithSecurityMgr.java generic-all

@ -0,0 +1,143 @@
/*
* 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 8068795
* @summary HttpServer missing tailing space for some response codes
* @author lev.priima@oracle.com
*/
import java.net.InetSocketAddress;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class MissingTrailingSpace {
private static final int noMsgCode = 207;
private static final String someContext = "/context";
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
try {
server.setExecutor(Executors.newFixedThreadPool(1));
server.createContext(someContext, new HttpHandler() {
@Override
public void handle(HttpExchange msg) {
try {
try {
msg.sendResponseHeaders(noMsgCode, -1);
} catch(IOException ioe) {
ioe.printStackTrace();
}
} finally {
msg.close();
}
}
});
server.start();
System.out.println("Server started at port "
+ server.getAddress().getPort());
runRawSocketHttpClient("localhost", server.getAddress().getPort());
} finally {
((ExecutorService)server.getExecutor()).shutdown();
server.stop(0);
}
System.out.println("Server finished.");
}
static void runRawSocketHttpClient(String hostname, int port)
throws Exception
{
Socket socket = null;
PrintWriter writer = null;
BufferedReader reader = null;
final String CRLF = "\r\n";
try {
socket = new Socket(hostname, port);
writer = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream()));
System.out.println("Client connected by socket: " + socket);
writer.print("GET " + someContext + "/ HTTP/1.1" + CRLF);
writer.print("User-Agent: Java/"
+ System.getProperty("java.version")
+ CRLF);
writer.print("Host: " + hostname + CRLF);
writer.print("Accept: */*" + CRLF);
writer.print("Connection: keep-alive" + CRLF);
writer.print(CRLF); // Important, else the server will expect that
// there's more into the request.
writer.flush();
System.out.println("Client wrote rquest to socket: " + socket);
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
System.out.println("Client start reading from server:" );
String line = reader.readLine();
if ( !line.endsWith(" ") ) {
throw new RuntimeException("respond to unknown code "
+ noMsgCode
+ " doesn't return space at the end of the first header.\n"
+ "Should be: " + "\"" + line + " \""
+ ", but returns: " + "\"" + line + "\".");
}
for (; line != null; line = reader.readLine()) {
if (line.isEmpty()) {
break;
}
System.out.println("\"" + line + "\"");
}
System.out.println("Client finished reading from server" );
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException logOrIgnore) {
logOrIgnore.printStackTrace();
}
if (writer != null) {
writer.close();
}
if (socket != null) {
try {
socket.close();
} catch (IOException logOrIgnore) {
logOrIgnore.printStackTrace();
}
}
}
System.out.println("Client finished." );
}
}

@ -0,0 +1,209 @@
/*
* Copyright (c) 2007, 2014, 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 8054358
* @summary Check whether a set of dialogs created with a toolkit excluded Frame
* parent has a proper modal blocking behavior. Also show a document modal
* dialog and check if it blocks the document properly.
*
* @library ../helpers ../../../../lib/testlibrary/
* @build ExtendedRobot
* @build Flag
* @build TestDialog
* @build TestFrame
* @run main/timeout=500 MultipleDialogs1Test
*/
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Iterator;
public class MultipleDialogs1Test {
private volatile CustomFrame frame;
private List<CustomDialog> dialogList;
private static int delay = 500;
private int dialogCount = -1;
public void createGUI() {
final int n = 8;
dialogList = new ArrayList<>();
frame = new CustomFrame();
frame.setLocation(50, 50);
frame.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);
frame.setVisible(true);
int x = 250, y = 50;
CustomDialog dlg;
for (int i = 0; i < n - 1; ++i) {
dlg = new CustomDialog(frame);
dlg.setLocation(x, y);
x += 200;
if (x > 600) {
x = 50;
y += 200;
}
Dialog.ModalityType type;
if (i % 3 == 0) {
type = Dialog.ModalityType.MODELESS;
} else if (i % 3 == 1) {
type = Dialog.ModalityType.APPLICATION_MODAL;
} else {
type = Dialog.ModalityType.TOOLKIT_MODAL;
}
dlg.setModalityType(type);
dialogList.add(dlg);
}
dlg = new CustomDialog(frame);
dlg.setLocation(x, y);
dlg.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
dialogList.add(dlg);
}
public void doTest() throws Exception {
try {
EventQueue.invokeAndWait(this::createGUI);
ExtendedRobot robot = new ExtendedRobot();
robot.waitForIdle(delay);
List<CustomDialog> dialogs = Collections.synchronizedList(dialogList);
final int n = dialogs.size();
synchronized(dialogs) {
for (int i = 0; i < n - 1; ++i) {
frame.clickOpenButton(robot);
robot.waitForIdle(delay);
dialogs.get(i).checkUnblockedDialog(
robot, i + ": This is " + getType(i) + ".");
frame.checkUnblockedFrame(robot, i + ": Other dialogs are visible.");
if (i > 0) {
for (int j = 0; j < i; j++) {
dialogs.get(j).checkUnblockedDialog(robot, j + ": A toolkit modality " +
"excluded frame is a parent of this dialog.");
}
}
} // i
frame.clickOpenButton(robot);
robot.waitForIdle(delay);
dialogs.get(n - 1).checkUnblockedDialog(
robot, (n - 1) + ": This is " + getType(n - 1) + ".");
frame.checkBlockedFrame(robot,
"A document modal dialog with Frame parent is visible.");
for (int i = 0; i < n - 1; ++i) {
dialogs.get(i).checkUnblockedDialog(robot,
i + ": A document modal dialog should not block " +
"this dialog. The parent is modality excluded.");
}
dialogs.get(n - 1).clickCloseButton(robot);
robot.waitForIdle(delay);
for (int i = 0; i < n - 1; ++i) {
dialogs.get(i).checkUnblockedDialog(robot, i + ": A document modal " +
"dialog which blocked this dialog was closed.");
}
frame.checkUnblockedFrame(robot,
"A blocking document modal dialog was closed.");
robot.waitForIdle(delay);
} // synchronized
} finally {
EventQueue.invokeAndWait(this::closeAll);
}
}
private String getType(int i) {
switch (dialogList.get(i).getModalityType()) {
case APPLICATION_MODAL:
return "an application modal dialog";
case DOCUMENT_MODAL:
return "a document modal dialog";
case TOOLKIT_MODAL:
return "a toolkit modal dialog";
}
return "a modeless dialog";
}
private void closeAll() {
if (frame != null) { frame.dispose(); }
if (dialogList != null) {
Iterator<CustomDialog> it = dialogList.iterator();
while (it.hasNext()) { it.next().dispose(); }
}
}
class CustomFrame extends TestFrame {
@Override
public void doOpenAction() {
if ((dialogList != null) && (dialogList.size() > dialogCount)) {
dialogCount++;
CustomDialog d = dialogList.get(dialogCount);
if (d != null) { d.setVisible(true); }
}
}
}
class CustomDialog extends TestDialog {
public CustomDialog(Frame f) { super(f); }
public CustomDialog(Dialog d) { super(d); }
@Override
public void doCloseAction() { this.dispose(); }
}
public static void main(String[] args) throws Exception {
(new MultipleDialogs1Test()).doTest();
}
}

@ -0,0 +1,299 @@
/*
* Copyright (c) 2007, 2014, 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 8054358
* @summary Check whether a set of dialogs created with an application excluded Frame
* parent has a proper modal blocking behavior. Also show a document modal
* dialog and check if it blocks the document properly.
*
* @library ../helpers ../../../../lib/testlibrary/
* @build ExtendedRobot
* @build Flag
* @build TestDialog
* @build TestFrame
* @run main/timeout=500 MultipleDialogs2Test
*/
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Iterator;
public class MultipleDialogs2Test {
private volatile CustomFrame frame;
private List<CustomDialog> dialogList;
private static final int delay = 500;
private int dialogCount = -1;
private void createGUI() {
final int n = 8;
dialogList = new ArrayList<>();
frame = new CustomFrame();
frame.setLocation(50, 50);
frame.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
frame.setVisible(true);
CustomDialog dlg;
int x = 250, y = 50;
for (int i = 0; i < n - 1; ++i) {
dlg = new CustomDialog(frame);
dlg.setLocation(x, y);
x += 200;
if (x > 600) {
x = 50;
y += 200;
}
Dialog.ModalityType type;
if (i % 3 == 0) {
type = Dialog.ModalityType.MODELESS;
} else if (i % 3 == 1) {
type = Dialog.ModalityType.APPLICATION_MODAL;
} else {
type = Dialog.ModalityType.TOOLKIT_MODAL;
}
dlg.setModalityType(type);
dialogList.add(dlg);
}
dlg = new CustomDialog(frame);
dlg.setLocation(x, y);
dlg.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
dialogList.add(dlg);
}
public void doTest() throws Exception {
try {
EventQueue.invokeAndWait(this::createGUI);
ExtendedRobot robot = new ExtendedRobot();
robot.waitForIdle(delay);
List<CustomDialog> dialogs = Collections.synchronizedList(dialogList);
final int n = dialogs.size();
synchronized(dialogs) {
for (int i = 0; i < n - 1; ++i) {
frame.clickOpenButton(robot);
robot.waitForIdle(delay);
dialogs.get(i).checkUnblockedDialog(
robot, i + ": This is " + getType(i) + ".");
if (isToolkitModal(i)) {
for (int j = 0; j < i; ++j) {
dialogs.get(j).checkBlockedDialog(robot, j + ": This dialog " +
"should be blocked by a toolkit modal dialog.");
}
frame.checkBlockedFrame(robot, i + ": A toolkit modal dialog " +
"should block this application modality excluded frame.");
break;
} else {
for (int j = 0; j < i; ++j) {
dialogs.get(j).checkUnblockedDialog(robot,
j + ": An application modality excluded frame " +
"is the parent of this dialog.");
}
frame.checkUnblockedFrame(robot, i + ": The frame is " +
"application modality excluded, but it is blocked.");
}
}
int tkIndex = dialogCount; // continue testing
final int tk0 = tkIndex;
for (int i = tk0 + 1; i < n - 1; ++i) {
dialogs.get(tkIndex).clickOpenButton(robot);
robot.waitForIdle(delay);
frame.checkBlockedFrame(robot, i + ": A toolkit modal dialog " +
"should block this application modality excluded frame.");
if (isToolkitModal(i)) {
dialogs.get(i).checkUnblockedDialog(robot, i + ": This is " +
"a toolkit modal dialog with blocked frame parent. " +
"Another toolkit modal dialog is visible.");
for (int j = 0; j < i; ++j) {
dialogs.get(j).checkBlockedDialog(robot, j + ": " +
"A toolkit modal dialog should block this child " +
"dialog of application modality excluded frame.");
}
tkIndex = i;
} else {
dialogs.get(i).checkBlockedDialog(
robot, i + ": This is " + getType(i) + " with blocked " +
"Frame parent. Also, a toolkit modal dialog is visible.");
for (int j = 0; j < i; ++j) {
if (j != tkIndex) {
dialogs.get(j).checkBlockedDialog(robot, j +
": A toolkit modal dialog should block this " +
"child dialog of an application modality excluded frame.");
}
}
}
}
// show a document modal dialog; the toolkit modal dialog should block it
dialogs.get(tkIndex).clickOpenButton(robot);
robot.waitForIdle(delay);
frame.checkBlockedFrame(robot, "A toolkit modal dialog is visible.");
for (int i = 0; i < n; ++i) {
if (i == tkIndex) {
dialogs.get(tkIndex).checkUnblockedDialog(robot,
tkIndex + ": This is a toolkit modal dialog. " +
"A document modal dialog is visible.");
} else {
dialogs.get(i).checkBlockedDialog(robot,
i + ": A toolkit modal dialog should block this dialog.");
}
}
dialogs.get(tk0 + 3).clickCloseButton(robot); // close 2nd toolkit dialog
robot.waitForIdle(delay);
for (int i = 0; i < n; ++i) {
if (i == tk0 + 3) { continue; }
if (i == tk0) {
dialogs.get(i).checkUnblockedDialog(robot,
i + ": This is a toolkit modal dialog. A blocking " +
"toolkit modal dialog was opened and then closed.");
} else {
dialogs.get(i).checkBlockedDialog(robot,
i + ": This dialog should be blocked by a toolkit modal dialog. " +
"Another blocking toolkit modal dialog was closed.");
}
}
dialogs.get(tk0).clickCloseButton(robot);
robot.waitForIdle(delay);
frame.checkBlockedFrame(
robot, "A document modal dialog should block this Frame.");
for (int i = 0; i < n - 1; ++i) {
if (!isToolkitModal(i)) {
dialogs.get(i).checkUnblockedDialog(robot, i + ": The parent " +
"of the dialog is an app modality excluded Frame.");
}
}
dialogs.get(n - 1).clickCloseButton(robot);
robot.waitForIdle(delay);
frame.checkUnblockedFrame(robot, "A document modal dialog " +
"blocking this Frame was closed.");
for (int i = 0; i < n - 1; ++i) {
if (!isToolkitModal(i)) {
dialogs.get(i).checkUnblockedDialog(robot, i + ": A document modal " +
"dialog blocking the parent frame was closed.");
}
}
} // synchronized
} finally {
EventQueue.invokeAndWait(this::closeAll);
}
}
private boolean isToolkitModal(int i) { return (i % 3 == 2); }
private String getType(int i) {
switch (dialogList.get(i).getModalityType()) {
case APPLICATION_MODAL:
return "an application modal dialog";
case DOCUMENT_MODAL:
return "a document modal dialog";
case TOOLKIT_MODAL:
return "a toolkit modal dialog";
}
return "a modeless dialog";
}
public void closeAll() {
if (frame != null) { frame.dispose(); }
if (dialogList != null) {
Iterator<CustomDialog> it = dialogList.iterator();
while (it.hasNext()) { it.next().dispose(); }
}
}
class CustomFrame extends TestFrame {
@Override
public void doOpenAction() {
if ((dialogList != null) && (dialogList.size() > dialogCount)) {
dialogCount++;
CustomDialog d = dialogList.get(dialogCount);
if (d != null) { d.setVisible(true); }
}
}
}
class CustomDialog extends TestDialog {
public CustomDialog(Frame frame) { super(frame); }
@Override
public void doCloseAction() { this.dispose(); }
@Override
public void doOpenAction() {
if ((dialogList != null) && (dialogList.size() > dialogCount)) {
dialogCount++;
if (dialogList.get(dialogCount) != null) {
dialogList.get(dialogCount).setVisible(true);
}
}
}
}
public static void main(String[] args) throws Exception {
(new MultipleDialogs2Test()).doTest();
}
}

@ -0,0 +1,286 @@
/*
* Copyright (c) 2007, 2014, 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 8054358
* @summary Check correctness of modal blocking behavior for a chain of Dialogs
* having different modality types with a Frame as a document root.
*
* @library ../helpers ../../../../lib/testlibrary/
* @build ExtendedRobot
* @build Flag
* @build TestDialog
* @build TestFrame
* @run main/timeout=500 MultipleDialogs3Test
*/
import java.awt.*;
import static jdk.testlibrary.Asserts.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Iterator;
public class MultipleDialogs3Test {
private volatile CustomFrame frame;
private List<CustomDialog> dialogList;
private static int delay = 500;
private int dialogCount = -1;
public void createGUI() {
final int n = 8;
dialogList = new ArrayList<>();
frame = new CustomFrame();
frame.setLocation(50, 50);
frame.setVisible(true);
int x = 250;
int y = 50;
for (int i = 0; i < n; ++i) {
CustomDialog dlg;
if (i == 0) {
dlg = new CustomDialog(frame);
} else {
dlg = new CustomDialog(dialogList.get(i - 1));
}
dlg.setLocation(x, y);
x += 200;
if (x > 600) {
x = 50;
y += 200;
}
Dialog.ModalityType type;
if (i % 4 == 0) {
type = Dialog.ModalityType.MODELESS;
} else if (i % 4 == 1) {
type = Dialog.ModalityType.DOCUMENT_MODAL;
} else if (i % 4 == 2) {
type = Dialog.ModalityType.APPLICATION_MODAL;
} else {
type = Dialog.ModalityType.TOOLKIT_MODAL;
}
dlg.setModalityType(type);
dialogList.add(dlg);
}
}
public void doTest() throws Exception {
try {
EventQueue.invokeAndWait(this::createGUI);
ExtendedRobot robot = new ExtendedRobot();
robot.waitForIdle(delay);
frame.clickOpenButton(robot);
robot.waitForIdle(delay);
List<CustomDialog> dialogs = Collections.synchronizedList(dialogList);
final int n = dialogs.size();
synchronized(dialogs) {
for (int i = 0; i < n; ++i) {
dialogs.get(i).activated.waitForFlagTriggered();
assertTrue(dialogs.get(i).activated.flag(), i + ": Dialog did not " +
"trigger windowActivated event when it became visible.");
dialogs.get(i).closeGained.waitForFlagTriggered();
assertTrue(dialogs.get(i).closeGained.flag(), i + ": Close button " +
"did not gain focus when Dialog became visible.");
assertTrue(dialogs.get(i).closeButton.hasFocus(), i +
": Close button gained focus but then lost it.");
dialogs.get(i).checkUnblockedDialog(robot,
i + ": The dialog shouldn't be blocked.");
if (i == 0) {
assertTrue(dialogs.get(0).getModalityType() ==
Dialog.ModalityType.MODELESS, "0: invalid modality type.");
frame.checkUnblockedFrame(robot, i + ": A modeless dialog was " +
"shown, but the parent frame became blocked.");
} else {
if (i % 4 == 0) { // modeless dialog
assertTrue(dialogs.get(i).getModalityType() ==
Dialog.ModalityType.MODELESS, i +
": incorrect dialog modality type.");
dialogs.get(i - 1).checkUnblockedDialog(robot, i + ": A modeless " +
"dialog was shown, but the parent dialog became blocked.");
if (i > 0) {
for (int j = 0; j < i - 1; ++j) {
dialogs.get(j).checkBlockedDialog(robot, i + ", " + j +
": Showing a modeless dialog as a child of a " +
"modal dialog unblocked some dialog in its hierarchy.");
}
}
} else {
for (int j = 0; j < i; ++j) {
dialogs.get(j).checkBlockedDialog(robot, i + ", " + j +
": A modal dialog was shown, but some dialog " +
"in its hierarchy became unblocked.");
}
}
frame.checkBlockedFrame(robot, i + ": A modal was dialog shown, " +
"but the document root frame became unblocked.");
}
if (i != n - 1) {
dialogs.get(i).clickOpenButton(robot);
robot.waitForIdle(delay);
}
}
for (int i = n - 1; i >= 0; --i) {
resetAll();
dialogs.get(i).clickCloseButton(robot);
robot.waitForIdle(delay);
if (i > 0) {
dialogs.get(i - 1).activated.waitForFlagTriggered();
assertTrue(dialogs.get(i - 1).activated.flag(), i + ": Dialog " +
"was not activated when a child dialog was closed.");
if (i == 1) {
frame.checkUnblockedFrame(robot, "1: Frame having " +
"a child modeless dialog was blocked.");
dialogs.get(0).checkUnblockedDialog(robot,
"0: A modeless dialog at the bottom " +
"of the hierarchy was blocked.");
} else if ((i - 1) % 4 == 0) { // dialog[i - 1] is modeless
for (int j = 0; j < i - 2; ++j) {
dialogs.get(j).checkBlockedDialog(robot, i + ", " + j +
": A dialog in the hierarchy was not blocked. " +
"A dialog blocking a modeless dialog was closed.");
}
dialogs.get(i - 2).checkUnblockedDialog(robot, i + ": A modal " +
"dialog having a child modeless dialog was blocked.");
dialogs.get(i - 1).checkUnblockedDialog(robot, i + ": A modeless " +
"dialog at the bottom of the hierarchy was blocked.");
frame.checkBlockedFrame(robot, i +
": Frame having a child modal dialog was not blocked.");
} else {
for (int j = 0; j <= i - 2; ++j) {
dialogs.get(j).checkBlockedDialog(robot, i + ", " + j +
": A dialog in the hierarchy was not blocked. " +
"A child dialog was closed.");
}
dialogs.get(i - 1).checkUnblockedDialog(robot, (i - 1) +
": A dialog was not unblocked when the modal dialog was closed.");
frame.checkBlockedFrame(robot, i + ": Frame having " +
"a child modal dialog was not blocked. " +
"Another child dialog was closed.");
}
} else {
frame.activated.waitForFlagTriggered();
assertTrue(frame.activated.flag(), i + ": Frame was not " +
"activated when a child dialog was closed.");
}
}
} // synchronized
} finally {
EventQueue.invokeAndWait(this::closeAll);
}
}
private void resetAll() {
frame.resetStatus();
Iterator<CustomDialog> it = dialogList.iterator();
while (it.hasNext()) { it.next().resetStatus(); }
}
public void closeAll() {
if (frame != null) { frame.dispose(); }
if (dialogList != null) {
Iterator<CustomDialog> it = dialogList.iterator();
while (it.hasNext()) { it.next().dispose(); }
}
}
class CustomFrame extends TestFrame {
@Override
public void doOpenAction() {
if ((dialogList != null) && (dialogList.size() > dialogCount)) {
dialogCount++;
CustomDialog d = dialogList.get(dialogCount);
if (d != null) { d.setVisible(true); }
}
}
}
class CustomDialog extends TestDialog {
public CustomDialog(Frame frame) { super(frame); }
public CustomDialog(Dialog dialog) { super(dialog); }
@Override
public void doCloseAction() { this.dispose(); }
@Override
public void doOpenAction() {
if ((dialogList != null) && (dialogList.size() > dialogCount)) {
dialogCount++;
CustomDialog d = dialogList.get(dialogCount);
if (d != null) { d.setVisible(true); }
}
}
}
public static void main(String[] args) throws Exception {
(new MultipleDialogs3Test()).doTest();
}
}

@ -0,0 +1,178 @@
/*
* Copyright (c) 2007, 2014, 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 8054358 8055003
* @summary Check whether application and document modality levels for Dialog
* work properly. Also check whether the blocking dialogs are
* opening on top of the windows they block.
*
* @library ../helpers ../../../../lib/testlibrary/
* @build ExtendedRobot
* @build Flag
* @build TestDialog
* @build TestFrame
* @run main MultipleDialogs4Test
*/
import java.awt.*;
import static jdk.testlibrary.Asserts.*;
public class MultipleDialogs4Test {
private volatile TopLevelFrame frame;
private volatile CustomFrame secondFrame;
private volatile TestFrame thirdFrame;
private volatile TestDialog dialog, secondDialog, docChildDialog, appChildDialog;
private static final int delay = 500;
private void createGUI() {
frame = new TopLevelFrame();
frame.setLocation(50, 50);
frame.setVisible(true);
dialog = new TestDialog((Dialog) null);
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setLocation(150, 50);
appChildDialog = new TestDialog(dialog);
appChildDialog.setLocation(150, 90);
secondFrame = new CustomFrame();
secondFrame.setLocation(50, 250);
secondDialog = new TestDialog(secondFrame);
secondDialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
secondDialog.setLocation(150, 250);
docChildDialog = new TestDialog(secondFrame);
docChildDialog.setBackground(Color.black);
docChildDialog.setLocation(250, 250);
thirdFrame = new TestFrame();
thirdFrame.setLocation(250, 50);
}
public void doTest() throws Exception {
try {
EventQueue.invokeAndWait(this::createGUI);
final int nAttempts = 3;
ExtendedRobot robot = new ExtendedRobot();
robot.waitForIdle(delay);
frame.clickOpenButton(robot);
robot.waitForIdle(delay);
secondFrame.clickOpenButton(robot);
robot.waitForIdle(delay);
secondFrame.checkBlockedFrame(robot,
"A document modal dialog should block this Frame.");
secondDialog.checkUnblockedDialog(robot, "This is a document " +
"modal dialog. No window blocks it.");
frame.checkUnblockedFrame(robot,
"There are no dialogs blocking this Frame.");
frame.clickCloseButton(robot);
robot.waitForIdle(delay);
frame.clickDummyButton(robot, nAttempts, false,
"The frame still on top even after showing a modal dialog.");
robot.waitForIdle(delay);
EventQueue.invokeAndWait(() -> { thirdFrame.setVisible(true); });
robot.waitForIdle(delay);
dialog.clickDummyButton(robot);
robot.waitForIdle(delay);
secondDialog.clickDummyButton(
robot, nAttempts, false, "The document modal dialog " +
"was not blocked by an application modal dialog.");
robot.waitForIdle(delay);
EventQueue.invokeLater(() -> { docChildDialog.setVisible(true); });
robot.waitForIdle(delay);
Color c = robot.getPixelColor(
(int) secondDialog.getLocationOnScreen().x + secondDialog.getSize().width - 25,
(int) secondDialog.getLocationOnScreen().y + secondDialog.getSize().height - 25);
assertFalse(c.equals(Color.black), "A dialog which should be blocked " +
"by document modal dialog overlapping it.");
EventQueue.invokeLater(() -> { appChildDialog.setVisible(true); });
robot.waitForIdle(delay);
appChildDialog.activated.waitForFlagTriggered();
assertTrue(appChildDialog.activated.flag(), "The child dialog of the " +
"application modal dialog still not visible.");
robot.waitForIdle(delay);
dialog.clickDummyButton(robot, nAttempts, false, "The child dialog of " +
"the application modal dialog did not overlap it.");
robot.waitForIdle(delay);
} finally {
EventQueue.invokeAndWait(this::closeAll);
}
}
public void closeAll() {
if (frame != null) { frame.dispose(); }
if (dialog != null) { dialog.dispose(); }
if (appChildDialog != null) { appChildDialog.dispose(); }
if (secondFrame != null) { secondFrame.dispose(); }
if (secondDialog != null) { secondDialog.dispose(); }
if (docChildDialog != null) { docChildDialog.dispose(); }
if (thirdFrame != null) { thirdFrame.dispose(); }
}
class TopLevelFrame extends TestFrame {
@Override
public void doOpenAction() { secondFrame.setVisible(true); }
@Override
public void doCloseAction() { dialog.setVisible(true); }
}
class CustomFrame extends TestFrame {
@Override
public void doOpenAction() { secondDialog.setVisible(true); }
}
public static void main(String[] args) throws Exception {
(new MultipleDialogs4Test()).doTest();
}
}

@ -0,0 +1,184 @@
/*
* Copyright (c) 2007, 2014, 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 8054358
* @summary This is a simple check if a chain of dialogs having different
* modality types block each other properly.
*
* @library ../helpers ../../../../lib/testlibrary/
* @build ExtendedRobot
* @build Flag
* @build TestDialog
* @build TestFrame
* @build TestWindow
* @run main MultipleDialogs5Test
*/
import java.awt.*;
import static jdk.testlibrary.Asserts.*;
public class MultipleDialogs5Test {
private volatile ParentFrame parent;
private volatile ModalDialog appDialog, docDialog, tkDialog;
private volatile CustomWindow window;
private static int delay = 500;
private void createGUI() {
parent = new ParentFrame();
parent.setLocation(50, 50);
parent.setVisible(true);
appDialog = new ModalDialog(parent);
appDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
appDialog.setLocation(250, 50);
docDialog = new ModalDialog(appDialog);
docDialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
docDialog.setLocation(450, 50);
window = new CustomWindow(docDialog);
window.setLocation(50, 250);
tkDialog = new ModalDialog(docDialog);
tkDialog.setLocation(250, 250);
tkDialog.setModalityType(Dialog.ModalityType.TOOLKIT_MODAL);
appDialog.setWindowToOpen(docDialog);
docDialog.setWindowToOpen(window);
}
public void doTest() throws Exception {
try {
EventQueue.invokeAndWait(this::createGUI);
ExtendedRobot robot = new ExtendedRobot();
robot.waitForIdle(delay);
parent.clickOpenButton(robot);
robot.waitForIdle(delay);
parent.checkBlockedFrame(robot,
"This Frame is blocked by an application modal dialog.");
appDialog.clickOpenButton(robot);
robot.waitForIdle(delay);
appDialog.checkBlockedDialog(robot,
"This Dialog is blocked by a document modal dialog.");
docDialog.clickOpenButton(robot);
robot.waitForIdle(delay);
docDialog.checkUnblockedDialog(robot,
"This Dialog is not blocked by any modal dialog.");
window.clickOpenButton(robot);
robot.waitForIdle(delay);
window.checkBlockedWindow(robot,
"This Window is blocked by a toolkit modal dialog.");
tkDialog.clickCloseButton(robot);
robot.waitForIdle(delay);
assertFalse(tkDialog.isVisible(),
"The toolkit modal dialog was not disposed.");
window.clickCloseButton(robot);
robot.waitForIdle(delay);
assertFalse(window.isVisible(),
"The window was not disposed.");
docDialog.clickCloseButton(robot);
robot.waitForIdle(delay);
assertFalse(docDialog.isVisible(),
"The document modal dialog was not disposed.");
appDialog.clickCloseButton(robot);
robot.waitForIdle(delay);
assertFalse(appDialog.isVisible(),
"The application modal dialog was not disposed.");
} finally {
EventQueue.invokeAndWait(this::closeAll); // if something wasn't closed
}
}
private void closeAll() {
if (appDialog != null) { appDialog.dispose(); }
if (tkDialog != null) { tkDialog.dispose(); }
if (docDialog != null) { docDialog.dispose(); }
if (parent != null) { parent.dispose(); }
if (window != null) { window.dispose(); }
}
private class ParentFrame extends TestFrame {
@Override
public void doOpenAction() {
if (appDialog != null) { appDialog.setVisible(true); }
}
}
private class CustomWindow extends TestWindow {
public CustomWindow(Dialog d) { super(d); }
@Override
public void doOpenAction() {
if (tkDialog != null) { tkDialog.setVisible(true); }
}
@Override
public void doCloseAction() { this.dispose(); }
}
private class ModalDialog extends TestDialog {
private Window w;
public ModalDialog(Frame f) { super(f); }
public ModalDialog(Dialog d) { super(d); }
public void setWindowToOpen(Window w) { this.w = w; }
@Override
public void doCloseAction() { this.dispose(); }
@Override
public void doOpenAction() {
if (w != null) { w.setVisible(true); }
}
}
public static void main(String[] args) throws Exception {
(new MultipleDialogs5Test()).doTest();
}
}

@ -76,12 +76,17 @@ import java.util.concurrent.atomic.AtomicBoolean;
public final class Util {
private Util() {} // this is a helper class with static methods :)
private volatile static Robot robot;
/*
* @throws RuntimeException when creation failed
*/
public static Robot createRobot() {
try {
return new Robot();
if (robot == null) {
robot = new Robot();
}
return robot;
} catch (AWTException e) {
throw new RuntimeException("Error: unable to create robot", e);
}
@ -200,7 +205,10 @@ public final class Util {
return false;
}
public static void waitForIdle(final Robot robot) {
public static void waitForIdle(Robot robot) {
if (robot == null) {
robot = createRobot();
}
robot.waitForIdle();
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -34,10 +34,29 @@ import java.util.*;
@ExpectedGenericString("public class GenericStringTest")
public class GenericStringTest {
public static void main(String... args){
public Map<String, Integer>[] mixed = null;
public Map<String, Integer>[][] mixed2 = null;
public static void main(String... args) throws ReflectiveOperationException {
int failures = 0;
String[][] nested = {{""}};
int[][] intArray = {{1}};
failures += checkToGenericString(int.class, "int");
failures += checkToGenericString(void.class, "void");
failures += checkToGenericString(args.getClass(), "java.lang.String[]");
failures += checkToGenericString(nested.getClass(), "java.lang.String[][]");
failures += checkToGenericString(intArray.getClass(), "int[][]");
failures += checkToGenericString(java.util.Map.class, "public abstract interface java.util.Map<K,V>");
Field f = GenericStringTest.class.getDeclaredField("mixed");
// The expected value includes "<K,V>" rather than
// "<...String,...Integer>" since the Class object rather than
// Type objects is being queried.
failures += checkToGenericString(f.getType(), "java.util.Map<K,V>[]");
f = GenericStringTest.class.getDeclaredField("mixed2");
failures += checkToGenericString(f.getType(), "java.util.Map<K,V>[][]");
Class<?>[] types = {
GenericStringTest.class,

@ -0,0 +1,84 @@
/*
* 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 8067951
* @summary Unit test for internal ClassLoader#initializePath().
* Quoted entries should get unquoted on Windows.
* Empty entries should be replaced with dot.
* @library /lib/testlibrary
* @build jdk.testlibrary.Platform
* @run main LibraryPathProperty
*/
import java.lang.reflect.Method;
import java.io.File;
import java.util.Arrays;
import jdk.testlibrary.Platform;
public class LibraryPathProperty {
static final String propName = "test.property.name";
static final String SP = File.pathSeparator;
static Method method;
public static void main(String[] args) throws Throwable {
method = ClassLoader.class
.getDeclaredMethod("initializePath",
String.class);
method.setAccessible(true);
test("", ".");
test(SP, ".", ".");
test("a" + SP, "a", ".");
test(SP + "b", ".", "b");
test("a" + SP + SP + "b", "a", ".", "b");
if (Platform.isWindows()) {
// on Windows parts of paths may be quoted
test("\"\"", ".");
test("\"\"" + SP, ".", ".");
test(SP + "\"\"", ".", ".");
test("a" + SP + "\"b\"" + SP, "a", "b", ".");
test(SP + "\"a\"" + SP + SP + "b", ".", "a", ".", "b");
test("\"a\"" + SP + "\"b\"", "a", "b");
test("\"/a/\"b" + SP + "c", "/a/b", "c");
test("\"/a;b\"" + SP + "c", "/a;b", "c");
test("\"/a:b\"" + SP + "c", "/a:b", "c");
test("\"/a" + SP + "b\"" + SP + "c", "/a" + SP + "b", "c");
test("/\"a\"\";\"\"b\"" + SP + "\"c\"", "/a;b", "c");
test("/\"a:\"b" + SP + "c", "/a:b", "c");
}
}
static void test(String s, String... expected) throws Throwable {
System.setProperty(propName, s);
String[] res = (String[])method.invoke(null, propName);
if (!Arrays.asList(res).equals(Arrays.asList(expected))) {
throw new RuntimeException("Parsing [" + s + "] " +
" result " + Arrays.asList(res) +
" doesn't match " + Arrays.asList(expected));
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
@ -34,15 +34,16 @@
* @build jdk.testlibrary.* LowMemoryTest MemoryUtil RunUtil
* @requires vm.opt.ExplicitGCInvokesConcurrent == "false" | vm.opt.ExplicitGCInvokesConcurrent == "null"
* @run main/timeout=600 LowMemoryTest
* @requires vm.opt.ExplicitGCInvokesConcurrent != "true"
* @requires vm.opt.ExplicitGCInvokesConcurrentAndUnloadsClasses != "true"
* @requires vm.opt.DisableExplicitGC != "true"
*/
import com.sun.management.DiagnosticCommandMBean;
import java.lang.management.*;
import java.util.*;
import java.util.concurrent.Phaser;
import javax.management.*;
import javax.management.openmbean.CompositeData;
import sun.management.ManagementFactoryHelper;
public class LowMemoryTest {
private static final MemoryMXBean mm = ManagementFactory.getMemoryMXBean();

@ -24,7 +24,7 @@
/* @test
* @summary Unit test for java.net.URI
* @bug 4464135 4505046 4503239 4438319 4991359 4866303 7023363 7041800
* 7171415
* 7171415 6933879
* @author Mark Reinhold
*/
@ -1600,6 +1600,7 @@ public class Test {
static void bugs() {
b6339649();
b6933879();
b8037396();
}
@ -1614,6 +1615,18 @@ public class Test {
}
}
// 6933879 - check that "." and "_" characters are allowed in IPv6 scope_id.
private static void b6933879() {
final String HOST = "fe80::c00:16fe:cebe:3214%eth1.12_55";
URI uri;
try {
uri = new URI("http", null, HOST, 10, "/", null, null);
} catch (URISyntaxException ex) {
throw new AssertionError("Should not happen", ex);
}
eq("[" + HOST + "]", uri.getHost());
}
private static void b8037396() {
// primary checks:

@ -0,0 +1,110 @@
/*
* Copyright (c) 2014, 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.*;
import java.lang.reflect.Field;
import java.util.Hashtable;
/**
* @test
* @bug 8068427
* @summary Hashtable deserialization reconstitutes table with wrong capacity
*/
public class DeserializedLength {
static boolean testDeserializedLength(int elements, float loadFactor) throws Exception {
// construct Hashtable with minimal initial capacity and given loadFactor
Hashtable<Integer, Integer> ht1 = new Hashtable<>(1, loadFactor);
// add given number of unique elements
for (int i = 0; i < elements; i++) {
ht1.put(i, i);
}
// serialize and deserialize into a deep clone
Hashtable<Integer, Integer> ht2 = serialClone(ht1);
// compare lengths of internal tables
Object[] table1 = (Object[]) hashtableTableField.get(ht1);
Object[] table2 = (Object[]) hashtableTableField.get(ht2);
assert table1 != null;
assert table2 != null;
int minLength = (int) (ht1.size() / loadFactor) + 1;
int maxLength = minLength * 2;
boolean ok = (table2.length >= minLength && table2.length <= maxLength);
System.out.printf(
"%7d %5.2f %7d %7d %7d...%7d %s\n",
ht1.size(), loadFactor,
table1.length, table2.length,
minLength, maxLength,
(ok ? "OK" : "NOT-OK")
);
return ok;
}
static <T> T serialClone(T o) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(o);
}
@SuppressWarnings("unchecked")
T clone = (T) new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray())).readObject();
return clone;
}
private static final Field hashtableTableField;
static {
try {
hashtableTableField = Hashtable.class.getDeclaredField("table");
hashtableTableField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new Error(e);
}
}
public static void main(String[] args) throws Exception {
boolean ok = true;
System.out.printf("Results:\n" +
" ser. deser.\n" +
" size load lentgh length valid range ok?\n" +
"------- ----- ------- ------- ----------------- ------\n"
);
for (int elements : new int[]{10, 50, 500, 5000}) {
for (float loadFactor : new float[]{0.15f, 0.5f, 0.75f, 1.0f, 2.5f}) {
ok &= testDeserializedLength(elements, loadFactor);
}
}
if (!ok) {
throw new AssertionError("Test failed.");
}
}
}

Some files were not shown because too many files have changed in this diff Show More