提交 332b2d0c 编写于 作者: L lana

Merge

#
# Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. 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.
#
# Copyright year for beginning of Java and some of the apis
# (Needed when creating the javadocs)
FIRST_COPYRIGHT_YEAR = 1993
DOMAPI_FIRST_COPYRIGHT_YEAR = 2005
MIRROR_FIRST_COPYRIGHT_YEAR = 2004
DOCLETAPI_FIRST_COPYRIGHT_YEAR = 1993
TAGLETAPI_FIRST_COPYRIGHT_YEAR = 1993
JDI_FIRST_COPYRIGHT_YEAR = 1999
JAAS_FIRST_COPYRIGHT_YEAR = 1998
JGSS_FIRST_COPYRIGHT_YEAR = 2000
SMARTCARDIO_FIRST_COPYRIGHT_YEAR = 2005
HTTPSERVER_FIRST_COPYRIGHT_YEAR = 2005
MGMT_FIRST_COPYRIGHT_YEAR = 2003
ATTACH_FIRST_COPYRIGHT_YEAR = 2005
JCONSOLE_FIRST_COPYRIGHT_YEAR = 2006
SCTPAPI_FIRST_COPYRIGHT_YEAR = 2009
TRACING_FIRST_COPYRIGHT_YEAR = 2008
TREEAPI_FIRST_COPYRIGHT_YEAR = 2005
JNLP_FIRST_COPYRIGHT_YEAR = 1998
PLUGIN2_FIRST_COPYRIGHT_YEAR = 2007
# Oracle name
COMPANY_NAME = Oracle and/or its affiliates
# Copyright address
COMPANY_ADDRESS = 500 Oracle Parkway<br>Redwood Shores, CA 94065 USA.
# The trademark symbol
TRADEMARK = &trade;
# Common copyright lines used
# The word "Copyright" might optionally be a link to the file cpyr.html.
# The first year of copyright may vary or not be available.
# The address to the company might be optional.
COMMA:= ,
EMPTY:=
SPACE:=$(EMPTY) $(EMPTY)
COPYRIGHT_SYMBOL = &\#x00a9;
# Macros to handle the optional empty args.
# (The GNU make 3.78.1 "if" conditional is broken, fixed in GNU make 3.81)
define OptionalCopyrightUrl # url
$(shell \
if [ "$1" != "" ] ; then \
printf "<a href=\"%s\">Copyright</a>" "$1"; \
else \
printf "Copyright"; \
fi)
endef
define OptionalCopyrightFirstYear # year
$(shell \
if [ "$1" != "" ] ; then \
printf "%s," "$1";\
fi)
endef
define OptionalCompanyAddress # address
$(shell \
if [ "$1" != "" ] ; then \
printf "%s" "$1";\
fi)
endef
define CopyrightLine # optionalurl optionalfirstyear optionaladdress
$(call OptionalCopyrightUrl,$1) $(COPYRIGHT_SYMBOL)\
$(call OptionalCopyrightFirstYear,$2) $(COPYRIGHT_YEAR),\
$(COMPANY_NAME).\
$(call OptionalCompanyAddress,$3)\
All rights reserved.
endef
此差异已折叠。
......@@ -30,6 +30,7 @@
#
JAVA_JAVA_java = \
java/lang/Object.java \
java/lang/AutoCloseable.java \
java/lang/Class.java \
java/lang/Thread.java \
java/lang/Character.java \
......
#
# Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 1996, 2010 Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
......@@ -62,6 +62,11 @@ POLICY_BUILD = $(LIBDIR)/security/java.policy
CACERTS_SRC = $(CACERTS_FILE)
CACERTS_BUILD = $(LIBDIR)/security/cacerts
ifndef OPENJDK
BLACKLIST_SRC = $(CLOSED_SHARE_SRC)/lib/security/blacklist
BLACKLIST_BUILD = $(LIBDIR)/security/blacklist
endif
FILES_class = $(FILES_java:%.java=$(CLASSBINDIR)/%.class)
#
......@@ -69,7 +74,11 @@ FILES_class = $(FILES_java:%.java=$(CLASSBINDIR)/%.class)
#
include $(BUILDDIR)/common/Rules.gmk
ifdef OPENJDK
build: properties policy cacerts
else
build: properties policy cacerts blacklist
endif
install: all
......@@ -79,6 +88,8 @@ policy: classes $(POLICY_BUILD)
cacerts: classes $(CACERTS_BUILD)
blacklist: classes $(BLACKLIST_BUILD)
$(PROPS_BUILD): $(PROPS_SRC)
$(install-file)
......@@ -88,9 +99,12 @@ $(POLICY_BUILD): $(POLICY_SRC)
$(CACERTS_BUILD): $(CACERTS_SRC)
$(install-file)
$(BLACKLIST_BUILD): $(BLACKLIST_SRC)
$(install-file)
clean clobber:: .delete.classlist
$(RM) -r $(CLASSBINDIR)/java/security
$(RM) $(PROPS_BUILD) $(POLICY_BUILD) $(CACERTS_BUILD)
$(RM) $(PROPS_BUILD) $(POLICY_BUILD) $(CACERTS_BUILD) $(BLACKLIST_BUILD)
# Additional Rule for building sun.security.util
$(CLASSBINDIR)/%.class: $(SHARE_SRC)/sun/%.java
......
......@@ -28,7 +28,6 @@
* combine with an argument list of files and directories, and
* write a list of items to be included in a jar file.
*/
package build.tools.jarreorder;
import java.io.BufferedReader;
......@@ -36,74 +35,68 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Collections;
import java.util.HashSet;
import java.util.Vector;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class JarReorder {
// To deal with output
private static PrintStream out;
private final static boolean useTopDir = false;
private PrintStream out;
private static void usage() {
private void usage() {
String help;
help =
"Usage: jar JarReorder [-o <outputfile>] <order_list> <exclude_list> <file> ...\n"
+ " order_list is a file containing names of files to load\n"
+ " in order at the end of a jar file.\n"
+ " exclude_list is a file containing names of files/directories\n"
+ " NOT to be included in a jar file.\n";
if (useTopDir)
help +=
" top_dir is the top of the directory structure to be searched;\n"
+ " the contents of the lists and remaining arguments are\n"
+ " relative to this.\n";
help +=
"\n"
+ "The order_list or exclude_list may be replaced by a \"_\" if no\n"
+ "data is to be provided.\n"
+ "\n"
+ " The remaining arguments are files or directories to be included\n"
+ " in a jar file, from which will be excluded thse entries which\n"
+ " appear in the exclude list.\n";
"Usage: jar JarReorder [-o <outputfile>] <order_list> <exclude_list> <file> ...\n"
+ " order_list is a file containing names of files to load\n"
+ " in order at the end of a jar file unless\n"
+ " excluded in the exclude list.\n"
+ " exclude_list is a file containing names of files/directories\n"
+ " NOT to be included in a jar file.\n"
+ "\n"
+ "The order_list or exclude_list may be replaced by a \"-\" if no\n"
+ "data is to be provided.\n"
+ "\n"
+ " The remaining arguments are files or directories to be included\n"
+ " in a jar file, from which will be excluded those entries which\n"
+ " appear in the exclude list.\n";
System.err.println(help);
System.exit(1);
}
/*
* Create a list of files to be included in a jar file, such that the
* some the files will appear in a specific order, and allowing certain
* Create the file list to be included in a jar file, such that the
* list will appear in a specific order, and allowing certain
* files and directories to be excluded.
*
* Command line arguments are
* Command path arguments are
* - optional -o outputfile
* - name of a file containing a list of files to be included in a jar file.
* - name of a file containing a list of files (or directories) to be
* - name of a file containing a set of files to be included in a jar file.
* - name of a file containing a set of files (or directories) to be
* excluded from the jar file.
* - names of files or directories to be searched for files to include
* in the jar file.
*/
public static void main(String[] args) {
JarReorder jr = new JarReorder();
jr.run(args);
}
private void run(String args[]) {
HashMap filesExcluded = new HashMap();
Vector filesIncluded = new Vector();
int fileArgs;
String topDirName = "";
int arglen = args.length;
int argpos = 0;
// Look for "-o outputfilename" option
if ( arglen > 0 ) {
if ( arglen >= 2 && args[0].equals("-o") ) {
if (arglen > 0) {
if (arglen >= 2 && args[0].equals("-o")) {
try {
out = new PrintStream(new FileOutputStream(args[1]));
} catch ( FileNotFoundException e ) {
} catch (FileNotFoundException e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
System.exit(1);
......@@ -118,128 +111,111 @@ public class JarReorder {
out = System.out;
}
fileArgs = useTopDir ? 3 : 2;
if (arglen <= fileArgs) {
// Should be 2 or more args left
if (arglen <= 2) {
usage();
System.exit(1);
}
// Read the ordered list of files to be included in rt.jar.
// Read the list of files/directories to be excluded from rt.jar.
// Read the ordered set of files to be included in rt.jar.
// Read the set of files/directories to be excluded from rt.jar.
String classListFile = args[argpos];
String excludeListFile = args[argpos + 1];
argpos += 2;
arglen -= 2;
Vector orderList = readListFromFile(args[argpos], true);
Vector excludeList = readListFromFile(args[argpos+1], false);
if (useTopDir) {
topDirName = args[argpos+2];
if (!topDirName.endsWith(File.separator))
topDirName = topDirName + File.separator;
}
// Create 2 lists and a set of processed files
List<String> orderList = readListFromFile(classListFile, true);
List<String> excludeList = readListFromFile(excludeListFile, false);
Set<String> processed = new HashSet<String>();
// Copy these lists into filesExcluded so that these files will be excluded
// from the file list. (The orderList files will be appended later.)
// Create set of all files and directories excluded, then expand
// that list completely
Set<String> excludeSet = new HashSet<String>(excludeList);
Set<String> allFilesExcluded = expand(null, excludeSet, processed);
for (int i = 0; i < orderList.size(); ++i) {
String s = (String) orderList.elementAt(i);
filesExcluded.put(s, s);
}
for (int i = 0; i < excludeList.size(); ++i) {
String s = (String) excludeList.elementAt(i);
filesExcluded.put(s, s);
}
// Indicate all these have been processed, orderList too, kept to end.
processed.addAll(orderList);
// The remaining arguments are names of files/directories to be included
// in the jar file.
String[] files = new String[arglen - fileArgs];
for (int i = fileArgs; i < arglen; ++i) {
files[i-fileArgs] = args[argpos+i];
filesExcluded.put(args[argpos+i], args[argpos+i]);
Set<String> inputSet = new HashSet<String>();
for (int i = 0; i < arglen; ++i) {
String name = args[argpos + i];
name = cleanPath(new File(name));
if ( name != null && name.length() > 0 && !inputSet.contains(name) ) {
inputSet.add(name);
}
}
// Expand file/directory list to file list excluding those
// read from the class list.
// Expand file/directory input so we get a complete set (except ordered)
// Should be everything not excluded and not in order list.
Set<String> allFilesIncluded = expand(null, inputSet, processed);
if (useTopDir)
expand(new File(topDirName), files, filesIncluded, filesExcluded, topDirName);
else
expand(null, files, filesIncluded, filesExcluded, null);
// Create simple sorted list so we can add ordered items at end.
List<String> allFiles = new ArrayList<String>(allFilesIncluded);
Collections.sort(allFiles);
// Now add the ordered list to the end of the expanded list.
// Now add the ordered set to the end of the list.
// Add in REVERSE ORDER, so that the first element is closest to
// the end (and the index).
HashSet excludeSet = new HashSet(excludeList);
for (int i = orderList.size() - 1; i >= 0; --i) {
String s = (String) orderList.elementAt(i);
if (excludeSet.contains(s)) {
System.err.println("Included file " + s + " is also excluded, skipping.");
continue;
String s = orderList.get(i);
if (allFilesExcluded.contains(s)) {
System.err.println("Included order file " + s
+ " is also excluded, skipping.");
} else if (new File(s).exists()) {
allFiles.add(s);
} else {
System.err.println("Included order file " + s
+ " missing, skipping.");
}
if (new File(topDirName + s).exists())
filesIncluded.addElement(s);
else
System.err.println("Included file "+s+" missing, skipping.");
}
// Print results.
for (int i = 0; i < filesIncluded.size(); ++i) {
if (useTopDir) {
out.print("-C ");
out.print(topDirName);
out.print(" ");
}
out.println((String)filesIncluded.elementAt(i));
// Print final results.
for (String str : allFiles) {
out.println(str);
}
out.flush();
out.close();
}
/*
* Read a file containing a list of files into a Vector.
* Read a file containing a list of files and directories into a List.
*/
private static Vector readListFromFile(String fileName,
boolean addClassSuffix) {
private List<String> readListFromFile(String fileName,
boolean addClassSuffix) {
BufferedReader br = null;
Vector v = new Vector(2000);
if ("-".equals(fileName))
return v;
List<String> list = new ArrayList<String>();
// If you see "-" for the name, just assume nothing was provided.
if ("-".equals(fileName)) {
return list;
}
try {
br = new BufferedReader(new FileReader(fileName));
// Read the input file a line at a time. # in column 1 is a comment.
// Read the input file a path at a time. # in column 1 is a comment.
while (true) {
String line = null;
line = br.readLine();
if (line == null)
String path = br.readLine();
if (path == null) {
break;
if (line.length() == 0 ||
line.charAt(0) == '#')
}
// Look for comments
path = path.trim();
if (path.length() == 0
|| path.charAt(0) == '#') {
continue;
// Convert forward or back slashes to the type expected for
// the current platform.
if (File.separatorChar == '/')
line = line.replace('\\', '/');
else
line = line.replace('/', '\\');
line = line.trim();
if (addClassSuffix) {
if (!line.endsWith(".class")) {
line = line + ".class";
}
}
v.addElement(line);
// Add trailing .class if necessary
if (addClassSuffix && !path.endsWith(".class")) {
path = path + ".class";
}
// Normalize the path
path = cleanPath(new File(path));
// Add to list
if (path != null && path.length() > 0 && !list.contains(path)) {
list.add(path);
}
}
br.close();
} catch (FileNotFoundException e) {
......@@ -249,68 +225,89 @@ public class JarReorder {
e.printStackTrace();
System.exit(2);
}
return v;
return list;
}
/*
* Expands list of files to process into full list of all files that
* Expands inputSet (files or dirs) into full set of all files that
* can be found by recursively descending directories.
* @param dir root directory
* @param inputSet set of files or dirs to look into
* @param processed files or dirs already processed
* @return set of files
*/
private static void expand(File dir, String[] files,
Vector includedFiles, HashMap excludedFiles,
String topDirName) {
if (files == null) {
return;
private Set<String> expand(File dir,
Set<String> inputSet,
Set<String> processed) {
Set<String> includedFiles = new HashSet<String>();
if (inputSet.isEmpty()) {
return includedFiles;
}
for (int i = 0; i < files.length; i++) {
File f = (dir == null) ? new File(files[i])
: new File(dir, files[i]);
if (f.isFile()) {
String filePath = f.getPath();
if (useTopDir) {
if (filePath.startsWith(topDirName))
filePath = filePath.substring(topDirName.length());
}
if (filePath.length() >= 2 &&
filePath.charAt(0) == '.' &&
filePath.charAt(1) == File.separatorChar)
filePath = filePath.substring(2);
if (!excludedFiles.containsKey(filePath)) {
excludedFiles.put(filePath, filePath);
includedFiles.addElement(filePath);
}
} else if (f.isDirectory()) {
String dirPath = f.getPath();
dirPath = (dirPath.endsWith(File.separator)) ? dirPath :
(dirPath + File.separator);
if (useTopDir) {
if (dirPath.startsWith(topDirName))
dirPath = dirPath.substring(topDirName.length());
for (String name : inputSet) {
// Depending on start location
File f = (dir == null) ? new File(name)
: new File(dir, name);
// Normalized path to use
String path = cleanPath(f);
if (path != null && path.length() > 0
&& !processed.contains(path)) {
if (f.isFile()) {
// Not in the excludeList, add it to both lists
includedFiles.add(path);
processed.add(path);
} else if (f.isDirectory()) {
// Add the directory entries
String[] dirList = f.list();
Set<String> dirInputSet = new HashSet<String>();
for (String x : dirList) {
dirInputSet.add(x);
}
// Process all entries in this directory
Set<String> subList = expand(f, dirInputSet, processed);
includedFiles.addAll(subList);
processed.add(path);
}
}
}
return includedFiles;
}
if (dirPath.length() >= 2 &&
dirPath.charAt(0) == '.' &&
dirPath.charAt(1) == File.separatorChar)
dirPath = dirPath.substring(2);
if (!excludedFiles.containsKey(dirPath)) {
private String cleanPath(File f) {
String path = f.getPath();
if (f.isFile()) {
path = cleanFilePath(path);
} else if (f.isDirectory()) {
path = cleanDirPath(path);
} else {
System.err.println("WARNING: Path does not exist as file or directory: " + path);
path = null;
}
return path;
}
// Sort the directory list so that entries in the jar file
// are in a repeatable order. The order itself is not particularly
// important. [File.list() is unpredictable.]
private String cleanFilePath(String path) {
// Remove leading and trailing whitespace
path = path.trim();
// Make all / and \ chars one
if (File.separatorChar == '/') {
path = path.replace('\\', '/');
} else {
path = path.replace('/', '\\');
}
// Remove leading ./
if (path.startsWith("." + File.separator)) {
path = path.substring(2);
}
return path;
}
String[] dirList = f.list();
Arrays.sort(dirList);
expand(f, dirList, includedFiles, excludedFiles, topDirName);
}
} else {
System.err.println("Error accessing: " + f.getPath());
}
private String cleanDirPath(String path) {
path = cleanFilePath(path);
// Make sure it ends with a file separator
if (!path.endsWith(File.separator)) {
path = path + File.separator;
}
return path;
}
}
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -44,7 +44,7 @@
#define JVM_ERROR1 "Error: Could not create the Java Virtual Machine.\n" GEN_ERROR
#define JVM_ERROR2 "Error: Could not detach main thread.\n" JNI_ERROR
#define JVM_ERROR3 "Error: SPARC V8 processor detected; Server compiler requires V9 or better.\nUse Client compiler on V8 processors.\nCould not create the Java virtual machine."
#define JVM_ERROR3 "Error: SPARC V8 processor detected; Required V9 processors or better.\nUse JDK5 client compiler for V8 processors.\n" JVM_ERROR1
#define JAR_ERROR1 "Error: Failed to load Main-Class manifest attribute from\n%s\n%s"
#define JAR_ERROR2 "Error: Unable to access jarfile %s"
......@@ -69,7 +69,8 @@
#define CFG_ERROR5 "Error: Could not determine application home."
#define CFG_ERROR6 "Error: could not open `%s'"
#define CFG_ERROR7 "Error: no known VMs. (check for corrupt jvm.cfg file)"
#define CFG_ERROR8 "Error: no `%s' JVM at `%s'."
#define CFG_ERROR8 "Error: missing `%s' JVM at `%s'.\nPlease install or use the JRE or JDK that contains these missing components."
#define CFG_ERROR9 "Error: could not determine JVM type."
#define SPC_ERROR1 "Error: Syntax error in version specification \"%s\""
......
/*
* Copyright (c) 1995, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -192,8 +192,8 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */
int ret;
InvocationFunctions ifn;
jlong start, end;
char jrepath[MAXPATHLEN], jvmpath[MAXPATHLEN];
char ** original_argv = argv;
char jvmpath[MAXPATHLEN];
char jrepath[MAXPATHLEN];
_fVersion = fullversion;
_dVersion = dotversion;
......@@ -225,14 +225,17 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */
*/
SelectVersion(argc, argv, &main_class);
/* copy original argv */
JLI_TraceLauncher("Command line Args:\n");
original_argv = (JLI_CopyArgs(argc, (const char**)argv));
if (JLI_IsTraceLauncher()) {
int i;
printf("Command line args:\n");
for (i = 0; i < argc ; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
CreateExecutionEnvironment(&argc, &argv,
jrepath, sizeof(jrepath),
jvmpath, sizeof(jvmpath),
original_argv);
jvmpath, sizeof(jvmpath));
ifn.CreateJavaVM = 0;
ifn.GetDefaultJavaVMInitArgs = 0;
......@@ -301,22 +304,43 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */
return ContinueInNewThread(&ifn, argc, argv, jarfile, classname, ret);
}
/*
* Always detach the main thread so that it appears to have ended when
* the application's main method exits. This will invoke the
* uncaught exception handler machinery if main threw an
* exception. An uncaught exception handler cannot change the
* launcher's return code except by calling System.exit.
*
* Wait for all non-daemon threads to end, then destroy the VM.
* This will actually create a trivial new Java waiter thread
* named "DestroyJavaVM", but this will be seen as a different
* thread from the one that executed main, even though they are
* the same C thread. This allows mainThread.join() and
* mainThread.isAlive() to work as expected.
*/
#define LEAVE() \
if ((*vm)->DetachCurrentThread(vm) != 0) { \
JLI_ReportErrorMessage(JVM_ERROR2); \
ret = 1; \
} \
(*vm)->DestroyJavaVM(vm); \
return ret \
#define CHECK_EXCEPTION_NULL_LEAVE(e) \
if ((*env)->ExceptionOccurred(env)) { \
JLI_ReportExceptionDescription(env); \
goto leave; \
LEAVE(); \
} \
if ((e) == NULL) { \
JLI_ReportErrorMessage(JNI_ERROR); \
goto leave; \
LEAVE(); \
}
#define CHECK_EXCEPTION_LEAVE(rv) \
if ((*env)->ExceptionOccurred(env)) { \
JLI_ReportExceptionDescription(env); \
ret = (rv); \
goto leave; \
LEAVE(); \
}
int JNICALL
......@@ -349,8 +373,7 @@ JavaMain(void * _args)
PrintJavaVersion(env, showVersion);
CHECK_EXCEPTION_LEAVE(0);
if (printVersion) {
ret = 0;
goto leave;
LEAVE();
}
}
......@@ -358,7 +381,7 @@ JavaMain(void * _args)
if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) {
PrintUsage(env, printXUsage);
CHECK_EXCEPTION_LEAVE(1);
goto leave;
LEAVE();
}
FreeKnownVMs(); /* after last possible PrintUsage() */
......@@ -430,30 +453,7 @@ JavaMain(void * _args)
* System.exit) will be non-zero if main threw an exception.
*/
ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;
leave:
/*
* Always detach the main thread so that it appears to have ended when
* the application's main method exits. This will invoke the
* uncaught exception handler machinery if main threw an
* exception. An uncaught exception handler cannot change the
* launcher's return code except by calling System.exit.
*/
if ((*vm)->DetachCurrentThread(vm) != 0) {
JLI_ReportErrorMessage(JVM_ERROR2);
ret = 1;
}
/*
* Wait for all non-daemon threads to end, then destroy the VM.
* This will actually create a trivial new Java waiter thread
* named "DestroyJavaVM", but this will be seen as a different
* thread from the one that executed main, even though they are
* the same C thread. This allows mainThread.join() and
* mainThread.isAlive() to work as expected.
*/
(*vm)->DestroyJavaVM(vm);
return ret;
LEAVE();
}
/*
......@@ -1076,15 +1076,17 @@ ParseArguments(int *pargc, char ***pargv, char **pjarfile,
if (--argc >= 0) {
if (jarflag) {
*pjarfile = *argv++;
*pclassname = 0;
*pclassname = NULL;
} else {
*pjarfile = 0;
*pjarfile = NULL;
*pclassname = *argv++;
}
*pargc = argc;
*pargv = argv;
}
if (*pjarfile == NULL && *pclassname == NULL) {
*pret = 1;
}
return JNI_TRUE;
}
......
/*
* Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -114,13 +114,19 @@ GetApplicationHome(char *buf, jint bufsize);
#define GetArch() GetArchPath(CURRENT_DATA_MODEL)
void CreateExecutionEnvironment(int *_argc,
char ***_argv,
char jrepath[],
jint so_jrepath,
char jvmpath[],
jint so_jvmpath,
char **original_argv);
/*
* Different platforms will implement this, here
* pargc is a pointer to the original argc,
* pargv is a pointer to the original argv,
* jrepath is an accessible path to the jre as determined by the call
* so_jrepath is the length of the buffer jrepath
* jvmpath is an accessible path to the jvm as determined by the call
* so_jvmpath is the length of the buffer jvmpath
*/
void CreateExecutionEnvironment(int *argc, char ***argv,
char *jrepath, jint so_jrepath,
char *jvmpath, jint so_jvmpath);
/* Reports an error message to stderr or a window as appropriate. */
void JLI_ReportErrorMessage(const char * message, ...);
......
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -84,23 +84,6 @@ JLI_MemFree(void *ptr)
free(ptr);
}
/*
* Makes a copy of arguments
*/
char**
JLI_CopyArgs(int argc, const char **iargv)
{
int i;
char** oargv = (char**)JLI_MemAlloc(sizeof(char*)*(argc+1));
for (i = 0 ; i < argc+1 ; i++) {
oargv[i] = (iargv[i] == NULL) ? NULL : JLI_StringDup(iargv[i]);
if (iargv[i] != NULL && JLI_IsTraceLauncher() == JNI_TRUE) {
printf("\targv[%d] = '%s'\n",i,iargv[i]);
}
}
return oargv;
}
/*
* debug helpers we use
*/
......
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -33,7 +33,6 @@ void *JLI_MemAlloc(size_t size);
void *JLI_MemRealloc(void *ptr, size_t size);
char *JLI_StringDup(const char *s1);
void JLI_MemFree(void *ptr);
char **JLI_CopyArgs(int argc, const char **iargv);
int JLI_StrCCmp(const char *s1, const char* s2);
......@@ -56,10 +55,12 @@ int JLI_StrCCmp(const char *s1, const char* s2);
#include <io.h>
#define JLI_StrCaseCmp(p1, p2) stricmp((p1), (p2))
#define JLI_StrNCaseCmp(p1, p2, p3) strnicmp((p1), (p2), (p3))
#define JLI_Snprintf _snprintf
#else
#include <unistd.h>
#define JLI_StrCaseCmp(p1, p2) strcasecmp((p1), (p2))
#define JLI_StrNCaseCmp(p1, p2, p3) strncasecmp((p1), (p2), (p3))
#define JLI_Snprintf snprintf
#endif /* _WIN32 */
/*
......
......@@ -60,7 +60,7 @@ import org.xml.sax.helpers.DefaultHandler;
*
* @author Philip Milne
*/
public class XMLDecoder {
public class XMLDecoder implements AutoCloseable {
private final DocumentHandler handler = new DocumentHandler();
private final InputSource input;
private Object owner;
......
......@@ -204,7 +204,7 @@ import java.nio.charset.UnsupportedCharsetException;
*
* @author Philip Milne
*/
public class XMLEncoder extends Encoder {
public class XMLEncoder extends Encoder implements AutoCloseable {
private final CharsetEncoder encoder;
private final String charset;
......
......@@ -41,51 +41,39 @@ class Bits {
}
static char getChar(byte[] b, int off) {
return (char) (((b[off + 1] & 0xFF) << 0) +
((b[off + 0]) << 8));
return (char) ((b[off + 1] & 0xFF) +
(b[off] << 8));
}
static short getShort(byte[] b, int off) {
return (short) (((b[off + 1] & 0xFF) << 0) +
((b[off + 0]) << 8));
return (short) ((b[off + 1] & 0xFF) +
(b[off] << 8));
}
static int getInt(byte[] b, int off) {
return ((b[off + 3] & 0xFF) << 0) +
((b[off + 2] & 0xFF) << 8) +
return ((b[off + 3] & 0xFF) ) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off + 0]) << 24);
((b[off ] ) << 24);
}
static float getFloat(byte[] b, int off) {
int i = ((b[off + 3] & 0xFF) << 0) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off + 0]) << 24);
return Float.intBitsToFloat(i);
return Float.intBitsToFloat(getInt(b, off));
}
static long getLong(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) << 0) +
((b[off + 6] & 0xFFL) << 8) +
return ((b[off + 7] & 0xFFL) ) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off + 0]) << 56);
(((long) b[off]) << 56);
}
static double getDouble(byte[] b, int off) {
long j = ((b[off + 7] & 0xFFL) << 0) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off + 0]) << 56);
return Double.longBitsToDouble(j);
return Double.longBitsToDouble(getLong(b, off));
}
/*
......@@ -98,50 +86,38 @@ class Bits {
}
static void putChar(byte[] b, int off, char val) {
b[off + 1] = (byte) (val >>> 0);
b[off + 0] = (byte) (val >>> 8);
b[off + 1] = (byte) (val );
b[off ] = (byte) (val >>> 8);
}
static void putShort(byte[] b, int off, short val) {
b[off + 1] = (byte) (val >>> 0);
b[off + 0] = (byte) (val >>> 8);
b[off + 1] = (byte) (val );
b[off ] = (byte) (val >>> 8);
}
static void putInt(byte[] b, int off, int val) {
b[off + 3] = (byte) (val >>> 0);
b[off + 2] = (byte) (val >>> 8);
b[off + 3] = (byte) (val );
b[off + 2] = (byte) (val >>> 8);
b[off + 1] = (byte) (val >>> 16);
b[off + 0] = (byte) (val >>> 24);
b[off ] = (byte) (val >>> 24);
}
static void putFloat(byte[] b, int off, float val) {
int i = Float.floatToIntBits(val);
b[off + 3] = (byte) (i >>> 0);
b[off + 2] = (byte) (i >>> 8);
b[off + 1] = (byte) (i >>> 16);
b[off + 0] = (byte) (i >>> 24);
putInt(b, off, Float.floatToIntBits(val));
}
static void putLong(byte[] b, int off, long val) {
b[off + 7] = (byte) (val >>> 0);
b[off + 6] = (byte) (val >>> 8);
b[off + 7] = (byte) (val );
b[off + 6] = (byte) (val >>> 8);
b[off + 5] = (byte) (val >>> 16);
b[off + 4] = (byte) (val >>> 24);
b[off + 3] = (byte) (val >>> 32);
b[off + 2] = (byte) (val >>> 40);
b[off + 1] = (byte) (val >>> 48);
b[off + 0] = (byte) (val >>> 56);
b[off ] = (byte) (val >>> 56);
}
static void putDouble(byte[] b, int off, double val) {
long j = Double.doubleToLongBits(val);
b[off + 7] = (byte) (j >>> 0);
b[off + 6] = (byte) (j >>> 8);
b[off + 5] = (byte) (j >>> 16);
b[off + 4] = (byte) (j >>> 24);
b[off + 3] = (byte) (j >>> 32);
b[off + 2] = (byte) (j >>> 40);
b[off + 1] = (byte) (j >>> 48);
b[off + 0] = (byte) (j >>> 56);
putLong(b, off, Double.doubleToLongBits(val));
}
}
......@@ -28,14 +28,14 @@ package java.io;
import java.io.IOException;
/**
* A <tt>Closeable</tt> is a source or destination of data that can be closed.
* A {@code Closeable} is a source or destination of data that can be closed.
* The close method is invoked to release resources that the object is
* holding (such as open files).
*
* @since 1.5
*/
public interface Closeable {
public interface Closeable extends AutoCloseable {
/**
* Closes this stream and releases any system resources associated
......@@ -45,5 +45,4 @@ public interface Closeable {
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
}
......@@ -36,7 +36,7 @@ package java.io;
* @see java.io.ObjectInputStream
* @since JDK1.1
*/
public interface ObjectInput extends DataInput {
public interface ObjectInput extends DataInput, AutoCloseable {
/**
* Read and return an object. The class that implements this interface
* defines where the object is "read" from.
......
......@@ -36,7 +36,7 @@ package java.io;
* @see java.io.ObjectInputStream
* @since JDK1.1
*/
public interface ObjectOutput extends DataOutput {
public interface ObjectOutput extends DataOutput, AutoCloseable {
/**
* Write an object to the underlying storage or stream. The
* class that implements this interface defines how the object is
......
......@@ -721,19 +721,18 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence {
* {@code codePoint} isn't a valid Unicode code point
*/
public AbstractStringBuilder appendCodePoint(int codePoint) {
if (!Character.isValidCodePoint(codePoint)) {
throw new IllegalArgumentException();
}
int n = 1;
if (codePoint >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
n++;
}
ensureCapacityInternal(count + n);
if (n == 1) {
value[count++] = (char) codePoint;
} else {
final int count = this.count;
if (Character.isBmpCodePoint(codePoint)) {
ensureCapacityInternal(count + 1);
value[count] = (char) codePoint;
this.count = count + 1;
} else if (Character.isValidCodePoint(codePoint)) {
ensureCapacityInternal(count + 2);
Character.toSurrogates(codePoint, value, count);
count += n;
this.count = count + 2;
} else {
throw new IllegalArgumentException();
}
return this;
}
......
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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 java.lang;
/**
* A resource that must be closed when it is no longer needed.
*
* @author Josh Bloch
* @since 1.7
*/
public interface AutoCloseable {
/**
* Close this resource, relinquishing any underlying resources.
* This method is invoked automatically by the automatic resource
* management block construct.
*
* <p>Classes implementing this method are strongly encouraged to
* be declared to throw more specific exceptions (or no exception
* at all, if the close cannot fail).
*
* @throws Exception if this resource cannot be closed
*/
void close() throws Exception;
}
......@@ -38,7 +38,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The <code>String</code> class represents character strings. All
* string literals in Java programs, such as <code>"abc"</code>, are
......@@ -99,6 +98,8 @@ import java.util.regex.PatternSyntaxException;
*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Martin Buchholz
* @author Ulf Zibis
* @see java.lang.Object#toString()
* @see java.lang.StringBuffer
* @see java.lang.StringBuilder
......@@ -273,32 +274,32 @@ public final class String
throw new StringIndexOutOfBoundsException(offset + count);
}
final int end = offset + count;
// Pass 1: Compute precise size of char[]
int n = 0;
for (int i = offset; i < offset + count; i++) {
int n = count;
for (int i = offset; i < end; i++) {
int c = codePoints[i];
if (c >= Character.MIN_CODE_POINT &&
c < Character.MIN_SUPPLEMENTARY_CODE_POINT)
n += 1;
else if (Character.isSupplementaryCodePoint(c))
n += 2;
if (Character.isBmpCodePoint(c))
continue;
else if (Character.isValidCodePoint(c))
n++;
else throw new IllegalArgumentException(Integer.toString(c));
}
// Pass 2: Allocate and fill in char[]
char[] v = new char[n];
for (int i = offset, j = 0; i < offset + count; i++) {
final char[] v = new char[n];
for (int i = offset, j = 0; i < end; i++, j++) {
int c = codePoints[i];
if (c < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
v[j++] = (char) c;
} else {
Character.toSurrogates(c, v, j);
j += 2;
}
if (Character.isBmpCodePoint(c))
v[j] = (char) c;
else
Character.toSurrogates(c, v, j++);
}
this.value = v;
this.count = v.length;
this.count = n;
this.offset = 0;
}
......@@ -1573,9 +1574,6 @@ public final class String
* if the character does not occur.
*/
public int indexOf(int ch, int fromIndex) {
int max = offset + count;
char v[] = value;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= count) {
......@@ -1583,29 +1581,36 @@ public final class String
return -1;
}
int i = offset + fromIndex;
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
for (; i < max ; i++) {
if (v[i] == ch) {
final char[] value = this.value;
final int offset = this.offset;
final int max = offset + count;
for (int i = offset + fromIndex; i < max ; i++) {
if (value[i] == ch) {
return i - offset;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
if (ch <= Character.MAX_CODE_POINT) {
// handle supplementary characters here
char[] surrogates = Character.toChars(ch);
for (; i < max; i++) {
if (v[i] == surrogates[0]) {
if (i + 1 == max) {
break;
}
if (v[i+1] == surrogates[1]) {
return i - offset;
}
/**
* Handles (rare) calls of indexOf with a supplementary character.
*/
private int indexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
final int offset = this.offset;
final char hi = Character.highSurrogate(ch);
final char lo = Character.lowSurrogate(ch);
final int max = offset + count - 1;
for (int i = offset + fromIndex; i < max; i++) {
if (value[i] == hi && value[i+1] == lo) {
return i - offset;
}
}
}
......@@ -1674,34 +1679,36 @@ public final class String
* if the character does not occur before that point.
*/
public int lastIndexOf(int ch, int fromIndex) {
int min = offset;
char v[] = value;
int i = offset + ((fromIndex >= count) ? count - 1 : fromIndex);
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
for (; i >= min ; i--) {
if (v[i] == ch) {
final char[] value = this.value;
final int offset = this.offset;
int i = offset + Math.min(fromIndex, count - 1);
for (; i >= offset ; i--) {
if (value[i] == ch) {
return i - offset;
}
}
return -1;
} else {
return lastIndexOfSupplementary(ch, fromIndex);
}
}
int max = offset + count;
if (ch <= Character.MAX_CODE_POINT) {
// handle supplementary characters here
char[] surrogates = Character.toChars(ch);
for (; i >= min; i--) {
if (v[i] == surrogates[0]) {
if (i + 1 == max) {
break;
}
if (v[i+1] == surrogates[1]) {
return i - offset;
}
/**
* Handles (rare) calls of lastIndexOf with a supplementary character.
*/
private int lastIndexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
final int offset = this.offset;
char hi = Character.highSurrogate(ch);
char lo = Character.lowSurrogate(ch);
int i = offset + Math.min(fromIndex, count - 2);
for (; i >= offset; i--) {
if (value[i] == hi && value[i+1] == lo) {
return i - offset;
}
}
}
......@@ -1710,18 +1717,17 @@ public final class String
/**
* Returns the index within this string of the first occurrence of the
* specified substring. The integer returned is the smallest value
* <i>k</i> such that:
* specified substring.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* is <code>true</code>.
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str any string.
* @return if the string argument occurs as a substring within this
* object, then the index of the first character of the first
* such substring is returned; if it does not occur as a
* substring, <code>-1</code> is returned.
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
return indexOf(str, 0);
......@@ -1729,17 +1735,19 @@ public final class String
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index. The integer
* returned is the smallest value <tt>k</tt> for which:
* specified substring, starting at the specified index.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* k &gt;= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
* <i>k</i> &gt;= fromIndex && this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then -1 is returned.
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring for which to search.
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, offset, count,
......@@ -1798,20 +1806,19 @@ public final class String
}
/**
* Returns the index within this string of the rightmost occurrence
* of the specified substring. The rightmost empty string "" is
* considered to occur at the index value <code>this.length()</code>.
* The returned index is the largest value <i>k</i> such that
* Returns the index within this string of the last occurrence of the
* specified substring. The last occurrence of the empty string ""
* is considered to occur at the index value {@code this.length()}.
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, k)
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* is true.
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return if the string argument occurs one or more times as a substring
* within this object, then the index of the first character of
* the last such substring is returned. If it does not occur as
* a substring, <code>-1</code> is returned.
* @return the index of the last occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str) {
return lastIndexOf(str, count);
......@@ -1820,16 +1827,18 @@ public final class String
/**
* Returns the index within this string of the last occurrence of the
* specified substring, searching backward starting at the specified index.
* The integer returned is the largest value <i>k</i> such that:
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* k &lt;= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
* <i>k</i> &lt;= fromIndex && this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then -1 is returned.
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index to start the search from.
* @return the index within this string of the last occurrence of the
* specified substring.
* @return the index of the last occurrence of the specified substring,
* searching backward from the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str, int fromIndex) {
return lastIndexOf(value, offset, count,
......
......@@ -69,7 +69,7 @@ public final class System {
* corresponds to keyboard input or another input source specified by
* the host environment or user.
*/
public final static InputStream in = nullInputStream();
public final static InputStream in = null;
/**
* The "standard" output stream. This stream is already
......@@ -96,7 +96,7 @@ public final class System {
* @see java.io.PrintStream#println(java.lang.Object)
* @see java.io.PrintStream#println(java.lang.String)
*/
public final static PrintStream out = nullPrintStream();
public final static PrintStream out = null;
/**
* The "standard" error output stream. This stream is already
......@@ -110,7 +110,7 @@ public final class System {
* variable <code>out</code>, has been redirected to a file or other
* destination that is typically not continuously monitored.
*/
public final static PrintStream err = nullPrintStream();
public final static PrintStream err = null;
/* The security manager for the system.
*/
......@@ -1092,26 +1092,6 @@ public final class System {
*/
public static native String mapLibraryName(String libname);
/**
* The following two methods exist because in, out, and err must be
* initialized to null. The compiler, however, cannot be permitted to
* inline access to them, since they are later set to more sensible values
* by initializeSystemClass().
*/
private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
/**
* Initialize the system class. Called after thread initialization.
*/
......
......@@ -25,6 +25,7 @@
package java.lang;
import java.io.*;
import java.util.*;
/**
* The <code>Throwable</code> class is the superclass of all errors and
......@@ -102,7 +103,7 @@ import java.io.*;
* lowLevelOp();
* } catch (LowLevelException le) {
* throw (HighLevelException)
new HighLevelException().initCause(le); // Legacy constructor
* new HighLevelException().initCause(le); // Legacy constructor
* }
* </pre>
*
......@@ -192,6 +193,24 @@ public class Throwable implements Serializable {
* nulled out when fillInStackTrace is called.
*/
/**
* The list of suppressed exceptions, as returned by
* {@link #getSuppressedExceptions()}.
*
* @serial
* @since 1.7
*/
private List<Throwable> suppressedExceptions = Collections.emptyList();
/** Message for trying to suppress a null exception. */
private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
/** Caption for labeling causative exception stack traces */
private static final String CAUSE_CAPTION = "Caused by: ";
/** Caption for labeling suppressed exception stack traces */
private static final String SUPPRESSED_CAPTION = "Suppressed: ";
/**
* Constructs a new throwable with <code>null</code> as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
......@@ -469,6 +488,52 @@ public class Throwable implements Serializable {
* class LowLevelException extends Exception {
* }
* </pre>
* As of release 7, the platform supports the notion of
* <i>suppressed exceptions</i> (in conjunction with automatic
* resource management blocks). Any exceptions that were
* suppressed in order to deliver an exception are printed out
* beneath the stack trace. The format of this information
* depends on the implementation, but the following example may be
* regarded as typical:
*
* <pre>
* Exception in thread "main" java.lang.Exception: Something happened
* at Foo.bar(Foo.java:10)
* at Foo.main(Foo.java:5)
* Suppressed: Resource$CloseFailException: Resource ID = 0
* at Resource.close(Resource.java:26)
* at Foo.bar(Foo.java:9)
* ... 1 more
* </pre>
* Note that the "... n more" notation is used on suppressed exceptions
* just at it is used on causes. Unlike causes, suppressed exceptions are
* indented beyond their "containing exceptions."
*
* <p>An exception can have both a cause and one or more suppressed
* exceptions:
* <pre>
* Exception in thread "main" java.lang.Exception: Main block
* at Foo3.main(Foo3.java:7)
* Suppressed: Resource$CloseFailException: Resource ID = 2
* at Resource.close(Resource.java:26)
* at Foo3.main(Foo3.java:5)
* Suppressed: Resource$CloseFailException: Resource ID = 1
* at Resource.close(Resource.java:26)
* at Foo3.main(Foo3.java:5)
* Caused by: java.lang.Exception: I did it
* at Foo3.main(Foo3.java:8)
* </pre>
* Likewise, a suppressed exception can have a cause:
* <pre>
* Exception in thread "main" java.lang.Exception: Main block
* at Foo4.main(Foo4.java:6)
* Suppressed: Resource2$CloseFailException: Resource ID = 1
* at Resource2.close(Resource2.java:20)
* at Foo4.main(Foo4.java:5)
* Caused by: java.lang.Exception: Rats, you caught me
* at Resource2$CloseFailException.<init>(Resource2.java:45)
* ... 2 more
* </pre>
*/
public void printStackTrace() {
printStackTrace(System.err);
......@@ -480,44 +545,71 @@ public class Throwable implements Serializable {
* @param s <code>PrintStream</code> to use for output
*/
public void printStackTrace(PrintStream s) {
synchronized (s) {
printStackTrace(new WrappedPrintStream(s));
}
private void printStackTrace(PrintStreamOrWriter s) {
Set<Throwable> dejaVu = new HashSet<Throwable>();
dejaVu.add(this);
synchronized (s.lock()) {
// Print our stack trace
s.println(this);
StackTraceElement[] trace = getOurStackTrace();
for (int i=0; i < trace.length; i++)
s.println("\tat " + trace[i]);
for (StackTraceElement traceElement : trace)
s.println("\tat " + traceElement);
// Print suppressed exceptions, if any
for (Throwable se : suppressedExceptions)
se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
// Print cause, if any
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printStackTraceAsCause(s, trace);
ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
}
}
/**
* Print our stack trace as a cause for the specified stack trace.
* Print our stack trace as an enclosed exception for the specified
* stack trace.
*/
private void printStackTraceAsCause(PrintStream s,
StackTraceElement[] causedTrace)
{
// assert Thread.holdsLock(s);
// Compute number of frames in common between this and caused
StackTraceElement[] trace = getOurStackTrace();
int m = trace.length-1, n = causedTrace.length-1;
while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) {
m--; n--;
private void printEnclosedStackTrace(PrintStreamOrWriter s,
StackTraceElement[] enclosingTrace,
String caption,
String prefix,
Set<Throwable> dejaVu) {
assert Thread.holdsLock(s.lock());
if (dejaVu.contains(this)) {
s.println("\t[CIRCULAR REFERENCE:" + this + "]");
} else {
dejaVu.add(this);
// Compute number of frames in common between this and enclosing trace
StackTraceElement[] trace = getOurStackTrace();
int m = trace.length - 1;
int n = enclosingTrace.length - 1;
while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
m--; n--;
}
int framesInCommon = trace.length - 1 - m;
// Print our stack trace
s.println(prefix + caption + this);
for (int i = 0; i <= m; i++)
s.println(prefix + "\tat " + trace[i]);
if (framesInCommon != 0)
s.println(prefix + "\t... " + framesInCommon + " more");
// Print suppressed exceptions, if any
for (Throwable se : suppressedExceptions)
se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
prefix +"\t", dejaVu);
// Print cause, if any
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
}
int framesInCommon = trace.length - 1 - m;
s.println("Caused by: " + this);
for (int i=0; i <= m; i++)
s.println("\tat " + trace[i]);
if (framesInCommon != 0)
s.println("\t... " + framesInCommon + " more");
// Recurse if we have a cause
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printStackTraceAsCause(s, trace);
}
/**
......@@ -528,44 +620,51 @@ public class Throwable implements Serializable {
* @since JDK1.1
*/
public void printStackTrace(PrintWriter s) {
synchronized (s) {
s.println(this);
StackTraceElement[] trace = getOurStackTrace();
for (int i=0; i < trace.length; i++)
s.println("\tat " + trace[i]);
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printStackTraceAsCause(s, trace);
}
printStackTrace(new WrappedPrintWriter(s));
}
/**
* Print our stack trace as a cause for the specified stack trace.
* Wrapper class for PrintStream and PrintWriter to enable a single
* implementation of printStackTrace.
*/
private void printStackTraceAsCause(PrintWriter s,
StackTraceElement[] causedTrace)
{
// assert Thread.holdsLock(s);
private abstract static class PrintStreamOrWriter {
/** Returns the object to be locked when using this StreamOrWriter */
abstract Object lock();
/** Prints the specified string as a line on this StreamOrWriter */
abstract void println(Object o);
}
private static class WrappedPrintStream extends PrintStreamOrWriter {
private final PrintStream printStream;
WrappedPrintStream(PrintStream printStream) {
this.printStream = printStream;
}
Object lock() {
return printStream;
}
void println(Object o) {
printStream.println(o);
}
}
private static class WrappedPrintWriter extends PrintStreamOrWriter {
private final PrintWriter printWriter;
WrappedPrintWriter(PrintWriter printWriter) {
this.printWriter = printWriter;
}
Object lock() {
return printWriter;
}
// Compute number of frames in common between this and caused
StackTraceElement[] trace = getOurStackTrace();
int m = trace.length-1, n = causedTrace.length-1;
while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) {
m--; n--;
void println(Object o) {
printWriter.println(o);
}
int framesInCommon = trace.length - 1 - m;
s.println("Caused by: " + this);
for (int i=0; i <= m; i++)
s.println("\tat " + trace[i]);
if (framesInCommon != 0)
s.println("\t... " + framesInCommon + " more");
// Recurse if we have a cause
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printStackTraceAsCause(s, trace);
}
/**
......@@ -667,10 +766,60 @@ public class Throwable implements Serializable {
*/
native StackTraceElement getStackTraceElement(int index);
private synchronized void writeObject(java.io.ObjectOutputStream s)
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject(); // read in all fields
List<Throwable> suppressed = Collections.emptyList();
if (suppressedExceptions != null &&
!suppressedExceptions.isEmpty()) { // Copy Throwables to new list
suppressed = new ArrayList<Throwable>();
for(Throwable t : suppressedExceptions) {
if (t == null)
throw new NullPointerException(NULL_CAUSE_MESSAGE);
suppressed.add(t);
}
}
suppressedExceptions = suppressed;
}
private synchronized void writeObject(ObjectOutputStream s)
throws IOException
{
getOurStackTrace(); // Ensure that stackTrace field is initialized.
s.defaultWriteObject();
}
/**
* Adds the specified exception to the list of exceptions that
* were suppressed, typically by the automatic resource management
* statement, in order to deliver this exception.
*
* @param exception the exception to be added to the list of
* suppressed exceptions
* @throws NullPointerException if {@code exception} is null
* @since 1.7
*/
public synchronized void addSuppressedException(Throwable exception) {
if (exception == null)
throw new NullPointerException(NULL_CAUSE_MESSAGE);
if (suppressedExceptions.size() == 0)
suppressedExceptions = new ArrayList<Throwable>();
suppressedExceptions.add(exception);
}
private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
/**
* Returns an array containing all of the exceptions that were
* suppressed, typically by the automatic resource management
* statement, in order to deliver this exception.
*
* @return an array containing all of the exceptions that were
* suppressed to deliver this exception.
* @since 1.7
*/
public Throwable[] getSuppressedExceptions() {
return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
}
}
......@@ -427,8 +427,9 @@ class Inet6Address extends InetAddress {
try {
scope_id = deriveNumericScope (scope_ifname);
} catch (UnknownHostException e) {
// should not happen
assert false;
// typically should not happen, but it may be that
// the machine being used for deserialization has
// the same interface name but without IPv6 configured.
}
}
} catch (SocketException e) {}
......
......@@ -41,25 +41,19 @@ class Bits { // package-private
// -- Swapping --
static short swap(short x) {
return (short)((x << 8) |
((char)x >>> 8));
return Short.reverseBytes(x);
}
static char swap(char x) {
return (char)((x << 8) |
(x >>> 8));
return Character.reverseBytes(x);
}
static int swap(int x) {
return ((x << 24) |
((x & 0x0000ff00) << 8) |
((x & 0x00ff0000) >>> 8) |
(x >>> 24));
return Integer.reverseBytes(x);
}
static long swap(long x) {
return (((long)swap((int)x) << 32) |
((long)swap((int)(x >>> 32)) & 0xffffffffL));
return Long.reverseBytes(x);
}
......@@ -71,52 +65,52 @@ class Bits { // package-private
static char getCharL(ByteBuffer bb, int bi) {
return makeChar(bb._get(bi + 1),
bb._get(bi + 0));
bb._get(bi ));
}
static char getCharL(long a) {
return makeChar(_get(a + 1),
_get(a + 0));
_get(a ));
}
static char getCharB(ByteBuffer bb, int bi) {
return makeChar(bb._get(bi + 0),
return makeChar(bb._get(bi ),
bb._get(bi + 1));
}
static char getCharB(long a) {
return makeChar(_get(a + 0),
return makeChar(_get(a ),
_get(a + 1));
}
static char getChar(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getCharB(bb, bi) : getCharL(bb, bi));
return bigEndian ? getCharB(bb, bi) : getCharL(bb, bi);
}
static char getChar(long a, boolean bigEndian) {
return (bigEndian ? getCharB(a) : getCharL(a));
return bigEndian ? getCharB(a) : getCharL(a);
}
private static byte char1(char x) { return (byte)(x >> 8); }
private static byte char0(char x) { return (byte)(x >> 0); }
private static byte char0(char x) { return (byte)(x ); }
static void putCharL(ByteBuffer bb, int bi, char x) {
bb._put(bi + 0, char0(x));
bb._put(bi , char0(x));
bb._put(bi + 1, char1(x));
}
static void putCharL(long a, char x) {
_put(a + 0, char0(x));
_put(a , char0(x));
_put(a + 1, char1(x));
}
static void putCharB(ByteBuffer bb, int bi, char x) {
bb._put(bi + 0, char1(x));
bb._put(bi , char1(x));
bb._put(bi + 1, char0(x));
}
static void putCharB(long a, char x) {
_put(a + 0, char1(x));
_put(a , char1(x));
_put(a + 1, char0(x));
}
......@@ -143,52 +137,52 @@ class Bits { // package-private
static short getShortL(ByteBuffer bb, int bi) {
return makeShort(bb._get(bi + 1),
bb._get(bi + 0));
bb._get(bi ));
}
static short getShortL(long a) {
return makeShort(_get(a + 1),
_get(a));
_get(a ));
}
static short getShortB(ByteBuffer bb, int bi) {
return makeShort(bb._get(bi + 0),
return makeShort(bb._get(bi ),
bb._get(bi + 1));
}
static short getShortB(long a) {
return makeShort(_get(a),
return makeShort(_get(a ),
_get(a + 1));
}
static short getShort(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getShortB(bb, bi) : getShortL(bb, bi));
return bigEndian ? getShortB(bb, bi) : getShortL(bb, bi);
}
static short getShort(long a, boolean bigEndian) {
return (bigEndian ? getShortB(a) : getShortL(a));
return bigEndian ? getShortB(a) : getShortL(a);
}
private static byte short1(short x) { return (byte)(x >> 8); }
private static byte short0(short x) { return (byte)(x >> 0); }
private static byte short0(short x) { return (byte)(x ); }
static void putShortL(ByteBuffer bb, int bi, short x) {
bb._put(bi + 0, short0(x));
bb._put(bi , short0(x));
bb._put(bi + 1, short1(x));
}
static void putShortL(long a, short x) {
_put(a, short0(x));
_put(a , short0(x));
_put(a + 1, short1(x));
}
static void putShortB(ByteBuffer bb, int bi, short x) {
bb._put(bi + 0, short1(x));
bb._put(bi , short1(x));
bb._put(bi + 1, short0(x));
}
static void putShortB(long a, short x) {
_put(a, short1(x));
_put(a , short1(x));
_put(a + 1, short0(x));
}
......@@ -210,76 +204,76 @@ class Bits { // package-private
// -- get/put int --
static private int makeInt(byte b3, byte b2, byte b1, byte b0) {
return (((b3 & 0xff) << 24) |
return (((b3 ) << 24) |
((b2 & 0xff) << 16) |
((b1 & 0xff) << 8) |
((b0 & 0xff) << 0));
((b0 & 0xff) ));
}
static int getIntL(ByteBuffer bb, int bi) {
return makeInt(bb._get(bi + 3),
bb._get(bi + 2),
bb._get(bi + 1),
bb._get(bi + 0));
bb._get(bi ));
}
static int getIntL(long a) {
return makeInt(_get(a + 3),
_get(a + 2),
_get(a + 1),
_get(a + 0));
_get(a ));
}
static int getIntB(ByteBuffer bb, int bi) {
return makeInt(bb._get(bi + 0),
return makeInt(bb._get(bi ),
bb._get(bi + 1),
bb._get(bi + 2),
bb._get(bi + 3));
}
static int getIntB(long a) {
return makeInt(_get(a + 0),
return makeInt(_get(a ),
_get(a + 1),
_get(a + 2),
_get(a + 3));
}
static int getInt(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getIntB(bb, bi) : getIntL(bb, bi));
return bigEndian ? getIntB(bb, bi) : getIntL(bb, bi) ;
}
static int getInt(long a, boolean bigEndian) {
return (bigEndian ? getIntB(a) : getIntL(a));
return bigEndian ? getIntB(a) : getIntL(a) ;
}
private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >> 8); }
private static byte int0(int x) { return (byte)(x >> 0); }
private static byte int0(int x) { return (byte)(x ); }
static void putIntL(ByteBuffer bb, int bi, int x) {
bb._put(bi + 3, int3(x));
bb._put(bi + 2, int2(x));
bb._put(bi + 1, int1(x));
bb._put(bi + 0, int0(x));
bb._put(bi , int0(x));
}
static void putIntL(long a, int x) {
_put(a + 3, int3(x));
_put(a + 2, int2(x));
_put(a + 1, int1(x));
_put(a + 0, int0(x));
_put(a , int0(x));
}
static void putIntB(ByteBuffer bb, int bi, int x) {
bb._put(bi + 0, int3(x));
bb._put(bi , int3(x));
bb._put(bi + 1, int2(x));
bb._put(bi + 2, int1(x));
bb._put(bi + 3, int0(x));
}
static void putIntB(long a, int x) {
_put(a + 0, int3(x));
_put(a , int3(x));
_put(a + 1, int2(x));
_put(a + 2, int1(x));
_put(a + 3, int0(x));
......@@ -305,14 +299,14 @@ class Bits { // package-private
static private long makeLong(byte b7, byte b6, byte b5, byte b4,
byte b3, byte b2, byte b1, byte b0)
{
return ((((long)b7 & 0xff) << 56) |
return ((((long)b7 ) << 56) |
(((long)b6 & 0xff) << 48) |
(((long)b5 & 0xff) << 40) |
(((long)b4 & 0xff) << 32) |
(((long)b3 & 0xff) << 24) |
(((long)b2 & 0xff) << 16) |
(((long)b1 & 0xff) << 8) |
(((long)b0 & 0xff) << 0));
(((long)b0 & 0xff) ));
}
static long getLongL(ByteBuffer bb, int bi) {
......@@ -323,7 +317,7 @@ class Bits { // package-private
bb._get(bi + 3),
bb._get(bi + 2),
bb._get(bi + 1),
bb._get(bi + 0));
bb._get(bi ));
}
static long getLongL(long a) {
......@@ -334,11 +328,11 @@ class Bits { // package-private
_get(a + 3),
_get(a + 2),
_get(a + 1),
_get(a + 0));
_get(a ));
}
static long getLongB(ByteBuffer bb, int bi) {
return makeLong(bb._get(bi + 0),
return makeLong(bb._get(bi ),
bb._get(bi + 1),
bb._get(bi + 2),
bb._get(bi + 3),
......@@ -349,7 +343,7 @@ class Bits { // package-private
}
static long getLongB(long a) {
return makeLong(_get(a + 0),
return makeLong(_get(a ),
_get(a + 1),
_get(a + 2),
_get(a + 3),
......@@ -360,11 +354,11 @@ class Bits { // package-private
}
static long getLong(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getLongB(bb, bi) : getLongL(bb, bi));
return bigEndian ? getLongB(bb, bi) : getLongL(bb, bi);
}
static long getLong(long a, boolean bigEndian) {
return (bigEndian ? getLongB(a) : getLongL(a));
return bigEndian ? getLongB(a) : getLongL(a);
}
private static byte long7(long x) { return (byte)(x >> 56); }
......@@ -374,7 +368,7 @@ class Bits { // package-private
private static byte long3(long x) { return (byte)(x >> 24); }
private static byte long2(long x) { return (byte)(x >> 16); }
private static byte long1(long x) { return (byte)(x >> 8); }
private static byte long0(long x) { return (byte)(x >> 0); }
private static byte long0(long x) { return (byte)(x ); }
static void putLongL(ByteBuffer bb, int bi, long x) {
bb._put(bi + 7, long7(x));
......@@ -384,7 +378,7 @@ class Bits { // package-private
bb._put(bi + 3, long3(x));
bb._put(bi + 2, long2(x));
bb._put(bi + 1, long1(x));
bb._put(bi + 0, long0(x));
bb._put(bi , long0(x));
}
static void putLongL(long a, long x) {
......@@ -395,11 +389,11 @@ class Bits { // package-private
_put(a + 3, long3(x));
_put(a + 2, long2(x));
_put(a + 1, long1(x));
_put(a + 0, long0(x));
_put(a , long0(x));
}
static void putLongB(ByteBuffer bb, int bi, long x) {
bb._put(bi + 0, long7(x));
bb._put(bi , long7(x));
bb._put(bi + 1, long6(x));
bb._put(bi + 2, long5(x));
bb._put(bi + 3, long4(x));
......@@ -410,7 +404,7 @@ class Bits { // package-private
}
static void putLongB(long a, long x) {
_put(a + 0, long7(x));
_put(a , long7(x));
_put(a + 1, long6(x));
_put(a + 2, long5(x));
_put(a + 3, long4(x));
......@@ -454,11 +448,11 @@ class Bits { // package-private
}
static float getFloat(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getFloatB(bb, bi) : getFloatL(bb, bi));
return bigEndian ? getFloatB(bb, bi) : getFloatL(bb, bi);
}
static float getFloat(long a, boolean bigEndian) {
return (bigEndian ? getFloatB(a) : getFloatL(a));
return bigEndian ? getFloatB(a) : getFloatL(a);
}
static void putFloatL(ByteBuffer bb, int bi, float x) {
......@@ -511,11 +505,11 @@ class Bits { // package-private
}
static double getDouble(ByteBuffer bb, int bi, boolean bigEndian) {
return (bigEndian ? getDoubleB(bb, bi) : getDoubleL(bb, bi));
return bigEndian ? getDoubleB(bb, bi) : getDoubleL(bb, bi);
}
static double getDouble(long a, boolean bigEndian) {
return (bigEndian ? getDoubleB(a) : getDoubleL(a));
return bigEndian ? getDoubleB(a) : getDoubleL(a);
}
static void putDoubleL(ByteBuffer bb, int bi, double x) {
......@@ -794,7 +788,7 @@ class Bits { // package-private
static native void copyFromIntArray(Object src, long srcPos, long dstAddr,
long length);
static native void copyToIntArray(long srcAddr, Object dst, long dstPos,
long length);
long length);
static native void copyFromLongArray(Object src, long srcPos, long dstAddr,
long length);
......
......@@ -116,7 +116,7 @@ import java.io.IOException;
* @since 1.4
*/
public abstract class FileLock {
public abstract class FileLock implements AutoCloseable {
private final Channel channel;
private final long position;
......@@ -298,6 +298,17 @@ public abstract class FileLock {
*/
public abstract void release() throws IOException;
/**
* This method invokes the {@link #release} method. It was added
* to the class so that it could be used in conjunction with the
* automatic resource management block construct.
*
* @since 1.7
*/
public final void close() throws IOException {
release();
}
/**
* Returns a string describing the range, type, and validity of this lock.
*
......
......@@ -343,7 +343,7 @@ import sun.misc.LRUCache;
*
* @since 1.5
*/
public final class Scanner implements Iterator<String> {
public final class Scanner implements Iterator<String>, Closeable {
// Internal buffer used to hold input
private CharBuffer buf;
......
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -29,6 +29,7 @@ package java.util.logging;
import java.io.*;
import java.util.*;
import java.security.*;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
......@@ -154,10 +155,10 @@ public class LogManager {
= new PropertyChangeSupport(LogManager.class);
private final static Level defaultLevel = Level.INFO;
// Table of known loggers. Maps names to Loggers.
private Hashtable<String,WeakReference<Logger>> loggers =
new Hashtable<String,WeakReference<Logger>>();
// Tree of known loggers
// Table of named Loggers that maps names to Loggers.
private Hashtable<String,LoggerWeakRef> namedLoggers =
new Hashtable<String,LoggerWeakRef>();
// Tree of named Loggers
private LogNode root = new LogNode(null);
private Logger rootLogger;
......@@ -417,6 +418,121 @@ public class LogManager {
}});
}
// loggerRefQueue holds LoggerWeakRef objects for Logger objects
// that have been GC'ed.
private final ReferenceQueue<Logger> loggerRefQueue
= new ReferenceQueue<Logger>();
// Package-level inner class.
// Helper class for managing WeakReferences to Logger objects.
//
// LogManager.namedLoggers
// - has weak references to all named Loggers
// - namedLoggers keeps the LoggerWeakRef objects for the named
// Loggers around until we can deal with the book keeping for
// the named Logger that is being GC'ed.
// LogManager.LogNode.loggerRef
// - has a weak reference to a named Logger
// - the LogNode will also keep the LoggerWeakRef objects for
// the named Loggers around; currently LogNodes never go away.
// Logger.kids
// - has a weak reference to each direct child Logger; this
// includes anonymous and named Loggers
// - anonymous Loggers are always children of the rootLogger
// which is a strong reference; rootLogger.kids keeps the
// LoggerWeakRef objects for the anonymous Loggers around
// until we can deal with the book keeping.
//
final class LoggerWeakRef extends WeakReference<Logger> {
private String name; // for namedLoggers cleanup
private LogNode node; // for loggerRef cleanup
private WeakReference<Logger> parentRef; // for kids cleanup
LoggerWeakRef(Logger logger) {
super(logger, loggerRefQueue);
name = logger.getName(); // save for namedLoggers cleanup
}
// dispose of this LoggerWeakRef object
void dispose() {
if (node != null) {
// if we have a LogNode, then we were a named Logger
// so clear namedLoggers weak ref to us
manager.namedLoggers.remove(name);
name = null; // clear our ref to the Logger's name
node.loggerRef = null; // clear LogNode's weak ref to us
node = null; // clear our ref to LogNode
}
if (parentRef != null) {
// this LoggerWeakRef has or had a parent Logger
Logger parent = parentRef.get();
if (parent != null) {
// the parent Logger is still there so clear the
// parent Logger's weak ref to us
parent.removeChildLogger(this);
}
parentRef = null; // clear our weak ref to the parent Logger
}
}
// set the node field to the specified value
void setNode(LogNode node) {
this.node = node;
}
// set the parentRef field to the specified value
void setParentRef(WeakReference<Logger> parentRef) {
this.parentRef = parentRef;
}
}
// Package-level method.
// Drain some Logger objects that have been GC'ed.
//
// drainLoggerRefQueueBounded() is called by addLogger() below
// and by Logger.getAnonymousLogger(String) so we'll drain up to
// MAX_ITERATIONS GC'ed Loggers for every Logger we add.
//
// On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives
// us about a 50/50 mix in increased weak ref counts versus
// decreased weak ref counts in the AnonLoggerWeakRefLeak test.
// Here are stats for cleaning up sets of 400 anonymous Loggers:
// - test duration 1 minute
// - sample size of 125 sets of 400
// - average: 1.99 ms
// - minimum: 0.57 ms
// - maximum: 25.3 ms
//
// The same config gives us a better decreased weak ref count
// than increased weak ref count in the LoggerWeakRefLeak test.
// Here are stats for cleaning up sets of 400 named Loggers:
// - test duration 2 minutes
// - sample size of 506 sets of 400
// - average: 0.57 ms
// - minimum: 0.02 ms
// - maximum: 10.9 ms
//
private final static int MAX_ITERATIONS = 400;
final synchronized void drainLoggerRefQueueBounded() {
for (int i = 0; i < MAX_ITERATIONS; i++) {
if (loggerRefQueue == null) {
// haven't finished loading LogManager yet
break;
}
LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll();
if (ref == null) {
break;
}
// a Logger object has been GC'ed so clean it up
ref.dispose();
}
}
/**
* Add a named logger. This does nothing and returns false if a logger
* with the same name is already registered.
......@@ -439,13 +555,16 @@ public class LogManager {
throw new NullPointerException();
}
WeakReference<Logger> ref = loggers.get(name);
// cleanup some Loggers that have been GC'ed
drainLoggerRefQueueBounded();
LoggerWeakRef ref = namedLoggers.get(name);
if (ref != null) {
if (ref.get() == null) {
// Hashtable holds stale weak reference
// to a logger which has been GC-ed.
// Allow to register new one.
loggers.remove(name);
// It's possible that the Logger was GC'ed after the
// drainLoggerRefQueueBounded() call above so allow
// a new one to be registered.
namedLoggers.remove(name);
} else {
// We already have a registered logger with the given name.
return false;
......@@ -454,7 +573,8 @@ public class LogManager {
// We're adding a new logger.
// Note that we are creating a weak reference here.
loggers.put(name, new WeakReference<Logger>(logger));
ref = new LoggerWeakRef(logger);
namedLoggers.put(name, ref);
// Apply any initial level defined for the new logger.
Level level = getLevelProperty(name+".level", null);
......@@ -469,11 +589,11 @@ public class LogManager {
// Find the new node and its parent.
LogNode node = findNode(name);
node.loggerRef = new WeakReference<Logger>(logger);
node.loggerRef = ref;
Logger parent = null;
LogNode nodep = node.parent;
while (nodep != null) {
WeakReference<Logger> nodeRef = nodep.loggerRef;
LoggerWeakRef nodeRef = nodep.loggerRef;
if (nodeRef != null) {
parent = nodeRef.get();
if (parent != null) {
......@@ -489,6 +609,9 @@ public class LogManager {
// Walk over the children and tell them we are their new parent.
node.walkAndSetParent(logger);
// new LogNode is ready so tell the LoggerWeakRef about it
ref.setNode(node);
return true;
}
......@@ -572,7 +695,7 @@ public class LogManager {
* @return matching logger or null if none is found
*/
public synchronized Logger getLogger(String name) {
WeakReference<Logger> ref = loggers.get(name);
LoggerWeakRef ref = namedLoggers.get(name);
if (ref == null) {
return null;
}
......@@ -580,7 +703,7 @@ public class LogManager {
if (logger == null) {
// Hashtable holds stale weak reference
// to a logger which has been GC-ed.
loggers.remove(name);
namedLoggers.remove(name);
}
return logger;
}
......@@ -594,7 +717,7 @@ public class LogManager {
* @return enumeration of logger name strings
*/
public synchronized Enumeration<String> getLoggerNames() {
return loggers.keys();
return namedLoggers.keys();
}
/**
......@@ -942,7 +1065,7 @@ public class LogManager {
// Nested class to represent a node in our tree of named loggers.
private static class LogNode {
HashMap<String,LogNode> children;
WeakReference<Logger> loggerRef;
LoggerWeakRef loggerRef;
LogNode parent;
LogNode(LogNode parent) {
......@@ -958,7 +1081,7 @@ public class LogManager {
Iterator<LogNode> values = children.values().iterator();
while (values.hasNext()) {
LogNode node = values.next();
WeakReference<Logger> ref = node.loggerRef;
LoggerWeakRef ref = node.loggerRef;
Logger logger = (ref == null) ? null : ref.get();
if (logger == null) {
node.walkAndSetParent(parent);
......
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -183,7 +183,7 @@ public class Logger {
// We keep weak references from parents to children, but strong
// references from children to parents.
private volatile Logger parent; // our nearest parent.
private ArrayList<WeakReference<Logger>> kids; // WeakReferences to loggers that have us as parent
private ArrayList<LogManager.LoggerWeakRef> kids; // WeakReferences to loggers that have us as parent
private volatile Level levelObject;
private volatile int levelValue; // current effective level value
......@@ -366,13 +366,8 @@ public class Logger {
*
* @return a newly created private Logger
*/
public static synchronized Logger getAnonymousLogger() {
LogManager manager = LogManager.getLogManager();
Logger result = new Logger(null, null);
result.anonymous = true;
Logger root = manager.getLogger("");
result.doSetParent(root);
return result;
public static Logger getAnonymousLogger() {
return getAnonymousLogger(null);
}
/**
......@@ -401,6 +396,8 @@ public class Logger {
*/
public static synchronized Logger getAnonymousLogger(String resourceBundleName) {
LogManager manager = LogManager.getLogManager();
// cleanup some Loggers that have been GC'ed
manager.drainLoggerRefQueueBounded();
Logger result = new Logger(null, resourceBundleName);
result.anonymous = true;
Logger root = manager.getLogger("");
......@@ -1380,14 +1377,18 @@ public class Logger {
synchronized (treeLock) {
// Remove ourself from any previous parent.
LogManager.LoggerWeakRef ref = null;
if (parent != null) {
// assert parent.kids != null;
for (Iterator<WeakReference<Logger>> iter = parent.kids.iterator(); iter.hasNext(); ) {
WeakReference<Logger> ref = iter.next();
for (Iterator<LogManager.LoggerWeakRef> iter = parent.kids.iterator(); iter.hasNext(); ) {
ref = iter.next();
Logger kid = ref.get();
if (kid == this) {
// ref is used down below to complete the reparenting
iter.remove();
break;
} else {
ref = null;
}
}
// We have now removed ourself from our parents' kids.
......@@ -1396,9 +1397,14 @@ public class Logger {
// Set our new parent.
parent = newParent;
if (parent.kids == null) {
parent.kids = new ArrayList<WeakReference<Logger>>(2);
parent.kids = new ArrayList<LogManager.LoggerWeakRef>(2);
}
if (ref == null) {
// we didn't have a previous parent
ref = manager.new LoggerWeakRef(this);
}
parent.kids.add(new WeakReference<Logger>(this));
ref.setParentRef(new WeakReference<Logger>(parent));
parent.kids.add(ref);
// As a result of the reparenting, the effective level
// may have changed for us and our children.
......@@ -1407,6 +1413,21 @@ public class Logger {
}
}
// Package-level method.
// Remove the weak reference for the specified child Logger from the
// kid list. We should only be called from LoggerWeakRef.dispose().
final void removeChildLogger(LogManager.LoggerWeakRef child) {
synchronized (treeLock) {
for (Iterator<LogManager.LoggerWeakRef> iter = kids.iterator(); iter.hasNext(); ) {
LogManager.LoggerWeakRef ref = iter.next();
if (ref == child) {
iter.remove();
return;
}
}
}
}
// Recalculate the effective level for this node and
// recursively for our children.
......@@ -1438,7 +1459,7 @@ public class Logger {
// Recursively update the level on each of our kids.
if (kids != null) {
for (int i = 0; i < kids.size(); i++) {
WeakReference<Logger> ref = kids.get(i);
LogManager.LoggerWeakRef ref = kids.get(i);
Logger kid = ref.get();
if (kid != null) {
kid.updateEffectiveLevel();
......
......@@ -25,6 +25,7 @@
package javax.imageio.stream;
import java.io.Closeable;
import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteOrder;
......@@ -42,7 +43,7 @@ import java.nio.ByteOrder;
* @see MemoryCacheImageInputStream
*
*/
public interface ImageInputStream extends DataInput {
public interface ImageInputStream extends DataInput, Closeable {
/**
* Sets the desired byte order for future reads of data values
......
......@@ -107,7 +107,7 @@ import java.util.List;
* @author Florian Bomers
*/
public interface MidiDevice {
public interface MidiDevice extends AutoCloseable {
/**
......
......@@ -38,7 +38,7 @@ package javax.sound.midi;
*
* @author Kara Kytle
*/
public interface Receiver {
public interface Receiver extends AutoCloseable {
//$$fb 2002-04-12: fix for 4662090: Contradiction in Receiver specification
......
......@@ -35,7 +35,7 @@ package javax.sound.midi;
*
* @author Kara Kytle
*/
public interface Transmitter {
public interface Transmitter extends AutoCloseable {
/**
......
......@@ -70,7 +70,7 @@ package javax.sound.sampled;
* @see LineEvent
* @since 1.3
*/
public interface Line {
public interface Line extends AutoCloseable {
/**
* Obtains the <code>Line.Info</code> object describing this
......
......@@ -24,7 +24,6 @@
*/
package sun.io;
import sun.nio.cs.Surrogate;
import sun.nio.cs.ext.DoubleByte;
import static sun.nio.cs.CharsetMapping.*;
......
......@@ -24,7 +24,6 @@
*/
package sun.io;
import sun.nio.cs.Surrogate;
import sun.nio.cs.ext.DoubleByte;
import static sun.nio.cs.CharsetMapping.*;
......
/*
* Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -208,7 +208,7 @@ public enum LauncherHelper {
Method method = null;
try {
method = clazz.getMethod("main", String[].class);
} catch (Exception e) {
} catch (NoSuchMethodException nsme) {
ostream.println(getLocalizedMessage("java.launcher.cls.error4",
classname));
throw new RuntimeException("Main method not found in " + classname);
......@@ -225,8 +225,7 @@ public enum LauncherHelper {
throw new RuntimeException("Main method is not static in class " +
classname);
}
Class<?> rType = method.getReturnType();
if (!rType.isPrimitive() || !rType.getName().equals("void")) {
if (method.getReturnType() != java.lang.Void.TYPE) {
ostream.println(getLocalizedMessage("java.launcher.cls.error3",
classname));
throw new RuntimeException("Main method must return a value" +
......
......@@ -52,14 +52,16 @@ class ExchangeImpl {
boolean http10 = false;
/* for formatting the Date: header */
static TimeZone tz;
static DateFormat df;
static {
String pattern = "EEE, dd MMM yyyy HH:mm:ss zzz";
tz = TimeZone.getTimeZone ("GMT");
df = new SimpleDateFormat (pattern, Locale.US);
df.setTimeZone (tz);
}
private static final String pattern = "EEE, dd MMM yyyy HH:mm:ss zzz";
private static final TimeZone gmtTZ = TimeZone.getTimeZone("GMT");
private static final ThreadLocal<DateFormat> dateFormat =
new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
DateFormat df = new SimpleDateFormat(pattern, Locale.US);
df.setTimeZone(gmtTZ);
return df;
}
};
private static final String HEAD = "HEAD";
......@@ -206,7 +208,7 @@ class ExchangeImpl {
PlaceholderOutputStream o = getPlaceholderResponseBody();
tmpout.write (bytes(statusLine, 0), 0, statusLine.length());
boolean noContentToSend = false; // assume there is content
rspHdrs.set ("Date", df.format (new Date()));
rspHdrs.set ("Date", dateFormat.get().format (new Date()));
/* check for response type that is not allowed to send a body */
......
......@@ -2331,7 +2331,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
* closed the connection to the web server.
*/
private void disconnectWeb() throws IOException {
if (usingProxy()) {
if (usingProxy() && http.isKeepingAlive()) {
responseCode = -1;
// clean up, particularly, skip the content part
// of a 401 error response
......
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -34,8 +34,9 @@ import java.nio.charset.UnmappableCharacterException;
* Utility class for dealing with surrogates.
*
* @author Mark Reinhold
* @author Martin Buchholz
* @author Ulf Zibis
*/
public class Surrogate {
private Surrogate() { }
......@@ -74,17 +75,10 @@ public class Surrogate {
return (MIN <= c) && (c <= MAX);
}
/**
* Tells whether or not the given UCS-4 character is in the Basic
* Multilingual Plane, and can be represented using a single char.
*/
public static boolean isBMPCodePoint(int uc) {
return uc >> 16 == 0;
}
/**
* Tells whether or not the given UCS-4 character must be represented as a
* surrogate pair in UTF-16.
* Use of {@link Character#isSupplementaryCodePoint} is generally preferred.
*/
public static boolean neededFor(int uc) {
return Character.isSupplementaryCodePoint(uc);
......@@ -92,24 +86,25 @@ public class Surrogate {
/**
* Returns the high UTF-16 surrogate for the given supplementary UCS-4 character.
* Use of {@link Character#highSurrogate} is generally preferred.
*/
public static char high(int uc) {
assert Character.isSupplementaryCodePoint(uc);
return (char)((uc >> 10)
+ (Character.MIN_HIGH_SURROGATE
- (Character.MIN_SUPPLEMENTARY_CODE_POINT >> 10)));
return Character.highSurrogate(uc);
}
/**
* Returns the low UTF-16 surrogate for the given supplementary UCS-4 character.
* Use of {@link Character#lowSurrogate} is generally preferred.
*/
public static char low(int uc) {
assert Character.isSupplementaryCodePoint(uc);
return (char)((uc & 0x3ff) + Character.MIN_LOW_SURROGATE);
return Character.lowSurrogate(uc);
}
/**
* Converts the given surrogate pair into a 32-bit UCS-4 character.
* Use of {@link Character#toCodePoint} is generally preferred.
*/
public static int toUCS4(char c, char d) {
assert Character.isHighSurrogate(c) && Character.isLowSurrogate(d);
......@@ -290,8 +285,9 @@ public class Surrogate {
* error() will return a descriptive result object
*/
public int generate(int uc, int len, CharBuffer dst) {
if (Surrogate.isBMPCodePoint(uc)) {
if (Surrogate.is(uc)) {
if (Character.isBmpCodePoint(uc)) {
char c = (char) uc;
if (Character.isSurrogate(c)) {
error = CoderResult.malformedForLength(len);
return -1;
}
......@@ -299,16 +295,16 @@ public class Surrogate {
error = CoderResult.OVERFLOW;
return -1;
}
dst.put((char)uc);
dst.put(c);
error = null;
return 1;
} else if (Character.isSupplementaryCodePoint(uc)) {
} else if (Character.isValidCodePoint(uc)) {
if (dst.remaining() < 2) {
error = CoderResult.OVERFLOW;
return -1;
}
dst.put(Surrogate.high(uc));
dst.put(Surrogate.low(uc));
dst.put(Character.highSurrogate(uc));
dst.put(Character.lowSurrogate(uc));
error = null;
return 2;
} else {
......@@ -334,8 +330,9 @@ public class Surrogate {
* error() will return a descriptive result object
*/
public int generate(int uc, int len, char[] da, int dp, int dl) {
if (Surrogate.isBMPCodePoint(uc)) {
if (Surrogate.is(uc)) {
if (Character.isBmpCodePoint(uc)) {
char c = (char) uc;
if (Character.isSurrogate(c)) {
error = CoderResult.malformedForLength(len);
return -1;
}
......@@ -343,16 +340,16 @@ public class Surrogate {
error = CoderResult.OVERFLOW;
return -1;
}
da[dp] = (char)uc;
da[dp] = c;
error = null;
return 1;
} else if (Character.isSupplementaryCodePoint(uc)) {
} else if (Character.isValidCodePoint(uc)) {
if (dl - dp < 2) {
error = CoderResult.OVERFLOW;
return -1;
}
da[dp] = Surrogate.high(uc);
da[dp + 1] = Surrogate.low(uc);
da[dp] = Character.highSurrogate(uc);
da[dp + 1] = Character.lowSurrogate(uc);
error = null;
return 2;
} else {
......
......@@ -86,22 +86,21 @@ class UTF_32Coder {
src.position(mark);
}
}
while (src.remaining() > 3) {
while (src.remaining() >= 4) {
cp = getCP(src);
if (cp < 0 || cp > Surrogate.UCS4_MAX) {
return CoderResult.malformedForLength(4);
}
if (cp < Surrogate.UCS4_MIN) {
if (Character.isBmpCodePoint(cp)) {
if (!dst.hasRemaining())
return CoderResult.OVERFLOW;
mark += 4;
dst.put((char)cp);
} else {
dst.put((char) cp);
} else if (Character.isValidCodePoint(cp)) {
if (dst.remaining() < 2)
return CoderResult.OVERFLOW;
mark += 4;
dst.put(Surrogate.high(cp));
dst.put(Surrogate.low(cp));
dst.put(Character.highSurrogate(cp));
dst.put(Character.lowSurrogate(cp));
} else {
return CoderResult.malformedForLength(4);
}
}
return CoderResult.UNDERFLOW;
......@@ -154,7 +153,12 @@ class UTF_32Coder {
try {
while (src.hasRemaining()) {
char c = src.get();
if (Character.isHighSurrogate(c)) {
if (!Character.isSurrogate(c)) {
if (dst.remaining() < 4)
return CoderResult.OVERFLOW;
mark++;
put(c, dst);
} else if (Character.isHighSurrogate(c)) {
if (!src.hasRemaining())
return CoderResult.UNDERFLOW;
char low = src.get();
......@@ -162,17 +166,13 @@ class UTF_32Coder {
if (dst.remaining() < 4)
return CoderResult.OVERFLOW;
mark += 2;
put(Surrogate.toUCS4(c, low), dst);
put(Character.toCodePoint(c, low), dst);
} else {
return CoderResult.malformedForLength(1);
}
} else if (Character.isLowSurrogate(c)) {
return CoderResult.malformedForLength(1);
} else {
if (dst.remaining() < 4)
return CoderResult.OVERFLOW;
mark++;
put(c, dst);
// assert Character.isLowSurrogate(c);
return CoderResult.malformedForLength(1);
}
}
return CoderResult.UNDERFLOW;
......
......@@ -102,7 +102,7 @@ class UTF_8 extends Unicode
// [F1..F3] [80..BF] [80..BF] [80..BF]
// [F4] [80..8F] [80..BF] [80..BF]
// only check 80-be range here, the [0xf0,0x80...] and [0xf4,0x90-...]
// will be checked by Surrogate.neededFor(uc)
// will be checked by Character.isSupplementaryCodePoint(uc)
private static boolean isMalformed4(int b2, int b3, int b4) {
return (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 ||
(b4 & 0xc0) != 0x80;
......@@ -207,15 +207,15 @@ class UTF_8 extends Unicode
// ASCII only loop
while (dp < dlASCII && sa[sp] >= 0)
da[dp++] = (char)sa[sp++];
da[dp++] = (char) sa[sp++];
while (sp < sl) {
int b1 = sa[sp];
if (b1 >= 0) {
if (b1 >= 0) {
// 1 byte, 7 bits: 0xxxxxxx
if (dp >= dl)
return xflow(src, sp, sl, dst, dp, 1);
da[dp++] = (char)b1;
da[dp++] = (char) b1;
sp++;
} else if ((b1 >> 5) == -2) {
// 2 bytes, 11 bits: 110xxxxx 10xxxxxx
......@@ -224,7 +224,10 @@ class UTF_8 extends Unicode
int b2 = sa[sp + 1];
if (isMalformed2(b1, b2))
return malformed(src, sp, dst, dp, 2);
da[dp++] = (char) (((b1 << 6) ^ b2) ^ 0x0f80);
da[dp++] = (char) (((b1 << 6) ^ b2)
^
(((byte) 0xC0 << 6) ^
((byte) 0x80 << 0)));
sp += 2;
} else if ((b1 >> 4) == -2) {
// 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
......@@ -234,7 +237,13 @@ class UTF_8 extends Unicode
int b3 = sa[sp + 2];
if (isMalformed3(b1, b2, b3))
return malformed(src, sp, dst, dp, 3);
da[dp++] = (char) (((b1 << 12) ^ (b2 << 6) ^ b3) ^ 0x1f80);
da[dp++] = (char)
((b1 << 12) ^
(b2 << 6) ^
(b3 ^
(((byte) 0xE0 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0))));
sp += 3;
} else if ((b1 >> 3) == -2) {
// 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
......@@ -243,16 +252,21 @@ class UTF_8 extends Unicode
int b2 = sa[sp + 1];
int b3 = sa[sp + 2];
int b4 = sa[sp + 3];
int uc = ((b1 & 0x07) << 18) |
((b2 & 0x3f) << 12) |
((b3 & 0x3f) << 06) |
(b4 & 0x3f);
int uc = ((b1 << 18) ^
(b2 << 12) ^
(b3 << 6) ^
(b4 ^
(((byte) 0xF0 << 18) ^
((byte) 0x80 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0))));
if (isMalformed4(b2, b3, b4) ||
!Surrogate.neededFor(uc)) {
// shortest form check
!Character.isSupplementaryCodePoint(uc)) {
return malformed(src, sp, dst, dp, 4);
}
da[dp++] = Surrogate.high(uc);
da[dp++] = Surrogate.low(uc);
da[dp++] = Character.highSurrogate(uc);
da[dp++] = Character.lowSurrogate(uc);
sp += 4;
} else
return malformed(src, sp, dst, dp, 1);
......@@ -270,8 +284,8 @@ class UTF_8 extends Unicode
if (b1 >= 0) {
// 1 byte, 7 bits: 0xxxxxxx
if (dst.remaining() < 1)
return xflow(src, mark, 1); //overflow
dst.put((char)b1);
return xflow(src, mark, 1); // overflow
dst.put((char) b1);
mark++;
} else if ((b1 >> 5) == -2) {
// 2 bytes, 11 bits: 110xxxxx 10xxxxxx
......@@ -280,7 +294,10 @@ class UTF_8 extends Unicode
int b2 = src.get();
if (isMalformed2(b1, b2))
return malformed(src, mark, 2);
dst.put((char) (((b1 << 6) ^ b2) ^ 0x0f80));
dst.put((char) (((b1 << 6) ^ b2)
^
(((byte) 0xC0 << 6) ^
((byte) 0x80 << 0))));
mark += 2;
} else if ((b1 >> 4) == -2) {
// 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
......@@ -290,7 +307,13 @@ class UTF_8 extends Unicode
int b3 = src.get();
if (isMalformed3(b1, b2, b3))
return malformed(src, mark, 3);
dst.put((char) (((b1 << 12) ^ (b2 << 6) ^ b3) ^ 0x1f80));
dst.put((char)
((b1 << 12) ^
(b2 << 6) ^
(b3 ^
(((byte) 0xE0 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0)))));
mark += 3;
} else if ((b1 >> 3) == -2) {
// 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
......@@ -299,16 +322,21 @@ class UTF_8 extends Unicode
int b2 = src.get();
int b3 = src.get();
int b4 = src.get();
int uc = ((b1 & 0x07) << 18) |
((b2 & 0x3f) << 12) |
((b3 & 0x3f) << 06) |
(b4 & 0x3f);
int uc = ((b1 << 18) ^
(b2 << 12) ^
(b3 << 6) ^
(b4 ^
(((byte) 0xF0 << 18) ^
((byte) 0x80 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0))));
if (isMalformed4(b2, b3, b4) ||
!Surrogate.neededFor(uc)) { // shortest form check
// shortest form check
!Character.isSupplementaryCodePoint(uc)) {
return malformed(src, mark, 4);
}
dst.put(Surrogate.high(uc));
dst.put(Surrogate.low(uc));
dst.put(Character.highSurrogate(uc));
dst.put(Character.lowSurrogate(uc));
mark += 4;
} else {
return malformed(src, mark, 1);
......@@ -366,7 +394,7 @@ class UTF_8 extends Unicode
int dl = dst.arrayOffset() + dst.limit();
int dlASCII = dp + Math.min(sl - sp, dl - dp);
//ASCII only loop
// ASCII only loop
while (dp < dlASCII && sa[sp] < '\u0080')
da[dp++] = (byte) sa[sp++];
while (sp < sl) {
......@@ -380,7 +408,7 @@ class UTF_8 extends Unicode
// 2 bytes, 11 bits
if (dl - dp < 2)
return overflow(src, sp, dst, dp);
da[dp++] = (byte)(0xc0 | ((c >> 06)));
da[dp++] = (byte)(0xc0 | (c >> 6));
da[dp++] = (byte)(0x80 | (c & 0x3f));
} else if (Character.isSurrogate(c)) {
// Have a surrogate pair
......@@ -395,7 +423,7 @@ class UTF_8 extends Unicode
return overflow(src, sp, dst, dp);
da[dp++] = (byte)(0xf0 | ((uc >> 18)));
da[dp++] = (byte)(0x80 | ((uc >> 12) & 0x3f));
da[dp++] = (byte)(0x80 | ((uc >> 06) & 0x3f));
da[dp++] = (byte)(0x80 | ((uc >> 6) & 0x3f));
da[dp++] = (byte)(0x80 | (uc & 0x3f));
sp++; // 2 chars
} else {
......@@ -403,7 +431,7 @@ class UTF_8 extends Unicode
if (dl - dp < 3)
return overflow(src, sp, dst, dp);
da[dp++] = (byte)(0xe0 | ((c >> 12)));
da[dp++] = (byte)(0x80 | ((c >> 06) & 0x3f));
da[dp++] = (byte)(0x80 | ((c >> 6) & 0x3f));
da[dp++] = (byte)(0x80 | (c & 0x3f));
}
sp++;
......@@ -427,7 +455,7 @@ class UTF_8 extends Unicode
// 2 bytes, 11 bits
if (dst.remaining() < 2)
return overflow(src, mark);
dst.put((byte)(0xc0 | ((c >> 06))));
dst.put((byte)(0xc0 | (c >> 6)));
dst.put((byte)(0x80 | (c & 0x3f)));
} else if (Character.isSurrogate(c)) {
// Have a surrogate pair
......@@ -442,15 +470,15 @@ class UTF_8 extends Unicode
return overflow(src, mark);
dst.put((byte)(0xf0 | ((uc >> 18))));
dst.put((byte)(0x80 | ((uc >> 12) & 0x3f)));
dst.put((byte)(0x80 | ((uc >> 06) & 0x3f)));
dst.put((byte)(0x80 | ((uc >> 6) & 0x3f)));
dst.put((byte)(0x80 | (uc & 0x3f)));
mark++; //2 chars
mark++; // 2 chars
} else {
// 3 bytes, 16 bits
if (dst.remaining() < 3)
return overflow(src, mark);
dst.put((byte)(0xe0 | ((c >> 12))));
dst.put((byte)(0x80 | ((c >> 06) & 0x3f)));
dst.put((byte)(0x80 | ((c >> 6) & 0x3f)));
dst.put((byte)(0x80 | (c & 0x3f)));
}
mark++;
......
......@@ -93,8 +93,8 @@ public abstract class UnicodeEncoder extends CharsetEncoder {
if (dst.remaining() < 4)
return CoderResult.OVERFLOW;
mark += 2;
put(Surrogate.high(d), dst);
put(Surrogate.low(d), dst);
put(Character.highSurrogate(d), dst);
put(Character.lowSurrogate(d), dst);
}
return CoderResult.UNDERFLOW;
} finally {
......
......@@ -34,7 +34,6 @@ import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import sun.nio.cs.HistoricallyNamedCharset;
import sun.nio.cs.Surrogate;
import static sun.nio.cs.CharsetMapping.*;
public class EUC_TW extends Charset implements HistoricallyNamedCharset
......@@ -159,8 +158,8 @@ public class EUC_TW extends Charset implements HistoricallyNamedCharset
c1[0] = c;
return c1;
} else {
c2[0] = Surrogate.high(0x20000 + c);
c2[1] = Surrogate.low(0x20000 + c);
c2[0] = Character.highSurrogate(0x20000 + c);
c2[1] = Character.lowSurrogate(0x20000 + c);
return c2;
}
}
......@@ -441,7 +440,7 @@ public class EUC_TW extends Charset implements HistoricallyNamedCharset
}
static int encode(char hi, char low, byte[] bb) {
int c = Surrogate.toUCS4(hi, low);
int c = Character.toCodePoint(hi, low);
if ((c & 0xf0000) != 0x20000)
return -1;
c -= 0x20000;
......
......@@ -12628,7 +12628,7 @@ public class GB18030
if (Character.isSurrogate(c)) {
if ((condensedKey=sgp.parse(c, sa, sp, sl)) < 0)
return sgp.error();
// Surogate.toUCS4 looks like
// Character.toCodePoint looks like
// (((high & 0x3ff) << 10) | (low & 0x3ff)) + 0x10000;
// so we add (0x2e248 - 0x10000) to get the "key".
condensedKey += 0x1E248;
......
......@@ -36,7 +36,6 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import sun.nio.cs.HistoricallyNamedCharset;
import sun.nio.cs.Surrogate;
public class IBM33722
extends Charset
......
......@@ -36,7 +36,6 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import sun.nio.cs.HistoricallyNamedCharset;
import sun.nio.cs.Surrogate;
public class IBM964
extends Charset
......
/*
* Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -33,9 +33,7 @@ package sun.security.krb5;
import sun.security.krb5.internal.*;
import sun.security.krb5.internal.ccache.CredentialsCache;
import sun.security.krb5.internal.ktab.*;
import sun.security.krb5.internal.crypto.EType;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.net.InetAddress;
......@@ -506,59 +504,6 @@ public class Credentials {
return result;
}
/**
* Gets service credential from key table. The credential is used to
* decrypt the received client message
* and authenticate the client by verifying the client's credential.
*
* @param serviceName the name of service, using format component@realm
* @param keyTabFile the file of key table.
* @return a <code>KrbCreds</code> object.
*/
public static Credentials getServiceCreds(String serviceName,
File keyTabFile) {
EncryptionKey k = null;
PrincipalName service = null;
Credentials result = null;
try {
service = new PrincipalName(serviceName);
if (service.getRealm() == null) {
String realm = Config.getInstance().getDefaultRealm();
if (realm == null) {
return null;
} else {
service.setRealm(realm);
}
}
} catch (RealmException e) {
if (DEBUG) {
e.printStackTrace();
}
return null;
} catch (KrbException e) {
if (DEBUG) {
e.printStackTrace();
}
return null;
}
KeyTab kt;
if (keyTabFile == null) {
kt = KeyTab.getInstance();
} else {
kt = KeyTab.getInstance(keyTabFile);
}
if ((kt != null) && (kt.findServiceEntry(service))) {
k = kt.readServiceKey(service);
result = new Credentials(null, service, null, null, null,
null, null, null, null, null);
result.serviceKey = k;
}
return result;
}
/**
* Acquires credentials for a specified service using initial credential.
* When the service has a different realm
......
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -130,7 +130,7 @@ public class KrbApRep {
byte[] temp = rep.encPart.decrypt(tgs_creds.key,
KeyUsage.KU_ENC_AP_REP_PART);
byte[] enc_ap_rep_part = rep.encPart.reset(temp, true);
byte[] enc_ap_rep_part = rep.encPart.reset(temp);
encoding = new DerValue(enc_ap_rep_part);
encPart = new EncAPRepPart(encoding);
......
/*
* Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -279,14 +279,14 @@ public class KrbApReq {
byte[] bytes = apReqMessg.ticket.encPart.decrypt(dkey,
KeyUsage.KU_TICKET);
byte[] temp = apReqMessg.ticket.encPart.reset(bytes, true);
byte[] temp = apReqMessg.ticket.encPart.reset(bytes);
EncTicketPart enc_ticketPart = new EncTicketPart(temp);
checkPermittedEType(enc_ticketPart.key.getEType());
byte[] bytes2 = apReqMessg.authenticator.decrypt(enc_ticketPart.key,
KeyUsage.KU_AP_REQ_AUTHENTICATOR);
byte[] temp2 = apReqMessg.authenticator.reset(bytes2, true);
byte[] temp2 = apReqMessg.authenticator.reset(bytes2);
authenticator = new Authenticator(temp2);
ctime = authenticator.ctime;
cusec = authenticator.cusec;
......
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -95,7 +95,7 @@ public class KrbAsRep extends KrbKdcRep {
byte[] enc_as_rep_bytes = rep.encPart.decrypt(dkey,
KeyUsage.KU_ENC_AS_REP_PART);
byte[] enc_as_rep_part = rep.encPart.reset(enc_as_rep_bytes, true);
byte[] enc_as_rep_part = rep.encPart.reset(enc_as_rep_bytes);
encoding = new DerValue(enc_as_rep_part);
EncASRepPart enc_part = new EncASRepPart(encoding);
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册