Mercurial > hg > icedtea9-forest > jdk
changeset 5872:da8649489aff
Merge
author | lana |
---|---|
date | Fri, 10 Aug 2012 10:15:52 -0700 |
parents | bf85c3ab2637 (diff) b3b0d75cb117 (current diff) |
children | 865c411ebcae |
files | |
diffstat | 45 files changed, 2176 insertions(+), 1799 deletions(-) [+] |
line wrap: on
line diff
--- a/make/common/Program.gmk Thu Aug 09 18:02:01 2012 -0700 +++ b/make/common/Program.gmk Fri Aug 10 10:15:52 2012 -0700 @@ -153,7 +153,6 @@ ifndef LOCAL_RESOURCE_FILE @$(ECHO) $(OBJDIR)/$(PROGRAM).res >> $@ endif - @$(ECHO) setargv.obj >> $@ @$(ECHO) Created $@ $(ACTUAL_PROGRAM):: $(OBJDIR)/$(PROGRAM)$(EXE_SUFFIX)
--- a/make/java/jli/Makefile Thu Aug 09 18:02:01 2012 -0700 +++ b/make/java/jli/Makefile Fri Aug 10 10:15:52 2012 -0700 @@ -90,7 +90,8 @@ # add platform specific files ifeq ($(PLATFORM), windows) - FILES_c += java_md.c + FILES_c += java_md.c \ + cmdtoargs.c else # NIXES FILES_c += java_md_common.c ifeq ($(PLATFORM), macosx) @@ -149,7 +150,11 @@ -export:JLI_ReportErrorMessage \ -export:JLI_ReportErrorMessageSys \ -export:JLI_ReportMessage \ - -export:JLI_ReportExceptionDescription + -export:JLI_ReportExceptionDescription \ + -export:JLI_MemAlloc \ + -export:JLI_CmdToArgs \ + -export:JLI_GetStdArgc \ + -export:JLI_GetStdArgs endif # PLATFORM OTHER_INCLUDES += -I$(LAUNCHER_SHARE_SRC)
--- a/make/java/jli/mapfile-vers Thu Aug 09 18:02:01 2012 -0700 +++ b/make/java/jli/mapfile-vers Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ # -# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2005, 2012, 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,6 +34,8 @@ JLI_ReportErrorMessageSys; JLI_ReportMessage; JLI_ReportExceptionDescription; + JLI_GetStdArgs; + JLI_GetStdArgc; local: *; };
--- a/make/java/zip/mapfile-vers Thu Aug 09 18:02:01 2012 -0700 +++ b/make/java/zip/mapfile-vers Fri Aug 10 10:15:52 2012 -0700 @@ -37,16 +37,12 @@ Java_java_util_zip_Deflater_deflateBytes; Java_java_util_zip_Deflater_end; Java_java_util_zip_Deflater_getAdler; - Java_java_util_zip_Deflater_getBytesRead; - Java_java_util_zip_Deflater_getBytesWritten; Java_java_util_zip_Deflater_init; Java_java_util_zip_Deflater_initIDs; Java_java_util_zip_Deflater_reset; Java_java_util_zip_Deflater_setDictionary; Java_java_util_zip_Inflater_end; Java_java_util_zip_Inflater_getAdler; - Java_java_util_zip_Inflater_getBytesRead; - Java_java_util_zip_Inflater_getBytesWritten; Java_java_util_zip_Inflater_inflateBytes; Java_java_util_zip_Inflater_init; Java_java_util_zip_Inflater_initIDs;
--- a/src/share/bin/java.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/java.c Fri Aug 10 10:15:52 2012 -0700 @@ -104,7 +104,6 @@ static jboolean InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn); static jstring NewPlatformString(JNIEnv *env, char *s); -static jobjectArray NewPlatformStringArray(JNIEnv *env, char **strv, int strc); static jclass LoadMainClass(JNIEnv *env, int mode, char *name); static void TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv); @@ -160,7 +159,7 @@ * Running Java code in primordial thread caused many problems. We will * create a new thread to invoke JVM. See 6316197 for more information. */ -static jlong threadStackSize = 0; /* stack size of the new thread */ +static jlong threadStackSize = 0; /* stack size of the new thread */ static jlong maxHeapSize = 0; /* max heap size */ static jlong initialHeapSize = 0; /* inital heap size */ @@ -202,6 +201,14 @@ InitLauncher(javaw); DumpState(); + if (JLI_IsTraceLauncher()) { + int i; + printf("Command line args:\n"); + for (i = 0; i < argc ; i++) { + printf("argv[%d] = %s\n", i, argv[i]); + } + AddOption("-Dsun.java.launcher.diag=true", NULL); + } /* * Make sure the specified version of the JRE is running. @@ -222,15 +229,6 @@ */ SelectVersion(argc, argv, &main_class); - if (JLI_IsTraceLauncher()) { - int i; - printf("Command line args:\n"); - for (i = 0; i < argc ; i++) { - printf("argv[%d] = %s\n", i, argv[i]); - } - AddOption("-Dsun.java.launcher.diag=true", NULL); - } - CreateExecutionEnvironment(&argc, &argv, jrepath, sizeof(jrepath), jvmpath, sizeof(jvmpath), @@ -435,8 +433,8 @@ "([Ljava/lang/String;)V"); CHECK_EXCEPTION_NULL_LEAVE(mainID); - /* Build argument array */ - mainArgs = NewPlatformStringArray(env, argv, argc); + /* Build platform specific argument array */ + mainArgs = CreateApplicationArgs(env, argv, argc); CHECK_EXCEPTION_NULL_LEAVE(mainArgs); /* Invoke main method. */ @@ -1120,8 +1118,9 @@ static jclass helperClass = NULL; -static jclass -GetLauncherHelperClass(JNIEnv *env) { +jclass +GetLauncherHelperClass(JNIEnv *env) +{ if (helperClass == NULL) { NULL_CHECK0(helperClass = FindBootStrapClass(env, "sun/launcher/LauncherHelper")); @@ -1165,7 +1164,7 @@ * Returns a new array of Java string objects for the specified * array of platform strings. */ -static jobjectArray +jobjectArray NewPlatformStringArray(JNIEnv *env, char **strv, int strc) { jarray cls; @@ -1210,7 +1209,7 @@ end = CounterGet(); printf("%ld micro seconds to load main class\n", (long)(jint)Counter2Micros(end-start)); - printf("----_JAVA_LAUNCHER_DEBUG----\n"); + printf("----%s----\n", JLDEBUG_ENV_ENTRY); } return (jclass)result; @@ -1745,7 +1744,6 @@ JLI_MemFree(knownVMs); } - /* * Displays the splash screen according to the jar file name * and image file names stored in environment variables
--- a/src/share/bin/java.h Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/java.h Fri Aug 10 10:15:52 2012 -0700 @@ -219,6 +219,10 @@ const char *name)); jclass FindBootStrapClass(JNIEnv *env, const char *classname); +jobjectArray CreateApplicationArgs(JNIEnv *env, char **strv, int argc); +jobjectArray NewPlatformStringArray(JNIEnv *env, char **strv, int strc); +jclass GetLauncherHelperClass(JNIEnv *env); + int JNICALL JavaMain(void * args); /* entry point */ enum LaunchMode { // cf. sun.launcher.LauncherHelper
--- a/src/share/bin/jli_util.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/jli_util.c Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2012, 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 @@ -102,9 +102,9 @@ void JLI_SetTraceLauncher() { - if (getenv("_JAVA_LAUNCHER_DEBUG") != 0) { + if (getenv(JLDEBUG_ENV_ENTRY) != 0) { _launcher_debug = JNI_TRUE; - JLI_TraceLauncher("----_JAVA_LAUNCHER_DEBUG----\n"); + JLI_TraceLauncher("----%s----\n", JLDEBUG_ENV_ENTRY); } }
--- a/src/share/bin/jli_util.h Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/jli_util.h Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ #include <string.h> #include <stdio.h> #include <jni.h> +#define JLDEBUG_ENV_ENTRY "_JAVA_LAUNCHER_DEBUG" void *JLI_MemAlloc(size_t size); void *JLI_MemRealloc(void *ptr, size_t size); @@ -37,6 +38,14 @@ void JLI_MemFree(void *ptr); int JLI_StrCCmp(const char *s1, const char* s2); +typedef struct { + char *arg; + jboolean has_wildcard; +} StdArg; + +StdArg *JLI_GetStdArgs(); +int JLI_GetStdArgc(); + #define JLI_StrLen(p1) strlen((p1)) #define JLI_StrChr(p1, p2) strchr((p1), (p2)) #define JLI_StrRChr(p1, p2) strrchr((p1), (p2)) @@ -58,6 +67,7 @@ #define JLI_StrCaseCmp(p1, p2) stricmp((p1), (p2)) #define JLI_StrNCaseCmp(p1, p2, p3) strnicmp((p1), (p2), (p3)) #define JLI_Snprintf _snprintf +void JLI_CmdToArgs(char *cmdline); #else #include <unistd.h> #include <strings.h>
--- a/src/share/bin/main.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/main.c Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2012, 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 @@ -87,22 +87,41 @@ const jboolean const_javaw = JNI_TRUE; __initenv = _environ; - margc = __argc; - margv = __argv; - #else /* JAVAW */ int -main(int argc, char ** argv) +main(int argc, char **argv) { int margc; char** margv; const jboolean const_javaw = JNI_FALSE; - +#endif /* JAVAW */ +#ifdef _WIN32 + { + int i = 0; + if (getenv(JLDEBUG_ENV_ENTRY) != NULL) { + printf("Windows original main args:\n"); + for (i = 0 ; i < __argc ; i++) { + printf("wwwd_args[%d] = %s\n", i, __argv[i]); + } + } + } + JLI_CmdToArgs(GetCommandLine()); + margc = JLI_GetStdArgc(); + // add one more to mark the end + margv = (char **)JLI_MemAlloc((margc + 1) * (sizeof(char *))); + { + int i = 0; + StdArg *stdargs = JLI_GetStdArgs(); + for (i = 0 ; i < margc ; i++) { + margv[i] = stdargs[i].arg; + } + margv[i] = NULL; + } +#else /* *NIXES */ margc = argc; margv = argv; -#endif /* JAVAW */ - +#endif /* WIN32 */ return JLI_Launch(margc, margv, sizeof(const_jargs) / sizeof(char *), const_jargs, sizeof(const_appclasspath) / sizeof(char *), const_appclasspath,
--- a/src/share/bin/wildcard.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/bin/wildcard.c Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2012, 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 @@ -129,11 +129,11 @@ HANDLE handle; char *firstFile; /* Stupid FindFirstFile...FindNextFile */ }; - +// since this is used repeatedly we keep it here. +static WIN32_FIND_DATA find_data; static WildcardIterator WildcardIterator_for(const char *wildcard) { - WIN32_FIND_DATA find_data; WildcardIterator it = NEW_(WildcardIterator); HANDLE handle = FindFirstFile(wildcard, &find_data); if (handle == INVALID_HANDLE_VALUE) @@ -146,7 +146,6 @@ static char * WildcardIterator_next(WildcardIterator it) { - WIN32_FIND_DATA find_data; if (it->firstFile != NULL) { char *firstFile = it->firstFile; it->firstFile = NULL; @@ -412,7 +411,7 @@ FileList_expandWildcards(fl); expanded = FileList_join(fl, PATH_SEPARATOR); FileList_free(fl); - if (getenv("_JAVA_LAUNCHER_DEBUG") != 0) + if (getenv(JLDEBUG_ENV_ENTRY) != 0) printf("Expanded wildcards:\n" " before: \"%s\"\n" " after : \"%s\"\n",
--- a/src/share/classes/java/lang/String.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/lang/String.java Fri Aug 10 10:15:52 2012 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2012, 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 @@ -987,7 +987,8 @@ /** * Compares this string to the specified {@code StringBuffer}. The result * is {@code true} if and only if this {@code String} represents the same - * sequence of characters as the specified {@code StringBuffer}. + * sequence of characters as the specified {@code StringBuffer}. This method + * synchronizes on the {@code StringBuffer}. * * @param sb * The {@code StringBuffer} to compare this {@code String} against @@ -999,15 +1000,29 @@ * @since 1.4 */ public boolean contentEquals(StringBuffer sb) { - synchronized (sb) { - return contentEquals((CharSequence) sb); + return contentEquals((CharSequence) sb); + } + + private boolean nonSyncContentEquals(AbstractStringBuilder sb) { + char v1[] = value; + char v2[] = sb.getValue(); + int i = 0; + int n = value.length; + while (n-- != 0) { + if (v1[i] != v2[i]) { + return false; + } + i++; } + return true; } /** - * Compares this string to the specified {@code CharSequence}. The result - * is {@code true} if and only if this {@code String} represents the same - * sequence of char values as the specified sequence. + * Compares this string to the specified {@code CharSequence}. The + * result is {@code true} if and only if this {@code String} represents the + * same sequence of char values as the specified sequence. Note that if the + * {@code CharSequence} is a {@code StringBuffer} then the method + * synchronizes on it. * * @param cs * The sequence to compare this {@code String} against @@ -1023,16 +1038,13 @@ return false; // Argument is a StringBuffer, StringBuilder if (cs instanceof AbstractStringBuilder) { - char v1[] = value; - char v2[] = ((AbstractStringBuilder) cs).getValue(); - int i = 0; - int n = value.length; - while (n-- != 0) { - if (v1[i] != v2[i]) - return false; - i++; + if (cs instanceof StringBuffer) { + synchronized(cs) { + return nonSyncContentEquals((AbstractStringBuilder)cs); + } + } else { + return nonSyncContentEquals((AbstractStringBuilder)cs); } - return true; } // Argument is a String if (cs.equals(this))
--- a/src/share/classes/java/security/cert/Certificate.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/security/cert/Certificate.java Fri Aug 10 10:15:52 2012 -0700 @@ -27,6 +27,7 @@ import java.util.Arrays; +import java.security.Provider; import java.security.PublicKey; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; @@ -187,6 +188,35 @@ SignatureException; /** + * Verifies that this certificate was signed using the + * private key that corresponds to the specified public key. + * This method uses the signature verification engine + * supplied by the specified provider. Note that the specified + * Provider object does not have to be registered in the provider list. + * + * <p> This method was added to version 1.8 of the Java Platform + * Standard Edition. In order to maintain backwards compatibility with + * existing service providers, this method cannot be <code>abstract</code> + * and by default throws an <code>UnsupportedOperationException</code>. + * + * @param key the PublicKey used to carry out the verification. + * @param sigProvider the signature provider. + * + * @exception NoSuchAlgorithmException on unsupported signature + * algorithms. + * @exception InvalidKeyException on incorrect key. + * @exception SignatureException on signature errors. + * @exception CertificateException on encoding errors. + * @exception UnsupportedOperationException if the method is not supported + * @since 1.8 + */ + public void verify(PublicKey key, Provider sigProvider) + throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, SignatureException { + throw new UnsupportedOperationException(); + } + + /** * Returns a string representation of this certificate. * * @return a string representation of this certificate.
--- a/src/share/classes/java/security/cert/X509CRL.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/security/cert/X509CRL.java Fri Aug 10 10:15:52 2012 -0700 @@ -30,6 +30,7 @@ import java.security.InvalidKeyException; import java.security.SignatureException; import java.security.Principal; +import java.security.Provider; import java.security.PublicKey; import javax.security.auth.x500.X500Principal; @@ -216,6 +217,34 @@ SignatureException; /** + * Verifies that this CRL was signed using the + * private key that corresponds to the given public key. + * This method uses the signature verification engine + * supplied by the given provider. Note that the specified Provider object + * does not have to be registered in the provider list. + * + * This method was added to version 1.8 of the Java Platform Standard + * Edition. In order to maintain backwards compatibility with existing + * service providers, this method is not <code>abstract</code> + * and it provides a default implementation. + * + * @param key the PublicKey used to carry out the verification. + * @param sigProvider the signature provider. + * + * @exception NoSuchAlgorithmException on unsupported signature + * algorithms. + * @exception InvalidKeyException on incorrect key. + * @exception SignatureException on signature errors. + * @exception CRLException on encoding errors. + * @since 1.8 + */ + public void verify(PublicKey key, Provider sigProvider) + throws CRLException, NoSuchAlgorithmException, + InvalidKeyException, SignatureException { + X509CRLImpl.verify(this, key, sigProvider); + } + + /** * Gets the <code>version</code> (version number) value from the CRL. * The ASN.1 definition for this is: * <pre>
--- a/src/share/classes/java/security/cert/X509Certificate.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/security/cert/X509Certificate.java Fri Aug 10 10:15:52 2012 -0700 @@ -26,8 +26,7 @@ package java.security.cert; import java.math.BigInteger; -import java.security.Principal; -import java.security.PublicKey; +import java.security.*; import java.util.Collection; import java.util.Date; import java.util.List; @@ -640,4 +639,33 @@ throws CertificateParsingException { return X509CertImpl.getIssuerAlternativeNames(this); } + + /** + * Verifies that this certificate was signed using the + * private key that corresponds to the specified public key. + * This method uses the signature verification engine + * supplied by the specified provider. Note that the specified + * Provider object does not have to be registered in the provider list. + * + * This method was added to version 1.8 of the Java Platform Standard + * Edition. In order to maintain backwards compatibility with existing + * service providers, this method is not <code>abstract</code> + * and it provides a default implementation. + * + * @param key the PublicKey used to carry out the verification. + * @param sigProvider the signature provider. + * + * @exception NoSuchAlgorithmException on unsupported signature + * algorithms. + * @exception InvalidKeyException on incorrect key. + * @exception SignatureException on signature errors. + * @exception CertificateException on encoding errors. + * @exception UnsupportedOperationException if the method is not supported + * @since 1.8 + */ + public void verify(PublicKey key, Provider sigProvider) + throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, SignatureException { + X509CertImpl.verify(this, key, sigProvider); + } }
--- a/src/share/classes/java/util/zip/Deflater.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/util/zip/Deflater.java Fri Aug 10 10:15:52 2012 -0700 @@ -79,6 +79,8 @@ private int level, strategy; private boolean setParams; private boolean finish, finished; + private long bytesRead; + private long bytesWritten; /** * Compression method for the deflate algorithm (the only one currently @@ -423,8 +425,13 @@ synchronized (zsRef) { ensureOpen(); if (flush == NO_FLUSH || flush == SYNC_FLUSH || - flush == FULL_FLUSH) - return deflateBytes(zsRef.address(), b, off, len, flush); + flush == FULL_FLUSH) { + int thisLen = this.len; + int n = deflateBytes(zsRef.address(), b, off, len, flush); + bytesWritten += n; + bytesRead += (thisLen - this.len); + return n; + } throw new IllegalArgumentException(); } } @@ -462,7 +469,7 @@ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); - return getBytesRead(zsRef.address()); + return bytesRead; } } @@ -488,7 +495,7 @@ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); - return getBytesWritten(zsRef.address()); + return bytesWritten; } } @@ -503,6 +510,7 @@ finish = false; finished = false; off = len = 0; + bytesRead = bytesWritten = 0; } } @@ -543,8 +551,6 @@ private native int deflateBytes(long addr, byte[] b, int off, int len, int flush); private native static int getAdler(long addr); - private native static long getBytesRead(long addr); - private native static long getBytesWritten(long addr); private native static void reset(long addr); private native static void end(long addr); }
--- a/src/share/classes/java/util/zip/Inflater.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/java/util/zip/Inflater.java Fri Aug 10 10:15:52 2012 -0700 @@ -78,6 +78,8 @@ private int off, len; private boolean finished; private boolean needDict; + private long bytesRead; + private long bytesWritten; private static final byte[] defaultBuf = new byte[0]; @@ -253,7 +255,11 @@ } synchronized (zsRef) { ensureOpen(); - return inflateBytes(zsRef.address(), b, off, len); + int thisLen = this.len; + int n = inflateBytes(zsRef.address(), b, off, len); + bytesWritten += n; + bytesRead += (thisLen - this.len); + return n; } } @@ -307,7 +313,7 @@ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); - return getBytesRead(zsRef.address()); + return bytesRead; } } @@ -333,7 +339,7 @@ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); - return getBytesWritten(zsRef.address()); + return bytesWritten; } } @@ -348,6 +354,7 @@ finished = false; needDict = false; off = len = 0; + bytesRead = bytesWritten = 0; } } @@ -395,8 +402,6 @@ private native int inflateBytes(long addr, byte[] b, int off, int len) throws DataFormatException; private native static int getAdler(long addr); - private native static long getBytesRead(long addr); - private native static long getBytesWritten(long addr); private native static void reset(long addr); private native static void end(long addr); }
--- a/src/share/classes/sun/launcher/LauncherHelper.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/launcher/LauncherHelper.java Fri Aug 10 10:15:52 2012 -0700 @@ -48,6 +48,9 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.Charset; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ResourceBundle; import java.text.MessageFormat; import java.util.ArrayList; @@ -69,8 +72,6 @@ private static StringBuilder outBuf = new StringBuilder(); - private static ResourceBundle javarb = null; - private static final String INDENT = " "; private static final String VM_SETTINGS = "VM settings:"; private static final String PROP_SETTINGS = "Property settings:"; @@ -78,6 +79,7 @@ // sync with java.c and sun.misc.VM private static final String diagprop = "sun.java.launcher.diag"; + final static boolean trace = sun.misc.VM.getSavedProperty(diagprop) != null; private static final String defaultBundleName = "sun.launcher.resources.launcher"; @@ -428,7 +430,7 @@ if (msgKey != null) { ostream.println(getLocalizedMessage(msgKey, args)); } - if (sun.misc.VM.getSavedProperty(diagprop) != null) { + if (trace) { if (t != null) { t.printStackTrace(); } else { @@ -532,4 +534,82 @@ } return null; // keep the compiler happy } + + static String[] expandArgs(String[] argArray) { + List<StdArg> aList = new ArrayList<>(); + for (String x : argArray) { + aList.add(new StdArg(x)); + } + return expandArgs(aList); + } + + static String[] expandArgs(List<StdArg> argList) { + ArrayList<String> out = new ArrayList<>(); + if (trace) { + System.err.println("Incoming arguments:"); + } + for (StdArg a : argList) { + if (trace) { + System.err.println(a); + } + if (a.needsExpansion) { + File x = new File(a.arg); + File parent = x.getParentFile(); + String glob = x.getName(); + if (parent == null) { + parent = new File("."); + } + try (DirectoryStream<Path> dstream = + Files.newDirectoryStream(parent.toPath(), glob)) { + int entries = 0; + for (Path p : dstream) { + out.add(p.normalize().toString()); + entries++; + } + if (entries == 0) { + out.add(a.arg); + } + } catch (Exception e) { + out.add(a.arg); + if (trace) { + System.err.println("Warning: passing argument as-is " + a); + System.err.print(e); + } + } + } else { + out.add(a.arg); + } + } + String[] oarray = new String[out.size()]; + out.toArray(oarray); + + if (trace) { + System.err.println("Expanded arguments:"); + for (String x : oarray) { + System.err.println(x); + } + } + return oarray; + } + + /* duplicate of the native StdArg struct */ + private static class StdArg { + final String arg; + final boolean needsExpansion; + StdArg(String arg, boolean expand) { + this.arg = arg; + this.needsExpansion = expand; + } + // protocol: first char indicates whether expansion is required + // 'T' = true ; needs expansion + // 'F' = false; needs no expansion + StdArg(String in) { + this.arg = in.substring(1); + needsExpansion = in.charAt(0) == 'T'; + } + public String toString() { + return "StdArg{" + "arg=" + arg + ", needsExpansion=" + needsExpansion + '}'; + } + } } +
--- a/src/share/classes/sun/launcher/resources/launcher.properties Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/launcher/resources/launcher.properties Fri Aug 10 10:15:52 2012 -0700 @@ -136,3 +136,4 @@ Error: An unexpected error occurred while trying to open file {0} java.launcher.jar.error2=manifest not found in {0} java.launcher.jar.error3=no main manifest attribute, in {0} +java.launcher.init.error=initialization error
--- a/src/share/classes/sun/rmi/transport/tcp/TCPTransport.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/rmi/transport/tcp/TCPTransport.java Fri Aug 10 10:15:52 2012 -0700 @@ -28,6 +28,7 @@ import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.UndeclaredThrowableException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -462,8 +463,10 @@ return; } // continue loop + } else if (t instanceof Error) { + throw (Error) t; } else { - throw (Error) t; + throw new UndeclaredThrowableException(t); } } }
--- a/src/share/classes/sun/security/provider/certpath/OCSPResponse.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/security/provider/certpath/OCSPResponse.java Fri Aug 10 10:15:52 2012 -0700 @@ -157,8 +157,6 @@ private final AlgorithmId sigAlgId; private final byte[] signature; private final byte[] tbsResponseData; - private final X500Principal responderName; - private final byte[] responderKey; private final byte[] responseNonce; /* @@ -195,8 +193,6 @@ sigAlgId = null; signature = null; tbsResponseData = null; - responderName = null; - responderKey = null; responseNonce = null; return; } @@ -268,15 +264,17 @@ // responderID short tag = (byte)(seq.tag & 0x1f); if (tag == NAME_TAG) { - responderName = - new X500Principal(new ByteArrayInputStream(seq.toByteArray())); if (debug != null) { + X500Principal responderName = + new X500Principal(seq.getData().toByteArray()); debug.println("OCSP Responder name: " + responderName); } - responderKey = null; } else if (tag == KEY_TAG) { - responderKey = seq.getOctetString(); - responderName = null; + if (debug != null) { + byte[] responderKey = seq.getData().getOctetString(); + debug.println("OCSP Responder key: " + + Debug.toString(responderKey)); + } } else { throw new IOException("Bad encoding in responderID element of " + "OCSP response: expected ASN.1 context specific tag 0 or 1");
--- a/src/share/classes/sun/security/x509/X509CRLImpl.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/security/x509/X509CRLImpl.java Fri Aug 10 10:15:52 2012 -0700 @@ -32,6 +32,7 @@ import java.security.Principal; import java.security.PublicKey; import java.security.PrivateKey; +import java.security.Provider; import java.security.Signature; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; @@ -399,6 +400,61 @@ } /** + * Verifies that this CRL was signed using the + * private key that corresponds to the given public key, + * and that the signature verification was computed by + * the given provider. Note that the specified Provider object + * does not have to be registered in the provider list. + * + * @param key the PublicKey used to carry out the verification. + * @param sigProvider the signature provider. + * + * @exception NoSuchAlgorithmException on unsupported signature + * algorithms. + * @exception InvalidKeyException on incorrect key. + * @exception SignatureException on signature errors. + * @exception CRLException on encoding errors. + */ + public synchronized void verify(PublicKey key, Provider sigProvider) + throws CRLException, NoSuchAlgorithmException, InvalidKeyException, + SignatureException { + + if (signedCRL == null) { + throw new CRLException("Uninitialized CRL"); + } + Signature sigVerf = null; + if (sigProvider == null) { + sigVerf = Signature.getInstance(sigAlgId.getName()); + } else { + sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider); + } + sigVerf.initVerify(key); + + if (tbsCertList == null) { + throw new CRLException("Uninitialized CRL"); + } + + sigVerf.update(tbsCertList, 0, tbsCertList.length); + + if (!sigVerf.verify(signature)) { + throw new SignatureException("Signature does not match."); + } + verifiedPublicKey = key; + } + + /** + * This static method is the default implementation of the + * verify(PublicKey key, Provider sigProvider) method in X509CRL. + * Called from java.security.cert.X509CRL.verify(PublicKey key, + * Provider sigProvider) + */ + public static void verify(X509CRL crl, PublicKey key, + Provider sigProvider) throws CRLException, + NoSuchAlgorithmException, InvalidKeyException, SignatureException { + crl.verify(key, sigProvider); + } + + /** * Encodes an X.509 CRL, and signs it using the given key. * * @param key the private key used for signing.
--- a/src/share/classes/sun/security/x509/X509CertImpl.java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/classes/sun/security/x509/X509CertImpl.java Fri Aug 10 10:15:52 2012 -0700 @@ -453,6 +453,62 @@ } /** + * Throws an exception if the certificate was not signed using the + * verification key provided. This method uses the signature verification + * engine supplied by the specified provider. Note that the specified + * Provider object does not have to be registered in the provider list. + * Successfully verifying a certificate does <em>not</em> indicate that one + * should trust the entity which it represents. + * + * @param key the public key used for verification. + * @param sigProvider the provider. + * + * @exception NoSuchAlgorithmException on unsupported signature + * algorithms. + * @exception InvalidKeyException on incorrect key. + * @exception SignatureException on signature errors. + * @exception CertificateException on encoding errors. + */ + public synchronized void verify(PublicKey key, Provider sigProvider) + throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, SignatureException { + if (signedCert == null) { + throw new CertificateEncodingException("Uninitialized certificate"); + } + // Verify the signature ... + Signature sigVerf = null; + if (sigProvider == null) { + sigVerf = Signature.getInstance(algId.getName()); + } else { + sigVerf = Signature.getInstance(algId.getName(), sigProvider); + } + sigVerf.initVerify(key); + + byte[] rawCert = info.getEncodedInfo(); + sigVerf.update(rawCert, 0, rawCert.length); + + // verify may throw SignatureException for invalid encodings, etc. + verificationResult = sigVerf.verify(signature); + verifiedPublicKey = key; + + if (verificationResult == false) { + throw new SignatureException("Signature does not match."); + } + } + + /** + * This static method is the default implementation of the + * verify(PublicKey key, Provider sigProvider) method in X509Certificate. + * Called from java.security.cert.X509Certificate.verify(PublicKey key, + * Provider sigProvider) + */ + public static void verify(X509Certificate cert, PublicKey key, + Provider sigProvider) throws CertificateException, + NoSuchAlgorithmException, InvalidKeyException, SignatureException { + cert.verify(key, sigProvider); + } + + /** * Creates an X.509 certificate, and signs it using the given key * (associating a signature algorithm and an X.500 name). * This operation is used to implement the certificate generation
--- a/src/share/native/java/util/zip/Deflater.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/Deflater.c Fri Aug 10 10:15:52 2012 -0700 @@ -215,18 +215,6 @@ return ((z_stream *)jlong_to_ptr(addr))->adler; } -JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_getBytesRead(JNIEnv *env, jclass cls, jlong addr) -{ - return ((z_stream *)jlong_to_ptr(addr))->total_in; -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_getBytesWritten(JNIEnv *env, jclass cls, jlong addr) -{ - return ((z_stream *)jlong_to_ptr(addr))->total_out; -} - JNIEXPORT void JNICALL Java_java_util_zip_Deflater_reset(JNIEnv *env, jclass cls, jlong addr) {
--- a/src/share/native/java/util/zip/Inflater.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/Inflater.c Fri Aug 10 10:15:52 2012 -0700 @@ -174,18 +174,6 @@ return ((z_stream *)jlong_to_ptr(addr))->adler; } -JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_getBytesRead(JNIEnv *env, jclass cls, jlong addr) -{ - return ((z_stream *)jlong_to_ptr(addr))->total_in; -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_getBytesWritten(JNIEnv *env, jclass cls, jlong addr) -{ - return ((z_stream *)jlong_to_ptr(addr))->total_out; -} - JNIEXPORT void JNICALL Java_java_util_zip_Inflater_reset(JNIEnv *env, jclass cls, jlong addr) {
--- a/src/share/native/java/util/zip/zlib-1.2.5/compress.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/zlib-1.2.5/compress.c Fri Aug 10 10:15:52 2012 -0700 @@ -75,7 +75,7 @@ deflateEnd(&stream); return err == Z_OK ? Z_BUF_ERROR : err; } - *destLen = (uLong)stream.total_out; + *destLen = stream.total_out; err = deflateEnd(&stream); return err;
--- a/src/share/native/java/util/zip/zlib-1.2.5/inflate.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/zlib-1.2.5/inflate.c Fri Aug 10 10:15:52 2012 -0700 @@ -1370,7 +1370,7 @@ z_streamp strm; { unsigned len; /* number of bytes to look at or looked at */ - long long in, out; /* temporary to save total_in and total_out */ + unsigned long in, out; /* temporary to save total_in and total_out */ unsigned char buf[4]; /* to restore bit buffer to byte string */ struct inflate_state FAR *state;
--- a/src/share/native/java/util/zip/zlib-1.2.5/patches/ChangeLog_java Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/zlib-1.2.5/patches/ChangeLog_java Fri Aug 10 10:15:52 2012 -0700 @@ -8,12 +8,3 @@ (3)updated crc32.c/crc32() unsigned long -> uLong - -(4)updated zlib.h (to support > 4G zipfile): - total_in/out: uLong -> long long - -(5)updated inflate.c/inflateSync() - unsigned long in, out; --> long long in, out; - -(6)updated compress.c/uncompr.c - *destLen = stream.total_out; --> *destLen = (uLong)stream.total_out;
--- a/src/share/native/java/util/zip/zlib-1.2.5/zlib.h Thu Aug 09 18:02:01 2012 -0700 +++ b/src/share/native/java/util/zip/zlib-1.2.5/zlib.h Fri Aug 10 10:15:52 2012 -0700 @@ -109,11 +109,11 @@ typedef struct z_stream_s { Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ - long long total_in; /* total nb of input bytes read so far */ + uLong total_in; /* total nb of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ - long long total_out;/* total nb of bytes output so far */ + uLong total_out; /* total nb of bytes output so far */ char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */
--- a/src/solaris/bin/java_md.c Thu Aug 09 18:02:01 2012 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1522 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -#include "java.h" -#include <dirent.h> -#include <dlfcn.h> -#include <fcntl.h> -#include <inttypes.h> -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <sys/stat.h> -#include <unistd.h> -#include <sys/types.h> -#include "manifest_info.h" -#include "version_comp.h" - -#ifdef __solaris__ -#include <thread.h> -#else -#include <pthread.h> -#endif - -#define JVM_DLL "libjvm.so" -#define JAVA_DLL "libjava.so" - -/* help jettison the LD_LIBRARY_PATH settings in the future */ -#ifndef SETENV_REQUIRED -#define SETENV_REQUIRED -#endif -/* - * If a processor / os combination has the ability to run binaries of - * two data models and cohabitation of jre/jdk bits with both data - * models is supported, then DUAL_MODE is defined. When DUAL_MODE is - * defined, the architecture names for the narrow and wide version of - * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME. - * Currently only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; - * linux i586/amd64 could be defined as DUAL_MODE but that is not the - * current policy. - */ - -#ifdef __solaris__ -# define DUAL_MODE -# ifndef LIBARCH32NAME -# error "The macro LIBARCH32NAME was not defined on the compile line" -# endif -# ifndef LIBARCH64NAME -# error "The macro LIBARCH64NAME was not defined on the compile line" -# endif -# include <sys/systeminfo.h> -# include <sys/elf.h> -# include <stdio.h> -#endif - -/* pointer to environment */ -extern char **environ; - -/* - * A collection of useful strings. One should think of these as #define - * entries, but actual strings can be more efficient (with many compilers). - */ -#ifdef __linux__ -static const char *system_dir = "/usr/java"; -static const char *user_dir = "/java"; -#else /* Solaris */ -static const char *system_dir = "/usr/jdk"; -static const char *user_dir = "/jdk"; -#endif - -/* Store the name of the executable once computed */ -static char *execname = NULL; - -/* - * Flowchart of launcher execs and options processing on unix - * - * The selection of the proper vm shared library to open depends on - * several classes of command line options, including vm "flavor" - * options (-client, -server) and the data model options, -d32 and - * -d64, as well as a version specification which may have come from - * the command line or from the manifest of an executable jar file. - * The vm selection options are not passed to the running - * virtual machine; they must be screened out by the launcher. - * - * The version specification (if any) is processed first by the - * platform independent routine SelectVersion. This may result in - * the exec of the specified launcher version. - * - * Previously the launcher modified the LD_LIBRARY_PATH appropriately for the - * desired data model path, regardless if data models matched or not. The - * launcher subsequently exec'ed the desired executable, in order to make the - * LD_LIBRARY_PATH path available, for the runtime linker. - * - * Now, in most cases,the launcher will dlopen the target libjvm.so. All - * required libraries are loaded by the runtime linker, using the - * $RPATH/$ORIGIN baked into the shared libraries at compile time. Therefore, - * in most cases, the launcher will only exec, if the data models are - * mismatched, and will not set any environment variables, regardless of the - * data models. - * - * However, if the environment contains a LD_LIBRARY_PATH, this will cause the - * launcher to inspect the LD_LIBRARY_PATH. The launcher will check - * a. if the LD_LIBRARY_PATH's first component is the the path to the desired - * libjvm.so - * b. if any other libjvm.so is found in any of the paths. - * If case b is true, then the launcher will set the LD_LIBRARY_PATH to the - * desired JRE and reexec, in order to propagate the environment. - * - * Main - * (incoming argv) - * | - * \|/ - * SelectVersion - * (selects the JRE version, note: not data model) - * | - * \|/ - * CreateExecutionEnvironment - * (determines desired data model) - * | - * | - * \|/ - * Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error) - * | | - * | | - * | \|/ - * | YES - * | | - * | | - * | \|/ - * | CheckJvmType - * | (removes -client, -server etc.) - * | | - * | | - * \|/ \|/ - * YES Find the desired executable/library - * | | - * | | - * \|/ \|/ - * CheckJvmType RequiresSetenv - * (removes -client, -server, etc.) - * | - * | - * \|/ - * TranslateDashJArgs... - * (Prepare to pass args to vm) - * | - * | - * \|/ - * ParseArguments - * (removes -d32 and -d64 if any, - * processes version options, - * creates argument list for vm, - * etc.) - * | - * | - * \|/ - * RequiresSetenv - * Is LD_LIBRARY_PATH - * and friends set ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main - * YES YES --> Continue - * | - * | - * \|/ - * Path is desired JRE ? YES --> Have Desired Model ? NO --> Re-exec --> Main - * NO YES --> Continue - * | - * | - * \|/ - * Paths have well known - * jvm paths ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main - * YES YES --> Continue - * | - * | - * \|/ - * Does libjvm.so exit - * in any of them ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main - * YES YES --> Continue - * | - * | - * \|/ - * Set the LD_LIBRARY_PATH - * | - * | - * \|/ - * Re-exec - * | - * | - * \|/ - * Main - */ - -static const char * SetExecname(char **argv); -static jboolean GetJVMPath(const char *jrepath, const char *jvmtype, - char *jvmpath, jint jvmpathsize, const char * arch); -static jboolean GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative); - - -#define GetArch() GetArchPath(CURRENT_DATA_MODEL) - -const char * -GetArchPath(int nbits) -{ - switch(nbits) { -#ifdef DUAL_MODE - case 32: - return LIBARCH32NAME; - case 64: - return LIBARCH64NAME; -#endif /* DUAL_MODE */ - default: - return LIBARCHNAME; - } -} - -#ifdef SETENV_REQUIRED -static jboolean -JvmExists(const char *path) { - char tmp[PATH_MAX + 1]; - struct stat statbuf; - JLI_Snprintf(tmp, PATH_MAX, "%s/%s", path, JVM_DLL); - if (stat(tmp, &statbuf) == 0) { - return JNI_TRUE; - } - return JNI_FALSE; -} -/* - * contains a lib/$LIBARCH/{server,client}/libjvm.so ? - */ -static jboolean -ContainsLibJVM(int wanted, const char *env) { - char clientPattern[PATH_MAX + 1]; - char serverPattern[PATH_MAX + 1]; - char *envpath; - char *path; - jboolean clientPatternFound; - jboolean serverPatternFound; - - /* fastest path */ - if (env == NULL) { - return JNI_FALSE; - } - - /* the usual suspects */ - JLI_Snprintf(clientPattern, PATH_MAX, "lib/%s/client", GetArchPath(wanted)); - JLI_Snprintf(serverPattern, PATH_MAX, "lib/%s/server", GetArchPath(wanted)); - - /* to optimize for time, test if any of our usual suspects are present. */ - clientPatternFound = JLI_StrStr(env, clientPattern) != NULL; - serverPatternFound = JLI_StrStr(env, serverPattern) != NULL; - if (clientPatternFound == JNI_FALSE && serverPatternFound == JNI_FALSE) { - return JNI_FALSE; - } - - /* - * we have a suspicious path component, check if it contains a libjvm.so - */ - envpath = JLI_StringDup(env); - for (path = JLI_StrTok(envpath, ":"); path != NULL; path = JLI_StrTok(NULL, ":")) { - if (clientPatternFound && JLI_StrStr(path, clientPattern) != NULL) { - if (JvmExists(path)) { - JLI_MemFree(envpath); - return JNI_TRUE; - } - } - if (serverPatternFound && JLI_StrStr(path, serverPattern) != NULL) { - if (JvmExists(path)) { - JLI_MemFree(envpath); - return JNI_TRUE; - } - } - } - JLI_MemFree(envpath); - return JNI_FALSE; -} - -/* - * Test whether the environment variable needs to be set, see flowchart. - */ -static jboolean -RequiresSetenv(int wanted, const char *jvmpath) { - char jpath[PATH_MAX + 1]; - char *llp; - char *dmllp = NULL; - char *p; /* a utility pointer */ - - llp = getenv("LD_LIBRARY_PATH"); -#ifdef __solaris__ - dmllp = (CURRENT_DATA_MODEL == 32) - ? getenv("LD_LIBRARY_PATH_32") - : getenv("LD_LIBRARY_PATH_64"); -#endif /* __solaris__ */ - /* no environment variable is a good environment variable */ - if (llp == NULL && dmllp == NULL) { - return JNI_FALSE; - } -#ifdef __linux - /* - * On linux, if a binary is running as sgid or suid, glibc sets - * LD_LIBRARY_PATH to the empty string for security purposes. (In contrast, - * on Solaris the LD_LIBRARY_PATH variable for a privileged binary does not - * lose its settings; but the dynamic linker does apply more scrutiny to the - * path.) The launcher uses the value of LD_LIBRARY_PATH to prevent an exec - * loop, here and further downstream. Therefore, if we are running sgid or - * suid, this function's setting of LD_LIBRARY_PATH will be ineffective and - * we should case a return from the calling function. Getting the right - * libraries will be handled by the RPATH. In reality, this check is - * redundant, as the previous check for a non-null LD_LIBRARY_PATH will - * return back to the calling function forthwith, it is left here to safe - * guard against any changes, in the glibc's existing security policy. - */ - if ((getgid() != getegid()) || (getuid() != geteuid())) { - return JNI_FALSE; - } -#endif /* __linux */ - - /* - * Prevent recursions. Since LD_LIBRARY_PATH is the one which will be set by - * previous versions of the JRE, thus it is the only path that matters here. - * So we check to see if the desired JRE is set. - */ - JLI_StrNCpy(jpath, jvmpath, PATH_MAX); - p = JLI_StrRChr(jpath, '/'); - *p = '\0'; - if (llp != NULL && JLI_StrNCmp(llp, jpath, JLI_StrLen(jpath)) == 0) { - return JNI_FALSE; - } - - /* scrutinize all the paths further */ - if (llp != NULL && ContainsLibJVM(wanted, llp)) { - return JNI_TRUE; - } - if (dmllp != NULL && ContainsLibJVM(wanted, dmllp)) { - return JNI_TRUE; - } - return JNI_FALSE; -} -#endif /* SETENV_REQUIRED */ - -void -CreateExecutionEnvironment(int *pargc, char ***pargv, - char jrepath[], jint so_jrepath, - char jvmpath[], jint so_jvmpath) { - /* - * First, determine if we are running the desired data model. If we - * are running the desired data model, all the error messages - * associated with calling GetJREPath, ReadKnownVMs, etc. should be - * output. However, if we are not running the desired data model, - * some of the errors should be suppressed since it is more - * informative to issue an error message based on whether or not the - * os/processor combination has dual mode capabilities. - */ - jboolean jvmpathExists; - - /* Compute/set the name of the executable */ - SetExecname(*pargv); - - /* Check data model flags, and exec process, if needed */ - { - char *arch = (char *)GetArch(); /* like sparc or sparcv9 */ - char * jvmtype = NULL; - int argc = *pargc; - char **argv = *pargv; - int running = CURRENT_DATA_MODEL; - - int wanted = running; /* What data mode is being - asked for? Current model is - fine unless another model - is asked for */ -#ifdef SETENV_REQUIRED - jboolean mustsetenv = JNI_FALSE; - char *runpath = NULL; /* existing effective LD_LIBRARY_PATH setting */ - char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */ - char* newpath = NULL; /* path on new LD_LIBRARY_PATH */ - char* lastslash = NULL; - char** newenvp = NULL; /* current environment */ -#ifdef __solaris__ - char* dmpath = NULL; /* data model specific LD_LIBRARY_PATH, - Solaris only */ -#endif /* __solaris__ */ -#endif /* SETENV_REQUIRED */ - - char** newargv = NULL; - int newargc = 0; - - /* - * Starting in 1.5, all unix platforms accept the -d32 and -d64 - * options. On platforms where only one data-model is supported - * (e.g. ia-64 Linux), using the flag for the other data model is - * an error and will terminate the program. - */ - - { /* open new scope to declare local variables */ - int i; - - newargv = (char **)JLI_MemAlloc((argc+1) * sizeof(char*)); - newargv[newargc++] = argv[0]; - - /* scan for data model arguments and remove from argument list; - last occurrence determines desired data model */ - for (i=1; i < argc; i++) { - - if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) { - wanted = 64; - continue; - } - if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) { - wanted = 32; - continue; - } - newargv[newargc++] = argv[i]; - - if (IsJavaArgs()) { - if (argv[i][0] != '-') continue; - } else { - if (JLI_StrCmp(argv[i], "-classpath") == 0 || JLI_StrCmp(argv[i], "-cp") == 0) { - i++; - if (i >= argc) break; - newargv[newargc++] = argv[i]; - continue; - } - if (argv[i][0] != '-') { i++; break; } - } - } - - /* copy rest of args [i .. argc) */ - while (i < argc) { - newargv[newargc++] = argv[i++]; - } - newargv[newargc] = NULL; - - /* - * newargv has all proper arguments here - */ - - argc = newargc; - argv = newargv; - } - - /* If the data model is not changing, it is an error if the - jvmpath does not exist */ - if (wanted == running) { - /* Find out where the JRE is that we will be using. */ - if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) { - JLI_ReportErrorMessage(JRE_ERROR1); - exit(2); - } - - /* Find the specified JVM type */ - if (ReadKnownVMs(jrepath, arch, JNI_FALSE) < 1) { - JLI_ReportErrorMessage(CFG_ERROR7); - exit(1); - } - - jvmpath[0] = '\0'; - jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE); - if (JLI_StrCmp(jvmtype, "ERROR") == 0) { - JLI_ReportErrorMessage(CFG_ERROR9); - exit(4); - } - - if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch )) { - JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath); - exit(4); - } - /* - * we seem to have everything we need, so without further ado - * we return back, otherwise proceed to set the environment. - */ -#ifdef SETENV_REQUIRED - mustsetenv = RequiresSetenv(wanted, jvmpath); - JLI_TraceLauncher("mustsetenv: %s\n", mustsetenv ? "TRUE" : "FALSE"); - - if (mustsetenv == JNI_FALSE) { - return; - } -#else - return; -#endif /* SETENV_REQUIRED */ - } else { /* do the same speculatively or exit */ -#ifdef DUAL_MODE - if (running != wanted) { - /* Find out where the JRE is that we will be using. */ - if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) { - /* give up and let other code report error message */ - JLI_ReportErrorMessage(JRE_ERROR2, wanted); - exit(1); - } - - /* - * Read in jvm.cfg for target data model and process vm - * selection options. - */ - if (ReadKnownVMs(jrepath, GetArchPath(wanted), JNI_TRUE) < 1) { - /* give up and let other code report error message */ - JLI_ReportErrorMessage(JRE_ERROR2, wanted); - exit(1); - } - jvmpath[0] = '\0'; - jvmtype = CheckJvmType(pargc, pargv, JNI_TRUE); - if (JLI_StrCmp(jvmtype, "ERROR") == 0) { - JLI_ReportErrorMessage(CFG_ERROR9); - exit(4); - } - - /* exec child can do error checking on the existence of the path */ - jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted)); -#ifdef SETENV_REQUIRED - mustsetenv = RequiresSetenv(wanted, jvmpath); -#endif /* SETENV_REQUIRED */ - } -#else - JLI_ReportErrorMessage(JRE_ERROR2, wanted); - exit(1); -#endif - } -#ifdef SETENV_REQUIRED - if (mustsetenv) { - /* - * We will set the LD_LIBRARY_PATH as follows: - * - * o $JVMPATH (directory portion only) - * o $JRE/lib/$LIBARCHNAME - * o $JRE/../lib/$LIBARCHNAME - * - * followed by the user's previous effective LD_LIBRARY_PATH, if - * any. - */ - -#ifdef __solaris__ - /* - * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH - * variables: - * - * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if - * data-model specific variables are not set. - * - * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH - * for 64-bit binaries. - * - * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH - * for 32-bit binaries. - * - * The vm uses LD_LIBRARY_PATH to set the java.library.path system - * property. To shield the vm from the complication of multiple - * LD_LIBRARY_PATH variables, if the appropriate data model - * specific variable is set, we will act as if LD_LIBRARY_PATH had - * the value of the data model specific variant and the data model - * specific variant will be unset. Note that the variable for the - * *wanted* data model must be used (if it is set), not simply the - * current running data model. - */ - - switch (wanted) { - case 0: - if (running == 32) { - dmpath = getenv("LD_LIBRARY_PATH_32"); - wanted = 32; - } else { - dmpath = getenv("LD_LIBRARY_PATH_64"); - wanted = 64; - } - break; - - case 32: - dmpath = getenv("LD_LIBRARY_PATH_32"); - break; - - case 64: - dmpath = getenv("LD_LIBRARY_PATH_64"); - break; - - default: - JLI_ReportErrorMessage(JRE_ERROR3, __LINE__); - exit(1); /* unknown value in wanted */ - break; - } - - /* - * If dmpath is NULL, the relevant data model specific variable is - * not set and normal LD_LIBRARY_PATH should be used. - */ - if (dmpath == NULL) { - runpath = getenv("LD_LIBRARY_PATH"); - } else { - runpath = dmpath; - } -#else - /* - * If not on Solaris, assume only a single LD_LIBRARY_PATH - * variable. - */ - runpath = getenv("LD_LIBRARY_PATH"); -#endif /* __solaris__ */ - - /* runpath contains current effective LD_LIBRARY_PATH setting */ - - jvmpath = JLI_StringDup(jvmpath); - new_runpath = JLI_MemAlloc(((runpath != NULL) ? JLI_StrLen(runpath) : 0) + - 2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) + - JLI_StrLen(jvmpath) + 52); - newpath = new_runpath + JLI_StrLen("LD_LIBRARY_PATH="); - - - /* - * Create desired LD_LIBRARY_PATH value for target data model. - */ - { - /* remove the name of the .so from the JVM path */ - lastslash = JLI_StrRChr(jvmpath, '/'); - if (lastslash) - *lastslash = '\0'; - - sprintf(new_runpath, "LD_LIBRARY_PATH=" - "%s:" - "%s/lib/%s:" - "%s/../lib/%s", - jvmpath, -#ifdef DUAL_MODE - jrepath, GetArchPath(wanted), - jrepath, GetArchPath(wanted) -#else - jrepath, arch, - jrepath, arch -#endif - ); - - - /* - * Check to make sure that the prefix of the current path is the - * desired environment variable setting, though the RequiresSetenv - * checks if the desired runpath exists, this logic does a more - * comprehensive check. - */ - if (runpath != NULL && - JLI_StrNCmp(newpath, runpath, JLI_StrLen(newpath)) == 0 && - (runpath[JLI_StrLen(newpath)] == 0 || runpath[JLI_StrLen(newpath)] == ':') && - (running == wanted) /* data model does not have to be changed */ -#ifdef __solaris__ - && (dmpath == NULL) /* data model specific variables not set */ -#endif - ) { - - return; - - } - } - - /* - * Place the desired environment setting onto the prefix of - * LD_LIBRARY_PATH. Note that this prevents any possible infinite - * loop of execv() because we test for the prefix, above. - */ - if (runpath != 0) { - JLI_StrCat(new_runpath, ":"); - JLI_StrCat(new_runpath, runpath); - } - - if (putenv(new_runpath) != 0) { - exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set - properly */ - } - - /* - * Unix systems document that they look at LD_LIBRARY_PATH only - * once at startup, so we have to re-exec the current executable - * to get the changed environment variable to have an effect. - */ - -#ifdef __solaris__ - /* - * If dmpath is not NULL, remove the data model specific string - * in the environment for the exec'ed child. - */ - if (dmpath != NULL) - (void)UnsetEnv((wanted == 32) ? "LD_LIBRARY_PATH_32" : "LD_LIBRARY_PATH_64"); -#endif - - newenvp = environ; - } -#endif /* SETENV_REQUIRED */ - { - char *newexec = execname; -#ifdef DUAL_MODE - /* - * If the data model is being changed, the path to the - * executable must be updated accordingly; the executable name - * and directory the executable resides in are separate. In the - * case of 32 => 64, the new bits are assumed to reside in, e.g. - * "olddir/LIBARCH64NAME/execname"; in the case of 64 => 32, - * the bits are assumed to be in "olddir/../execname". For example, - * - * olddir/sparcv9/execname - * olddir/amd64/execname - * - * for Solaris SPARC and Linux amd64, respectively. - */ - - if (running != wanted) { - char *oldexec = JLI_StrCpy(JLI_MemAlloc(JLI_StrLen(execname) + 1), execname); - char *olddir = oldexec; - char *oldbase = JLI_StrRChr(oldexec, '/'); - - - newexec = JLI_MemAlloc(JLI_StrLen(execname) + 20); - *oldbase++ = 0; - sprintf(newexec, "%s/%s/%s", olddir, - ((wanted == 64) ? LIBARCH64NAME : ".."), oldbase); - argv[0] = newexec; - } -#endif /* DUAL_MODE */ - JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n"); - (void) fflush(stdout); - (void) fflush(stderr); -#ifdef SETENV_REQUIRED - if (mustsetenv) { - execve(newexec, argv, newenvp); - } else { - execv(newexec, argv); - } -#else - execv(newexec, argv); -#endif /* SETENV_REQUIRED */ - JLI_ReportErrorMessageSys(JRE_ERROR4, newexec); - -#ifdef DUAL_MODE - if (running != wanted) { - JLI_ReportErrorMessage(JRE_ERROR5, wanted, running); -#ifdef __solaris__ -#ifdef __sparc - JLI_ReportErrorMessage(JRE_ERROR6); -#else - JLI_ReportErrorMessage(JRE_ERROR7); -#endif /* __sparc */ - } -#endif /* __solaris__ */ -#endif /* DUAL_MODE */ - - } - exit(1); - } -} - -/* - * On Solaris VM choosing is done by the launcher (java.c). - */ -static jboolean -GetJVMPath(const char *jrepath, const char *jvmtype, - char *jvmpath, jint jvmpathsize, const char * arch) -{ - struct stat s; - - if (JLI_StrChr(jvmtype, '/')) { - JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype); - } else { - JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype); - } - - JLI_TraceLauncher("Does `%s' exist ... ", jvmpath); - - if (stat(jvmpath, &s) == 0) { - JLI_TraceLauncher("yes.\n"); - return JNI_TRUE; - } else { - JLI_TraceLauncher("no.\n"); - return JNI_FALSE; - } -} - -/* - * Find path to JRE based on .exe's location or registry settings. - */ -static jboolean -GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) -{ - char libjava[MAXPATHLEN]; - - if (GetApplicationHome(path, pathsize)) { - /* Is JRE co-located with the application? */ - JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/%s/" JAVA_DLL, path, arch); - if (access(libjava, F_OK) == 0) { - JLI_TraceLauncher("JRE path is %s\n", path); - return JNI_TRUE; - } - - /* Does the app ship a private JRE in <apphome>/jre directory? */ - JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/%s/" JAVA_DLL, path, arch); - if (access(libjava, F_OK) == 0) { - JLI_StrCat(path, "/jre"); - JLI_TraceLauncher("JRE path is %s\n", path); - return JNI_TRUE; - } - } - - if (!speculative) - JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL); - return JNI_FALSE; -} - -jboolean -LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn) -{ - void *libjvm; - - JLI_TraceLauncher("JVM path is %s\n", jvmpath); - - libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL); - if (libjvm == NULL) { -#if defined(__solaris__) && defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */ - FILE * fp; - Elf32_Ehdr elf_head; - int count; - int location; - - fp = fopen(jvmpath, "r"); - if (fp == NULL) { - JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); - return JNI_FALSE; - } - - /* read in elf header */ - count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp); - fclose(fp); - if (count < 1) { - JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); - return JNI_FALSE; - } - - /* - * Check for running a server vm (compiled with -xarch=v8plus) - * on a stock v8 processor. In this case, the machine type in - * the elf header would not be included the architecture list - * provided by the isalist command, which is turn is gotten from - * sysinfo. This case cannot occur on 64-bit hardware and thus - * does not have to be checked for in binaries with an LP64 data - * model. - */ - if (elf_head.e_machine == EM_SPARC32PLUS) { - char buf[257]; /* recommended buffer size from sysinfo man - page */ - long length; - char* location; - - length = sysinfo(SI_ISALIST, buf, 257); - if (length > 0) { - location = JLI_StrStr(buf, "sparcv8plus "); - if (location == NULL) { - JLI_ReportErrorMessage(JVM_ERROR3); - return JNI_FALSE; - } - } - } -#endif - JLI_ReportErrorMessage(DLL_ERROR1, __LINE__); - JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); - return JNI_FALSE; - } - - ifn->CreateJavaVM = (CreateJavaVM_t) - dlsym(libjvm, "JNI_CreateJavaVM"); - if (ifn->CreateJavaVM == NULL) { - JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); - return JNI_FALSE; - } - - ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t) - dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs"); - if (ifn->GetDefaultJavaVMInitArgs == NULL) { - JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); - return JNI_FALSE; - } - - return JNI_TRUE; -} - -/* - * If app is "/foo/bin/javac", or "/foo/bin/sparcv9/javac" then put - * "/foo" into buf. - */ -jboolean -GetApplicationHome(char *buf, jint bufsize) -{ - if (execname != NULL) { - JLI_Snprintf(buf, bufsize, "%s", execname); - buf[bufsize-1] = '\0'; - } else { - return JNI_FALSE; - } - - if (JLI_StrRChr(buf, '/') == 0) { - buf[0] = '\0'; - return JNI_FALSE; - } - *(JLI_StrRChr(buf, '/')) = '\0'; /* executable file */ - if (JLI_StrLen(buf) < 4 || JLI_StrRChr(buf, '/') == 0) { - buf[0] = '\0'; - return JNI_FALSE; - } - if (JLI_StrCmp("/bin", buf + JLI_StrLen(buf) - 4) != 0) - *(JLI_StrRChr(buf, '/')) = '\0'; /* sparcv9 or amd64 */ - if (JLI_StrLen(buf) < 4 || JLI_StrCmp("/bin", buf + JLI_StrLen(buf) - 4) != 0) { - buf[0] = '\0'; - return JNI_FALSE; - } - *(JLI_StrRChr(buf, '/')) = '\0'; /* bin */ - - return JNI_TRUE; -} - - -/* - * Return true if the named program exists - */ -static int -ProgramExists(char *name) -{ - struct stat sb; - if (stat(name, &sb) != 0) return 0; - if (S_ISDIR(sb.st_mode)) return 0; - return (sb.st_mode & S_IEXEC) != 0; -} - - -/* - * Find a command in a directory, returning the path. - */ -static char * -Resolve(char *indir, char *cmd) -{ - char name[PATH_MAX + 2], *real; - - if ((JLI_StrLen(indir) + JLI_StrLen(cmd) + 1) > PATH_MAX) return 0; - JLI_Snprintf(name, sizeof(name), "%s%c%s", indir, FILE_SEPARATOR, cmd); - if (!ProgramExists(name)) return 0; - real = JLI_MemAlloc(PATH_MAX + 2); - if (!realpath(name, real)) - JLI_StrCpy(real, name); - return real; -} - - -/* - * Find a path for the executable - */ -static char * -FindExecName(char *program) -{ - char cwdbuf[PATH_MAX+2]; - char *path; - char *tmp_path; - char *f; - char *result = NULL; - - /* absolute path? */ - if (*program == FILE_SEPARATOR || - (FILE_SEPARATOR=='\\' && JLI_StrRChr(program, ':'))) - return Resolve("", program+1); - - /* relative path? */ - if (JLI_StrRChr(program, FILE_SEPARATOR) != 0) { - char buf[PATH_MAX+2]; - return Resolve(getcwd(cwdbuf, sizeof(cwdbuf)), program); - } - - /* from search path? */ - path = getenv("PATH"); - if (!path || !*path) path = "."; - tmp_path = JLI_MemAlloc(JLI_StrLen(path) + 2); - JLI_StrCpy(tmp_path, path); - - for (f=tmp_path; *f && result==0; ) { - char *s = f; - while (*f && (*f != PATH_SEPARATOR)) ++f; - if (*f) *f++ = 0; - if (*s == FILE_SEPARATOR) - result = Resolve(s, program); - else { - /* relative path element */ - char dir[2*PATH_MAX]; - JLI_Snprintf(dir, sizeof(dir), "%s%c%s", getcwd(cwdbuf, sizeof(cwdbuf)), - FILE_SEPARATOR, s); - result = Resolve(dir, program); - } - if (result != 0) break; - } - - JLI_MemFree(tmp_path); - return result; -} - - - -/* - * Compute the name of the executable - * - * In order to re-exec securely we need the absolute path of the - * executable. On Solaris getexecname(3c) may not return an absolute - * path so we use dladdr to get the filename of the executable and - * then use realpath to derive an absolute path. From Solaris 9 - * onwards the filename returned in DL_info structure from dladdr is - * an absolute pathname so technically realpath isn't required. - * On Linux we read the executable name from /proc/self/exe. - * As a fallback, and for platforms other than Solaris and Linux, - * we use FindExecName to compute the executable name. - */ -static const char* -SetExecname(char **argv) -{ - char* exec_path = NULL; -#if defined(__solaris__) - { - Dl_info dlinfo; - int (*fptr)(); - - fptr = (int (*)())dlsym(RTLD_DEFAULT, "main"); - if (fptr == NULL) { - JLI_ReportErrorMessage(DLL_ERROR3, dlerror()); - return JNI_FALSE; - } - - if (dladdr((void*)fptr, &dlinfo)) { - char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1); - if (resolved != NULL) { - exec_path = realpath(dlinfo.dli_fname, resolved); - if (exec_path == NULL) { - JLI_MemFree(resolved); - } - } - } - } -#elif defined(__linux__) - { - const char* self = "/proc/self/exe"; - char buf[PATH_MAX+1]; - int len = readlink(self, buf, PATH_MAX); - if (len >= 0) { - buf[len] = '\0'; /* readlink doesn't nul terminate */ - exec_path = JLI_StringDup(buf); - } - } -#else /* !__solaris__ && !__linux */ - { - /* Not implemented */ - } -#endif - - if (exec_path == NULL) { - exec_path = FindExecName(argv[0]); - } - execname = exec_path; - return exec_path; -} - -void JLI_ReportErrorMessage(const char* fmt, ...) { - va_list vl; - va_start(vl, fmt); - vfprintf(stderr, fmt, vl); - fprintf(stderr, "\n"); - va_end(vl); -} - -void JLI_ReportErrorMessageSys(const char* fmt, ...) { - va_list vl; - char *emsg; - - /* - * TODO: its safer to use strerror_r but is not available on - * Solaris 8. Until then.... - */ - emsg = strerror(errno); - if (emsg != NULL) { - fprintf(stderr, "%s\n", emsg); - } - - va_start(vl, fmt); - vfprintf(stderr, fmt, vl); - fprintf(stderr, "\n"); - va_end(vl); -} - -void JLI_ReportExceptionDescription(JNIEnv * env) { - (*env)->ExceptionDescribe(env); -} - -/* - * Since using the file system as a registry is a bit risky, perform - * additional sanity checks on the identified directory to validate - * it as a valid jre/sdk. - * - * Return 0 if the tests fail; otherwise return non-zero (true). - * - * Note that checking for anything more than the existence of an - * executable object at bin/java relative to the path being checked - * will break the regression tests. - */ -static int -CheckSanity(char *path, char *dir) -{ - char buffer[PATH_MAX]; - - if (JLI_StrLen(path) + JLI_StrLen(dir) + 11 > PATH_MAX) - return (0); /* Silently reject "impossibly" long paths */ - - JLI_Snprintf(buffer, sizeof(buffer), "%s/%s/bin/java", path, dir); - return ((access(buffer, X_OK) == 0) ? 1 : 0); -} - -/* - * Determine if there is an acceptable JRE in the directory dirname. - * Upon locating the "best" one, return a fully qualified path to - * it. "Best" is defined as the most advanced JRE meeting the - * constraints contained in the manifest_info. If no JRE in this - * directory meets the constraints, return NULL. - * - * Note that we don't check for errors in reading the directory - * (which would be done by checking errno). This is because it - * doesn't matter if we get an error reading the directory, or - * we just don't find anything interesting in the directory. We - * just return NULL in either case. - * - * The historical names of j2sdk and j2re were changed to jdk and - * jre respecively as part of the 1.5 rebranding effort. Since the - * former names are legacy on Linux, they must be recognized for - * all time. Fortunately, this is a minor cost. - */ -static char -*ProcessDir(manifest_info *info, char *dirname) -{ - DIR *dirp; - struct dirent *dp; - char *best = NULL; - int offset; - int best_offset = 0; - char *ret_str = NULL; - char buffer[PATH_MAX]; - - if ((dirp = opendir(dirname)) == NULL) - return (NULL); - - do { - if ((dp = readdir(dirp)) != NULL) { - offset = 0; - if ((JLI_StrNCmp(dp->d_name, "jre", 3) == 0) || - (JLI_StrNCmp(dp->d_name, "jdk", 3) == 0)) - offset = 3; - else if (JLI_StrNCmp(dp->d_name, "j2re", 4) == 0) - offset = 4; - else if (JLI_StrNCmp(dp->d_name, "j2sdk", 5) == 0) - offset = 5; - if (offset > 0) { - if ((JLI_AcceptableRelease(dp->d_name + offset, - info->jre_version)) && CheckSanity(dirname, dp->d_name)) - if ((best == NULL) || (JLI_ExactVersionId( - dp->d_name + offset, best + best_offset) > 0)) { - if (best != NULL) - JLI_MemFree(best); - best = JLI_StringDup(dp->d_name); - best_offset = offset; - } - } - } - } while (dp != NULL); - (void) closedir(dirp); - if (best == NULL) - return (NULL); - else { - ret_str = JLI_MemAlloc(JLI_StrLen(dirname) + JLI_StrLen(best) + 2); - sprintf(ret_str, "%s/%s", dirname, best); - JLI_MemFree(best); - return (ret_str); - } -} - -/* - * This is the global entry point. It examines the host for the optimal - * JRE to be used by scanning a set of directories. The set of directories - * is platform dependent and can be overridden by the environment - * variable JAVA_VERSION_PATH. - * - * This routine itself simply determines the set of appropriate - * directories before passing control onto ProcessDir(). - */ -char* -LocateJRE(manifest_info* info) -{ - char *path; - char *home; - char *target = NULL; - char *dp; - char *cp; - - /* - * Start by getting JAVA_VERSION_PATH - */ - if (info->jre_restrict_search) { - path = JLI_StringDup(system_dir); - } else if ((path = getenv("JAVA_VERSION_PATH")) != NULL) { - path = JLI_StringDup(path); - } else { - if ((home = getenv("HOME")) != NULL) { - path = (char *)JLI_MemAlloc(JLI_StrLen(home) + \ - JLI_StrLen(system_dir) + JLI_StrLen(user_dir) + 2); - sprintf(path, "%s%s:%s", home, user_dir, system_dir); - } else { - path = JLI_StringDup(system_dir); - } - } - - /* - * Step through each directory on the path. Terminate the scan with - * the first directory with an acceptable JRE. - */ - cp = dp = path; - while (dp != NULL) { - cp = JLI_StrChr(dp, (int)':'); - if (cp != NULL) - *cp = '\0'; - if ((target = ProcessDir(info, dp)) != NULL) - break; - dp = cp; - if (dp != NULL) - dp++; - } - JLI_MemFree(path); - return (target); -} - -/* - * Given a path to a jre to execute, this routine checks if this process - * is indeed that jre. If not, it exec's that jre. - * - * We want to actually check the paths rather than just the version string - * built into the executable, so that given version specification (and - * JAVA_VERSION_PATH) will yield the exact same Java environment, regardless - * of the version of the arbitrary launcher we start with. - */ -void -ExecJRE(char *jre, char **argv) -{ - char wanted[PATH_MAX]; - const char* progname = GetProgramName(); - - /* - * Resolve the real path to the directory containing the selected JRE. - */ - if (realpath(jre, wanted) == NULL) { - JLI_ReportErrorMessage(JRE_ERROR9, jre); - exit(1); - } - - /* - * Resolve the real path to the currently running launcher. - */ - SetExecname(argv); - if (execname == NULL) { - JLI_ReportErrorMessage(JRE_ERROR10); - exit(1); - } - - /* - * If the path to the selected JRE directory is a match to the initial - * portion of the path to the currently executing JRE, we have a winner! - * If so, just return. - */ - if (JLI_StrNCmp(wanted, execname, JLI_StrLen(wanted)) == 0) - return; /* I am the droid you were looking for */ - - - /* - * This should never happen (because of the selection code in SelectJRE), - * but check for "impossibly" long path names just because buffer overruns - * can be so deadly. - */ - if (JLI_StrLen(wanted) + JLI_StrLen(progname) + 6 > PATH_MAX) { - JLI_ReportErrorMessage(JRE_ERROR11); - exit(1); - } - - /* - * Construct the path and exec it. - */ - (void)JLI_StrCat(JLI_StrCat(wanted, "/bin/"), progname); - argv[0] = JLI_StringDup(progname); - if (JLI_IsTraceLauncher()) { - int i; - printf("ReExec Command: %s (%s)\n", wanted, argv[0]); - printf("ReExec Args:"); - for (i = 1; argv[i] != NULL; i++) - printf(" %s", argv[i]); - printf("\n"); - } - JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n"); - (void)fflush(stdout); - (void)fflush(stderr); - execv(wanted, argv); - JLI_ReportErrorMessageSys(JRE_ERROR12, wanted); - exit(1); -} - -/* - * "Borrowed" from Solaris 10 where the unsetenv() function is being added - * to libc thanks to SUSv3 (Standard Unix Specification, version 3). As - * such, in the fullness of time this will appear in libc on all relevant - * Solaris/Linux platforms and maybe even the Windows platform. At that - * time, this stub can be removed. - * - * This implementation removes the environment locking for multithreaded - * applications. (We don't have access to these mutexes within libc and - * the launcher isn't multithreaded.) Note that what remains is platform - * independent, because it only relies on attributes that a POSIX environment - * defines. - * - * Returns 0 on success, -1 on failure. - * - * Also removed was the setting of errno. The only value of errno set - * was EINVAL ("Invalid Argument"). - */ - -/* - * s1(environ) is name=value - * s2(name) is name(not the form of name=value). - * if names match, return value of 1, else return 0 - */ -static int -match_noeq(const char *s1, const char *s2) -{ - while (*s1 == *s2++) { - if (*s1++ == '=') - return (1); - } - if (*s1 == '=' && s2[-1] == '\0') - return (1); - return (0); -} - -/* - * added for SUSv3 standard - * - * Delete entry from environ. - * Do not free() memory! Other threads may be using it. - * Keep it around forever. - */ -static int -borrowed_unsetenv(const char *name) -{ - long idx; /* index into environ */ - - if (name == NULL || *name == '\0' || - JLI_StrChr(name, '=') != NULL) { - return (-1); - } - - for (idx = 0; environ[idx] != NULL; idx++) { - if (match_noeq(environ[idx], name)) - break; - } - if (environ[idx] == NULL) { - /* name not found but still a success */ - return (0); - } - /* squeeze up one entry */ - do { - environ[idx] = environ[idx+1]; - } while (environ[++idx] != NULL); - - return (0); -} -/* --- End of "borrowed" code --- */ - -/* - * Wrapper for unsetenv() function. - */ -int -UnsetEnv(char *name) -{ - return(borrowed_unsetenv(name)); -} - -/* --- Splash Screen shared library support --- */ - -static const char* SPLASHSCREEN_SO = "libsplashscreen.so"; - -static void* hSplashLib = NULL; - -void* SplashProcAddress(const char* name) { - if (!hSplashLib) { - hSplashLib = dlopen(SPLASHSCREEN_SO, RTLD_LAZY | RTLD_GLOBAL); - } - if (hSplashLib) { - void* sym = dlsym(hSplashLib, name); - return sym; - } else { - return NULL; - } -} - -void SplashFreeLibrary() { - if (hSplashLib) { - dlclose(hSplashLib); - hSplashLib = NULL; - } -} - -const char * -jlong_format_specifier() { - return "%lld"; -} - - - -/* - * Block current thread and continue execution in a new thread - */ -int -ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) { - int rslt; -#ifdef __solaris__ - thread_t tid; - long flags = 0; - if (thr_create(NULL, stack_size, (void *(*)(void *))continuation, args, flags, &tid) == 0) { - void * tmp; - thr_join(tid, NULL, &tmp); - rslt = (int)tmp; - } else { - /* See below. Continue in current thread if thr_create() failed */ - rslt = continuation(args); - } -#else - pthread_t tid; - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); - - if (stack_size > 0) { - pthread_attr_setstacksize(&attr, stack_size); - } - - if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) { - void * tmp; - pthread_join(tid, &tmp); - rslt = (int)tmp; - } else { - /* - * Continue execution in current thread if for some reason (e.g. out of - * memory/LWP) a new thread can't be created. This will likely fail - * later in continuation as JNI_CreateJavaVM needs to create quite a - * few new threads, anyway, just give it a try.. - */ - rslt = continuation(args); - } - - pthread_attr_destroy(&attr); -#endif - return rslt; -} - -/* Coarse estimation of number of digits assuming the worst case is a 64-bit pid. */ -#define MAX_PID_STR_SZ 20 - -void SetJavaLauncherPlatformProps() { - /* Linux only */ -#ifdef __linux__ - const char *substr = "-Dsun.java.launcher.pid="; - char *pid_prop_str = (char *)JLI_MemAlloc(JLI_StrLen(substr) + MAX_PID_STR_SZ + 1); - sprintf(pid_prop_str, "%s%d", substr, getpid()); - AddOption(pid_prop_str, NULL); -#endif -} - -jboolean -IsJavaw() -{ - /* noop on UNIX */ - return JNI_FALSE; -} - -void -InitLauncher(jboolean javaw) -{ - JLI_SetTraceLauncher(); -} - -/* - * The implementation for finding classes from the bootstrap - * class loader, refer to java.h - */ -static FindClassFromBootLoader_t *findBootClass = NULL; - -jclass -FindBootStrapClass(JNIEnv *env, const char* classname) -{ - if (findBootClass == NULL) { - findBootClass = (FindClassFromBootLoader_t *)dlsym(RTLD_DEFAULT, - "JVM_FindClassFromBootLoader"); - if (findBootClass == NULL) { - JLI_ReportErrorMessage(DLL_ERROR4, - "JVM_FindClassFromBootLoader"); - return NULL; - } - } - return findBootClass(env, classname); -}
--- a/src/solaris/bin/java_md_common.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/solaris/bin/java_md_common.c Fri Aug 10 10:15:52 2012 -0700 @@ -502,3 +502,19 @@ return findBootClass(env, classname); } +StdArg +*JLI_GetStdArgs() +{ + return NULL; +} + +int +JLI_GetStdArgc() { + return 0; +} + +jobjectArray +CreateApplicationArgs(JNIEnv *env, char **strv, int argc) +{ + return NewPlatformStringArray(env, strv, argc); +}
--- a/src/solaris/native/java/lang/java_props_md.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/solaris/native/java/lang/java_props_md.c Fri Aug 10 10:15:52 2012 -0700 @@ -135,12 +135,12 @@ #define P_tmpdir "/var/tmp" #endif -static int ParseLocale(int cat, char ** std_language, char ** std_script, +static int ParseLocale(JNIEnv* env, int cat, char ** std_language, char ** std_script, char ** std_country, char ** std_variant, char ** std_encoding) { - char temp[64]; + char *temp = NULL; char *language = NULL, *country = NULL, *variant = NULL, *encoding = NULL; - char *p, encoding_variant[64]; + char *p, *encoding_variant, *old_temp, *old_ev; char *lc; /* Query the locale set for the category */ @@ -156,6 +156,12 @@ return 0; } + temp = malloc(strlen(lc) + 1); + if (temp == NULL) { + JNU_ThrowOutOfMemoryError(env, NULL); + return 0; + } + if (cat == LC_CTYPE) { /* * Workaround for Solaris bug 4201684: Xlib doesn't like @euro @@ -178,6 +184,13 @@ if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) { lc = "en_US"; } + + temp = malloc(strlen(lc) + 1); + if (temp == NULL) { + JNU_ThrowOutOfMemoryError(env, NULL); + return 0; + } + #endif /* @@ -203,6 +216,14 @@ * to a default country if that's possible. It's also used to map * the Solaris locale aliases to their proper Java locale IDs. */ + + encoding_variant = malloc(strlen(temp)+1); + if (encoding_variant == NULL) { + free(temp); + JNU_ThrowOutOfMemoryError(env, NULL); + return 0; + } + if ((p = strchr(temp, '.')) != NULL) { strcpy(encoding_variant, p); /* Copy the leading '.' */ *p = '\0'; @@ -214,7 +235,23 @@ } if (mapLookup(locale_aliases, temp, &p)) { + old_temp = temp; + temp = realloc(temp, strlen(p)+1); + if (temp == NULL) { + free(old_temp); + free(encoding_variant); + JNU_ThrowOutOfMemoryError(env, NULL); + return 0; + } strcpy(temp, p); + old_ev = encoding_variant; + encoding_variant = realloc(encoding_variant, strlen(temp)+1); + if (encoding_variant == NULL) { + free(old_ev); + free(temp); + JNU_ThrowOutOfMemoryError(env, NULL); + return 0; + } // check the "encoding_variant" again, if any. if ((p = strchr(temp, '.')) != NULL) { strcpy(encoding_variant, p); /* Copy the leading '.' */ @@ -326,6 +363,9 @@ #endif } + free(temp); + free(encoding_variant); + return 1; } @@ -478,13 +518,13 @@ * and store these in the user.language, user.country, user.variant and * file.encoding system properties. */ setlocale(LC_ALL, ""); - if (ParseLocale(LC_CTYPE, + if (ParseLocale(env, LC_CTYPE, &(sprops.format_language), &(sprops.format_script), &(sprops.format_country), &(sprops.format_variant), &(sprops.encoding))) { - ParseLocale(LC_MESSAGES, + ParseLocale(env, LC_MESSAGES, &(sprops.language), &(sprops.script), &(sprops.country),
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/windows/bin/cmdtoargs.c Fri Aug 10 10:15:52 2012 -0700 @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2012, 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. + */ + + +/* + * Converts a single string command line to the traditional argc, argv. + * There are rules which govern the breaking of the the arguments, and + * these rules are embodied in the regression tests below, and duplicated + * in the jdk regression tests. + */ + +#ifndef IDE_STANDALONE +#include "java.h" +#include "jli_util.h" +#else /* IDE_STANDALONE */ +// The defines we need for stand alone testing +#include <stdio.h> +#include <stdlib.h> +#include <Windows.h> +#define JNI_TRUE TRUE +#define JNI_FALSE FALSE +#define JLI_MemRealloc realloc +#define JLI_StringDup _strdup +#define JLI_MemFree free +#define jboolean boolean +typedef struct { + char* arg; + boolean has_wildcard; +} StdArg ; +#endif +static StdArg *stdargs; +static int stdargc; + +static char* next_arg(char* cmdline, char* arg, jboolean* wildcard) { + + char* src = cmdline; + char* dest = arg; + jboolean separator = JNI_FALSE; + int quotes = 0; + int slashes = 0; + + char prev = 0; + char ch = 0; + int i; + jboolean done = JNI_FALSE; + + *wildcard = JNI_FALSE; + while ((ch = *src) != 0 && !done) { + switch (ch) { + case '"': + if (separator) { + done = JNI_TRUE; + break; + } + if (prev == '\\') { + for (i = 1; i < slashes; i += 2) { + *dest++ = prev; + } + if (slashes % 2 == 1) { + *dest++ = ch; + } else { + quotes++; + } + } else if (prev == '"' && quotes % 2 == 0) { + quotes++; + *dest++ = ch; // emit every other consecutive quote + } else if (quotes == 0) { + quotes++; // starting quote + } else { + quotes--; // matching quote + } + slashes = 0; + break; + + case '\\': + slashes++; + if (separator) { + done = JNI_TRUE; + separator = JNI_FALSE; + } + break; + + case ' ': + case '\t': + if (quotes % 2 == 1) { + *dest++ = ch; + } else { + separator = JNI_TRUE; + } + slashes = 0; + break; + + case '*': + case '?': + if (separator) { + done = JNI_TRUE; + separator = JNI_FALSE; + break; + } + if (quotes % 2 == 0) { + *wildcard = JNI_TRUE; + } + if (prev == '\\') { + *dest++ = prev; + } + *dest++ = ch; + break; + + default: + if (prev == '\\') { + for (i = 0 ; i < slashes ; i++) { + *dest++ = prev; + } + *dest++ = ch; + } else if (separator) { + done = JNI_TRUE; + } else { + *dest++ = ch; + } + slashes = 0; + } + + if (!done) { + prev = ch; + src++; + } + } + if (prev == '\\') { + for (i = 0; i < slashes; i++) { + *dest++ = prev; + } + } + *dest = 0; + return done ? src : NULL; +} + +int JLI_GetStdArgc() { + return stdargc; +} + +StdArg* JLI_GetStdArgs() { + return stdargs; +} + +void JLI_CmdToArgs(char* cmdline) { + int nargs = 0; + StdArg* argv = NULL; + jboolean wildcard = JNI_FALSE; + char* src = cmdline; + + // allocate arg buffer with sufficient space to receive the largest arg + char* arg = JLI_StringDup(cmdline); + + do { + src = next_arg(src, arg, &wildcard); + // resize to accommodate another Arg + argv = (StdArg*) JLI_MemRealloc(argv, (nargs+1) * sizeof(StdArg)); + argv[nargs].arg = JLI_StringDup(arg); + argv[nargs].has_wildcard = wildcard; + + nargs++; + } while (src != NULL); + + stdargc = nargs; + stdargs = argv; +} + +#ifdef IDE_STANDALONE +void doexit(int rv) { + printf("Hit any key to quit\n"); + int c = getchar(); + exit(rv); +} + +void doabort() { + doexit(1); +} + +class Vector { +public: + char* cmdline; + int argc; + char* argv[10]; + boolean wildcard[10]; + boolean enabled; + + Vector(){} + // Initialize our test vector with the program name, argv[0] + // and the single string command line. + Vector(char* pname, char* cline) { + argv[0] = pname; + wildcard[0] = FALSE; + cmdline = cline; + argc = 1; + enabled = TRUE; + } + + // add our expected strings, the program name has already been + // added so ignore that + void add(char* arg, boolean w) { + argv[argc] = arg; + wildcard[argc] = w; + argc++; + } + + void disable() { + enabled = FALSE; + } + + // validate the returned arguments with the expected arguments, using the + // new CmdToArgs method. + bool check() { + // "pgmname" rest of cmdline ie. pgmname + 2 double quotes + space + cmdline from windows + char* cptr = (char*) malloc(strlen(argv[0]) + sizeof(char) * 3 + strlen(cmdline) + 1); + _snprintf(cptr, MAX_PATH, "\"%s\" %s", argv[0], cmdline); + JLI_CmdToArgs(cptr); + free(cptr); + StdArg *kargv = JLI_GetStdArgs(); + int kargc = JLI_GetStdArgc(); + bool retval = true; + printf("\n===========================\n"); + printf("cmdline=%s\n", cmdline); + if (argc != kargc) { + printf("*** argument count does not match\n"); + printme(); + printtest(kargc, kargv); + doabort(); + } + for (int i = 0 ; i < argc && retval == true ; i++) { + if (strcmp(argv[i], kargv[i].arg) != 0) { + printf("*** argument at [%d] don't match\n got: %s\n exp: %s\n", + i, kargv[i].arg, argv[i]); + doabort(); + } + } + for (int i = 0 ; i < argc && retval == true ; i++) { + if (wildcard[i] != kargv[i].has_wildcard) { + printf("*** expansion flag at [%d] doesn't match\n got: %d\n exp: %d\n", + i, kargv[i].has_wildcard, wildcard[i]); + doabort(); + } + } + for (int i = 0 ; i < kargc ; i++) { + printf("k[%d]=%s\n", i, kargv[i].arg); + printf(" [%d]=%s\n", i, argv[i]); + } + return retval; + } + void printtest(int kargc, StdArg* kargv) { + for (int i = 0 ; i < kargc ; i++) { + printf("k[%d]=%s\n", i, kargv[i].arg); + } + } + void printme() { + for (int i = 0 ; i < argc ; i++) { + printf(" [%d]=%s\n", i, argv[i]); + } + } +}; + +void dotest(Vector** vectors) { + Vector* v = vectors[0]; + for (int i = 0 ; v != NULL;) { + if (v->enabled) { + v->check(); + } + v = vectors[++i]; + } +} + +#define MAXV 128 +int main(int argc, char* argv[]) { + + int n; + for (n=1; n < argc; n++) { + printf("%d %s\n", n, argv[n]); + } + if (n > 1) { + JLI_CmdToArgs(GetCommandLine()); + for (n = 0; n < stdargc; n++) { + printf(" [%d]=%s\n", n, stdargs[n].arg); + printf(" [%d]=%s\n", n, stdargs[n].has_wildcard ? "TRUE" : "FALSE"); + } + doexit(0); + } + + Vector *vectors[MAXV]; + + memset(vectors, 0, sizeof(vectors)); + int i = 0; + Vector* v = new Vector(argv[0], "abcd"); + v->add("abcd", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"a b c d\""); + v->add("a b c d", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a\"b c d\"e"); + v->add("ab c de", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "ab\\\"cd"); + v->add("ab\"cd", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"a b c d\\\\\""); + v->add("a b c d\\", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "ab\\\\\\\"cd"); + v->add("ab\\\"cd", FALSE); + // v->disable(); + vectors[i++] = v; + + + // Windows tests + v = new Vector(argv[0], "a\\\\\\c"); + v->add("a\\\\\\c", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"a\\\\\\d\""); + v->add("a\\\\\\d", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"a b c\" d e"); + v->add("a b c", FALSE); + v->add("d", FALSE); + v->add("e", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"ab\\\"c\" \"\\\\\" d"); + v->add("ab\"c", FALSE); + v->add("\\", FALSE); + v->add("d", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a\\\\\\c d\"e f\"g h"); + v->add("a\\\\\\c", FALSE); + v->add("de fg", FALSE); + v->add("h", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a\\\\\\\"b c d"); + v->add("a\\\"b", FALSE); // XXX "a\\\\\\\"b" + v->add("c", FALSE); + v->add("d", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a\\\\\\\\\"g c\" d e"); // XXX "a\\\\\\\\\"b c\" d e" + v->add("a\\\\\g c", FALSE); // XXX "a\\\\\\\\\"b c" + v->add("d", FALSE); + v->add("e", FALSE); + // v->disable(); + vectors[i++] = v; + + + // Additional tests + v = new Vector(argv[0], "\"a b c\"\""); + v->add("a b c\"", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"\"a b c\"\""); + v->add("a", FALSE); + v->add("b", FALSE); + v->add("c", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"\"\"a b c\"\"\""); + v->add("\"a b c\"", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"\"\"\"a b c\"\"\"\""); + v->add("\"a", FALSE); + v->add("b", FALSE); + v->add("c\"", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"\"\"\"\"a b c\"\"\"\"\""); + v->add("\"\"a b c\"\"", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"C:\\TEST A\\\\\""); + v->add("C:\\TEST A\\", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"\"C:\\TEST A\\\\\"\""); + v->add("C:\\TEST", FALSE); + v->add("A\\", FALSE); + // v->disable(); + vectors[i++] = v; + + + // test if a wildcard is present + v = new Vector(argv[0], "abc*def"); + v->add("abc*def", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"abc*def\""); + v->add("abc*def", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "*.abc"); + v->add("*.abc", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"*.abc\""); + v->add("*.abc", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "x.???"); + v->add("x.???", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\"x.???\""); + v->add("x.???", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "Debug\\*"); + v->add("Debug\\*", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "Debug\\f?a"); + v->add("Debug\\f?a", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "Debug\\?a.java"); + v->add("Debug\\?a.java", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "foo *.noexts"); + v->add("foo", FALSE); + v->add("*.noexts", TRUE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "X\\Y\\Z"); + v->add("X\\Y\\Z", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "\\X\\Y\\Z"); + v->add("\\X\\Y\\Z", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a b"); + v->add("a", FALSE); + v->add("b", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a\tb"); + v->add("a", FALSE); + v->add("b", FALSE); + // v->disable(); + vectors[i++] = v; + + + v = new Vector(argv[0], "a \t b"); + v->add("a", FALSE); + v->add("b", FALSE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "*\\"); + v->add("*\\", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "*/"); + v->add("*/", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], ".\\*"); + v->add(".\\*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "./*"); + v->add("./*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], ".\\*"); + v->add(".\\*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], ".//*"); + v->add(".//*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "..\\..\\*"); + v->add("..\\..\\*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "../../*"); + v->add("../../*", TRUE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "..\\..\\"); + v->add("..\\..\\", FALSE); + // v->disable(); + vectors[i++] = v; + + v = new Vector(argv[0], "../../"); + v->add("../../", FALSE); + // v->disable(); + vectors[i++] = v; + + dotest(vectors); + printf("All tests pass [%d]\n", i); + doexit(0); +} +#endif /* IDE_STANDALONE */
--- a/src/windows/bin/java_md.c Thu Aug 09 18:02:01 2012 -0700 +++ b/src/windows/bin/java_md.c Fri Aug 10 10:15:52 2012 -0700 @@ -1357,3 +1357,89 @@ { return JNI_FALSE; } + +/* + * At this point we have the arguments to the application, and we need to + * check with original stdargs in order to compare which of these truly + * needs expansion. cmdtoargs will specify this if it finds a bare + * (unquoted) argument containing a glob character(s) ie. * or ? + */ +jobjectArray +CreateApplicationArgs(JNIEnv *env, char **strv, int argc) +{ + int i, j, idx, tlen; + jobjectArray outArray, inArray; + char *ostart, *astart, **nargv; + jboolean needs_expansion = JNI_FALSE; + jmethodID mid; + int stdargc; + StdArg *stdargs; + jclass cls = GetLauncherHelperClass(env); + NULL_CHECK0(cls); + + if (argc == 0) { + return NewPlatformStringArray(env, strv, argc); + } + // the holy grail we need to compare with. + stdargs = JLI_GetStdArgs(); + stdargc = JLI_GetStdArgc(); + + // sanity check, this should never happen + if (argc > stdargc) { + JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc); + JLI_TraceLauncher("passing arguments as-is.\n"); + return NewPlatformStringArray(env, strv, argc); + } + + // sanity check, match the args we have, to the holy grail + idx = stdargc - argc; + ostart = stdargs[idx].arg; + astart = strv[0]; + // sanity check, ensure that the first argument of the arrays are the same + if (JLI_StrCmp(ostart, astart) != 0) { + // some thing is amiss the args don't match + JLI_TraceLauncher("Warning: app args parsing error\n"); + JLI_TraceLauncher("passing arguments as-is\n"); + return NewPlatformStringArray(env, strv, argc); + } + + // make a copy of the args which will be expanded in java if required. + nargv = (char **)JLI_MemAlloc(argc * sizeof(char*)); + for (i = 0, j = idx; i < argc; i++, j++) { + jboolean arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0) + ? stdargs[j].has_wildcard + : JNI_FALSE; + if (needs_expansion == JNI_FALSE) + needs_expansion = arg_expand; + + // indicator char + String + NULL terminator, the java method will strip + // out the first character, the indicator character, so no matter what + // we add the indicator + tlen = 1 + JLI_StrLen(strv[i]) + 1; + nargv[i] = (char *) JLI_MemAlloc(tlen); + JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F', strv[i]); + JLI_TraceLauncher("%s\n", nargv[i]); + } + + if (!needs_expansion) { + // clean up any allocated memory and return back the old arguments + for (i = 0 ; i < argc ; i++) { + JLI_MemFree(nargv[i]); + } + JLI_MemFree(nargv); + return NewPlatformStringArray(env, strv, argc); + } + NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls, + "expandArgs", + "([Ljava/lang/String;)[Ljava/lang/String;")); + + // expand the arguments that require expansion, the java method will strip + // out the indicator character. + inArray = NewPlatformStringArray(env, nargv, argc); + outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray); + for (i = 0; i < argc; i++) { + JLI_MemFree(nargv[i]); + } + JLI_MemFree(nargv); + return outArray; +}
--- a/test/ProblemList.txt Thu Aug 09 18:02:01 2012 -0700 +++ b/test/ProblemList.txt Fri Aug 10 10:15:52 2012 -0700 @@ -228,9 +228,6 @@ # 6962637 java/io/File/MaxPathLength.java windows-all -# 7076644 -java/io/File/Basic.java windows-all - # 7145435 - Test needs AWT window server, does not work headless java/io/Serializable/resolveClass/deserializeButton/run.sh macosx-all
--- a/test/java/io/File/basic.sh Thu Aug 09 18:02:01 2012 -0700 +++ b/test/java/io/File/basic.sh Fri Aug 10 10:15:52 2012 -0700 @@ -33,7 +33,16 @@ rm -rf x.Basic.* rm -f x.Basic.non printf "%s" "xyzzyN" > x.Basic.rw -touch x.Basic.ro; chmod ugo-w x.Basic.ro +touch x.Basic.ro +OS=`uname -s` +case "$OS" in + Windows_* | CYGWIN*) + attrib +R x.Basic.ro + ;; + *) + chmod ugo-w x.Basic.ro + ;; +esac mkdir x.Basic.dir if $TESTJAVA/bin/java $* -classpath "$TESTCLASSES" Basic; then [ -f x.Basic.rw ] && (echo "x.Basic.rw not deleted"; exit 1)
--- a/test/java/nio/channels/AsynchronousChannelGroup/AsExecutor.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/java/nio/channels/AsynchronousChannelGroup/AsExecutor.java Fri Aug 10 10:15:52 2012 -0700 @@ -37,24 +37,30 @@ .withFixedThreadPool(5, factory); AsynchronousChannelGroup group2 = AsynchronousChannelGroup .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0); + AsynchronousChannelGroup group3 = AsynchronousChannelGroup + .withThreadPool(Executors.newFixedThreadPool(10, factory)); try { // execute simple tasks testSimpleTask(group1); testSimpleTask(group2); + testSimpleTask(group3); // install security manager and test again System.setSecurityManager( new SecurityManager() ); testSimpleTask(group1); testSimpleTask(group2); + testSimpleTask(group3); // attempt to execute tasks that run with only frames from boot // class loader on the stack. testAttackingTask(group1); testAttackingTask(group2); + testAttackingTask(group3); } finally { group1.shutdown(); group2.shutdown(); + group3.shutdown(); } }
--- a/test/java/nio/channels/AsynchronousChannelGroup/Basic.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/java/nio/channels/AsynchronousChannelGroup/Basic.java Fri Aug 10 10:15:52 2012 -0700 @@ -51,98 +51,135 @@ miscTests(); } + static void testShutdownWithNoChannels(ExecutorService pool, + AsynchronousChannelGroup group) + throws Exception + { + group.shutdown(); + if (!group.isShutdown()) + throw new RuntimeException("Group should be shutdown"); + // group should terminate quickly + boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); + if (!terminated) + throw new RuntimeException("Group should have terminated"); + if (pool != null && !pool.isTerminated()) + throw new RuntimeException("Executor should have terminated"); + } + + static void testShutdownWithChannels(ExecutorService pool, + AsynchronousChannelGroup group) + throws Exception + { + + // create channel that is bound to group + AsynchronousChannel ch; + switch (rand.nextInt(2)) { + case 0 : ch = AsynchronousSocketChannel.open(group); break; + case 1 : ch = AsynchronousServerSocketChannel.open(group); break; + default : throw new AssertionError(); + } + group.shutdown(); + if (!group.isShutdown()) + throw new RuntimeException("Group should be shutdown"); + + // last channel so should terminate after this channel is closed + ch.close(); + + // group should terminate quickly + boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); + if (!terminated) + throw new RuntimeException("Group should have terminated"); + if (pool != null && !pool.isTerminated()) + throw new RuntimeException("Executor should have terminated"); + } + static void shutdownTests() throws Exception { System.out.println("-- test shutdown --"); // test shutdown with no channels in groups - for (int i=0; i<500; i++) { - ExecutorService pool = null; - AsynchronousChannelGroup group; - if (rand.nextBoolean()) { - pool = Executors.newCachedThreadPool(); - group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5)); - } else { - int nThreads = 1 + rand.nextInt(8); - group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, threadFactory); - } - group.shutdown(); - if (!group.isShutdown()) - throw new RuntimeException("Group should be shutdown"); - // group should terminate quickly - boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); - if (!terminated) - throw new RuntimeException("Group should have terminated"); - if (pool != null && !pool.isTerminated()) - throw new RuntimeException("Executor should have terminated"); + for (int i = 0; i < 100; i++) { + ExecutorService pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withCachedThreadPool(pool, rand.nextInt(5)); + testShutdownWithNoChannels(pool, group); + } + for (int i = 0; i < 100; i++) { + int nThreads = 1 + rand.nextInt(8); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withFixedThreadPool(nThreads, threadFactory); + testShutdownWithNoChannels(null, group); + } + for (int i = 0; i < 100; i++) { + ExecutorService pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withThreadPool(pool); + testShutdownWithNoChannels(pool, group); } - // shutdown with channel in group - for (int i=0; i<500; i++) { - ExecutorService pool = null; - AsynchronousChannelGroup group; - if (rand.nextBoolean()) { - pool = Executors.newCachedThreadPool(); - group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(10)); - } else { - int nThreads = 1 + rand.nextInt(8); - group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, threadFactory); - } - // create channel that is bound to group - AsynchronousChannel ch; - switch (rand.nextInt(2)) { - case 0 : ch = AsynchronousSocketChannel.open(group); break; - case 1 : ch = AsynchronousServerSocketChannel.open(group); break; - default : throw new AssertionError(); - } - group.shutdown(); - if (!group.isShutdown()) - throw new RuntimeException("Group should be shutdown"); + // test shutdown with channel in group + for (int i = 0; i < 100; i++) { + ExecutorService pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withCachedThreadPool(pool, rand.nextInt(10)); + testShutdownWithChannels(pool, group); + } + for (int i = 0; i < 100; i++) { + int nThreads = 1 + rand.nextInt(8); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withFixedThreadPool(nThreads, threadFactory); + testShutdownWithChannels(null, group); + } + for (int i = 0; i < 100; i++) { + ExecutorService pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withThreadPool(pool); + testShutdownWithChannels(pool, group); + } + } - // last channel so should terminate after this channel is closed - ch.close(); + static void testShutdownNow(ExecutorService pool, + AsynchronousChannelGroup group) + throws Exception + { + // I/O in progress + AsynchronousServerSocketChannel ch = AsynchronousServerSocketChannel + .open(group).bind(new InetSocketAddress(0)); + ch.accept(); - // group should terminate quickly - boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); - if (!terminated) - throw new RuntimeException("Group should have terminated"); - if (pool != null && !pool.isTerminated()) - throw new RuntimeException("Executor should have terminated"); - } + // forceful shutdown + group.shutdownNow(); + + // shutdownNow is required to close all channels + if (ch.isOpen()) + throw new RuntimeException("Channel should be closed"); + + boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); + if (!terminated) + throw new RuntimeException("Group should have terminated"); + if (pool != null && !pool.isTerminated()) + throw new RuntimeException("Executor should have terminated"); } static void shutdownNowTests() throws Exception { System.out.println("-- test shutdownNow --"); - for (int i=0; i< 10; i++) { - ExecutorService pool = null; - AsynchronousChannelGroup group; - if (rand.nextBoolean()) { - pool = Executors.newCachedThreadPool(); - group = AsynchronousChannelGroup + for (int i = 0; i < 10; i++) { + ExecutorService pool = pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup .withCachedThreadPool(pool, rand.nextInt(5)); - } else { - int nThreads = 1 + rand.nextInt(8); - group = AsynchronousChannelGroup + testShutdownNow(pool, group); + } + for (int i = 0; i < 10; i++) { + int nThreads = 1 + rand.nextInt(8); + AsynchronousChannelGroup group = AsynchronousChannelGroup .withFixedThreadPool(nThreads, threadFactory); - } - - // I/O in progress - AsynchronousServerSocketChannel ch = AsynchronousServerSocketChannel - .open(group).bind(new InetSocketAddress(0)); - ch.accept(); - - // forceful shutdown - group.shutdownNow(); - - // shutdownNow is required to close all channels - if (ch.isOpen()) - throw new RuntimeException("Channel should be closed"); - - boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS); - if (!terminated) - throw new RuntimeException("Group should have terminated"); - if (pool != null && !pool.isTerminated()) - throw new RuntimeException("Executor should have terminated"); + testShutdownNow(null, group); + } + for (int i = 0; i < 10; i++) { + ExecutorService pool = Executors.newCachedThreadPool(); + AsynchronousChannelGroup group = AsynchronousChannelGroup + .withThreadPool(pool); + testShutdownNow(pool, group); } } @@ -245,5 +282,10 @@ throw new RuntimeException("NPE expected"); } catch (NullPointerException x) { } + try { + AsynchronousChannelGroup.withThreadPool(null); + throw new RuntimeException("NPE expected"); + } catch (NullPointerException e) { + } } }
--- a/test/java/nio/channels/AsynchronousChannelGroup/Restart.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/java/nio/channels/AsynchronousChannelGroup/Restart.java Fri Aug 10 10:15:52 2012 -0700 @@ -71,17 +71,23 @@ testRestart(group, 100); group.shutdown(); - // group with custom thread pool + // group with cached thread pool ExecutorService pool = Executors.newCachedThreadPool(factory); group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5)); testRestart(group, 100); group.shutdown(); + // group with custom thread pool + group = AsynchronousChannelGroup + .withThreadPool(Executors.newFixedThreadPool(1+rand.nextInt(5), factory)); + testRestart(group, 100); + group.shutdown(); + // give time for threads to terminate Thread.sleep(3000); int actual = exceptionCount.get(); - if (actual != 200) - throw new RuntimeException(actual + " exceptions, expected: " + 200); + if (actual != 300) + throw new RuntimeException(actual + " exceptions, expected: " + 300); } static void testRestart(AsynchronousChannelGroup group, int count)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/util/zip/TotalInOut.java Fri Aug 10 10:15:52 2012 -0700 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2012, 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. + */ + +/* @test + * @bug 7188852 + * @summary Test De/Inflater.getBytesRead/Written() + */ + +import java.io.*; +import java.util.*; +import java.util.zip.*; + + +public class TotalInOut { + static final int BUF_SIZE= 1 * 1024 * 1024; + + static void realMain (String[] args) throws Throwable { + long dataSize = 128L * 1024L * 1024L; // 128MB + if (args.length > 0 && "large".equals(args[0])) + dataSize = 5L * 1024L * 1024L * 1024L; // 5GB + + Deflater deflater = new Deflater(); + Inflater inflater = new Inflater(); + + byte[] dataIn = new byte[BUF_SIZE]; + byte[] dataOut = new byte[BUF_SIZE]; + byte[] tmp = new byte[BUF_SIZE]; + + Random r = new Random(); + r.nextBytes(dataIn); + long bytesReadDef = 0; + long bytesWrittenDef = 0; + long bytesReadInf = 0; + long bytesWrittenInf = 0; + + deflater.setInput(dataIn, 0, dataIn.length); + while (bytesReadDef < dataSize || bytesWrittenInf < dataSize) { + int len = r.nextInt(BUF_SIZE/2) + BUF_SIZE / 2; + if (deflater.needsInput()) { + bytesReadDef += dataIn.length; + check(bytesReadDef == deflater.getBytesRead()); + deflater.setInput(dataIn, 0, dataIn.length); + } + int n = deflater.deflate(tmp, 0, len); + bytesWrittenDef += n; + check(bytesWrittenDef == deflater.getBytesWritten()); + + inflater.setInput(tmp, 0, n); + bytesReadInf += n; + while (!inflater.needsInput()) { + bytesWrittenInf += inflater.inflate(dataOut, 0, dataOut.length); + check(bytesWrittenInf == inflater.getBytesWritten()); + } + check(bytesReadInf == inflater.getBytesRead()); + } + } + + //--------------------- Infrastructure --------------------------- + static volatile int passed = 0, failed = 0; + static void pass() {passed++;} + static void pass(String msg) {System.out.println(msg); passed++;} + static void fail() {failed++; Thread.dumpStack();} + static void fail(String msg) {System.out.println(msg); fail();} + static void unexpected(Throwable t) {failed++; t.printStackTrace();} + static void unexpected(Throwable t, String msg) { + System.out.println(msg); failed++; t.printStackTrace();} + static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;} + static void equal(Object x, Object y) { + if (x == null ? y == null : x.equals(y)) pass(); + else fail(x + " not equal to " + y);} + public static void main(String[] args) throws Throwable { + try {realMain(args);} catch (Throwable t) {unexpected(t);} + System.out.println("\nPassed = " + passed + " failed = " + failed); + if (failed > 0) throw new AssertionError("Some tests failed");} +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/x509/X509CRLImpl/Verify.java Fri Aug 10 10:15:52 2012 -0700 @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 7026347 + * @summary X509CRL should have verify(PublicKey key, Provider sigProvider) + */ + +import java.io.ByteArrayInputStream; +import java.security.*; +import java.security.cert.*; + +public class Verify { + + static String selfSignedCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICPjCCAaegAwIBAgIBADANBgkqhkiG9w0BAQQFADAfMQswCQYDVQQGEwJVUzEQ\n" + + "MA4GA1UEChMHRXhhbXBsZTAeFw0wOTA0MjcwMjI0MzJaFw0zMDA0MDcwMjI0MzJa\n" + + "MB8xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdFeGFtcGxlMIGfMA0GCSqGSIb3DQEB\n" + + "AQUAA4GNADCBiQKBgQC4OTag24sTxL2tXTNuvpmUEtdxrYAZoFsslFQ60T+WD9wQ\n" + + "Jeiw87FSPsR2vxRuv0j8DNm2a4h7LNNIFcLurfNldbz5pvgZ7VqdbbUMPE9qP85n\n" + + "jgDl4woyRTSUeRI4A7O0CO6NpES21dtbdhroWQrEkHxpnrDPxsxrz5gf2m3gqwID\n" + + "AQABo4GJMIGGMB0GA1UdDgQWBBSCJd0hpl5PdAD9IZS+Hzng4lXLGzBHBgNVHSME\n" + + "QDA+gBSCJd0hpl5PdAD9IZS+Hzng4lXLG6EjpCEwHzELMAkGA1UEBhMCVVMxEDAO\n" + + "BgNVBAoTB0V4YW1wbGWCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAgQw\n" + + "DQYJKoZIhvcNAQEEBQADgYEAluy6HIjWcq009lTLmhp+Np6dxU78pInBK8RZkza0\n" + + "484qGaxFGD3UGyZkI5uWmsH2XuMbuox5khfIq6781gmkPBHXBIEtJN8eLusOHEye\n" + + "iE8h7WI+N3qa6Pj56WionMrioqC/3X+b06o147bbhx8U0vkYv/HyPaITOFfMXTdz\n" + + "Vjw=\n" + + "-----END CERTIFICATE-----"; + + static String crlIssuerCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICKzCCAZSgAwIBAgIBAjANBgkqhkiG9w0BAQQFADAfMQswCQYDVQQGEwJVUzEQ\n" + + "MA4GA1UEChMHRXhhbXBsZTAeFw0wOTA0MjcwMjI0MzNaFw0yOTAxMTIwMjI0MzNa\n" + + "MB8xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdFeGFtcGxlMIGfMA0GCSqGSIb3DQEB\n" + + "AQUAA4GNADCBiQKBgQDMJeBMBybHykI/YpwUJ4O9euqDSLb1kpWpceBS8TVqvgBC\n" + + "SgUJWtFZL0i6bdvF6mMdlbuBkGzhXqHiVAi96/zRLbUC9F8SMEJ6MuD+YhQ0ZFTQ\n" + + "atKy8zf8O9XzztelLJ26Gqb7QPV133WY3haAqHtCXOhEKkCN16NOYNC37DTaJwID\n" + + "AQABo3cwdTAdBgNVHQ4EFgQULXSWzXzUOIpOJpzbSCpW42IJUugwRwYDVR0jBEAw\n" + + "PoAUgiXdIaZeT3QA/SGUvh854OJVyxuhI6QhMB8xCzAJBgNVBAYTAlVTMRAwDgYD\n" + + "VQQKEwdFeGFtcGxlggEAMAsGA1UdDwQEAwIBAjANBgkqhkiG9w0BAQQFAAOBgQAY\n" + + "eMnf5AHSNlyUlzXk8o2S0h4gCuvKX6C3kFfKuZcWvFAbx4yQOWLS2s15/nzR4+AP\n" + + "FGX3lgJjROyAh7fGedTQK+NFWwkM2ag1g3hXktnlnT1qHohi0w31nVBJxXEDO/Ck\n" + + "uJTpJGt8XxxbFaw5v7cHy7XuTAeU/sekvjEiNHW00Q==\n" + + "-----END CERTIFICATE-----"; + + static String crlStr = + "-----BEGIN X509 CRL-----\n" + + "MIIBGzCBhQIBATANBgkqhkiG9w0BAQQFADAfMQswCQYDVQQGEwJVUzEQMA4GA1UE\n" + + "ChMHRXhhbXBsZRcNMDkwNDI3MDIzODA0WhcNMjgwNjI2MDIzODA0WjAiMCACAQUX\n" + + "DTA5MDQyNzAyMzgwMFowDDAKBgNVHRUEAwoBBKAOMAwwCgYDVR0UBAMCAQIwDQYJ\n" + + "KoZIhvcNAQEEBQADgYEAoarfzXEtw3ZDi4f9U8eSvRIipHSyxOrJC7HR/hM5VhmY\n" + + "CErChny6x9lBVg9s57tfD/P9PSzBLusCcHwHMAbMOEcTltVVKUWZnnbumpywlYyg\n" + + "oKLrE9+yCOkYUOpiRlz43/3vkEL5hjIKMcDSZnPKBZi1h16Yj2hPe9GMibNip54=\n" + + "-----END X509 CRL-----"; + + private static X509CRL crl; + private static PublicKey selfSignedCertPubKey; + private static PublicKey crlIssuerCertPubKey; + + public static void main(String[] args) throws Exception { + setup(); + + /* + * Verify CRL with its own public key. + * Should pass. + */ + verifyCRL(crlIssuerCertPubKey, "SunRsaSign"); + + /* + * Try to verify CRL with a provider that does not have a Signature + * implementation. + * Should fail with NoSuchAlgorithmException. + */ + try { + verifyCRL(crlIssuerCertPubKey, "SunPCSC"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (NoSuchAlgorithmException e) { + System.out.println("Caught the correct exception."); + } + + /* + * Try to verify CRL with a provider that has a Signature implementation + * but not of the right algorithm (MD5withRSA). + * Should fail with NoSuchAlgorithmException. + */ + try { + verifyCRL(crlIssuerCertPubKey, "SUN"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (NoSuchAlgorithmException e) { + System.out.println("Caught the correct exception."); + } + + /* + * Try to verify CRL with the wrong public key. + * Should fail with SignatureException. + */ + try { + verifyCRL(selfSignedCertPubKey, "SunRsaSign"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (SignatureException e) { + System.out.println("Caught the correct exception."); + } + } + + private static void setup() throws CertificateException, CRLException { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + /* Create CRL */ + ByteArrayInputStream inputStream = + new ByteArrayInputStream(crlStr.getBytes()); + crl = (X509CRL)cf.generateCRL(inputStream); + + /* Get public key of the CRL issuer cert */ + inputStream = new ByteArrayInputStream(crlIssuerCertStr.getBytes()); + X509Certificate cert + = (X509Certificate)cf.generateCertificate(inputStream); + crlIssuerCertPubKey = cert.getPublicKey(); + + /* Get public key of the self-signed Cert */ + inputStream = new ByteArrayInputStream(selfSignedCertStr.getBytes()); + selfSignedCertPubKey = cf.generateCertificate(inputStream).getPublicKey(); + } + + private static void verifyCRL(PublicKey key, String providerName) + throws CRLException, NoSuchAlgorithmException, InvalidKeyException, + SignatureException { + Provider provider = Security.getProvider(providerName); + crl.verify(key, provider); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/x509/X509CertImpl/Verify.java Fri Aug 10 10:15:52 2012 -0700 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 7026347 + * @summary Certificate should have + * verify(PublicKey key, Provider sigProvider) + */ + +import java.io.ByteArrayInputStream; +import java.security.*; +import java.security.cert.*; + +public class Verify { + + static String selfSignedCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICPjCCAaegAwIBAgIBADANBgkqhkiG9w0BAQQFADAfMQswCQYDVQQGEwJVUzEQ\n" + + "MA4GA1UEChMHRXhhbXBsZTAeFw0wOTA0MjcwMjI0MzJaFw0zMDA0MDcwMjI0MzJa\n" + + "MB8xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdFeGFtcGxlMIGfMA0GCSqGSIb3DQEB\n" + + "AQUAA4GNADCBiQKBgQC4OTag24sTxL2tXTNuvpmUEtdxrYAZoFsslFQ60T+WD9wQ\n" + + "Jeiw87FSPsR2vxRuv0j8DNm2a4h7LNNIFcLurfNldbz5pvgZ7VqdbbUMPE9qP85n\n" + + "jgDl4woyRTSUeRI4A7O0CO6NpES21dtbdhroWQrEkHxpnrDPxsxrz5gf2m3gqwID\n" + + "AQABo4GJMIGGMB0GA1UdDgQWBBSCJd0hpl5PdAD9IZS+Hzng4lXLGzBHBgNVHSME\n" + + "QDA+gBSCJd0hpl5PdAD9IZS+Hzng4lXLG6EjpCEwHzELMAkGA1UEBhMCVVMxEDAO\n" + + "BgNVBAoTB0V4YW1wbGWCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAgQw\n" + + "DQYJKoZIhvcNAQEEBQADgYEAluy6HIjWcq009lTLmhp+Np6dxU78pInBK8RZkza0\n" + + "484qGaxFGD3UGyZkI5uWmsH2XuMbuox5khfIq6781gmkPBHXBIEtJN8eLusOHEye\n" + + "iE8h7WI+N3qa6Pj56WionMrioqC/3X+b06o147bbhx8U0vkYv/HyPaITOFfMXTdz\n" + + "Vjw=\n" + + "-----END CERTIFICATE-----"; + + static String crlIssuerCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICKzCCAZSgAwIBAgIBAjANBgkqhkiG9w0BAQQFADAfMQswCQYDVQQGEwJVUzEQ\n" + + "MA4GA1UEChMHRXhhbXBsZTAeFw0wOTA0MjcwMjI0MzNaFw0yOTAxMTIwMjI0MzNa\n" + + "MB8xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdFeGFtcGxlMIGfMA0GCSqGSIb3DQEB\n" + + "AQUAA4GNADCBiQKBgQDMJeBMBybHykI/YpwUJ4O9euqDSLb1kpWpceBS8TVqvgBC\n" + + "SgUJWtFZL0i6bdvF6mMdlbuBkGzhXqHiVAi96/zRLbUC9F8SMEJ6MuD+YhQ0ZFTQ\n" + + "atKy8zf8O9XzztelLJ26Gqb7QPV133WY3haAqHtCXOhEKkCN16NOYNC37DTaJwID\n" + + "AQABo3cwdTAdBgNVHQ4EFgQULXSWzXzUOIpOJpzbSCpW42IJUugwRwYDVR0jBEAw\n" + + "PoAUgiXdIaZeT3QA/SGUvh854OJVyxuhI6QhMB8xCzAJBgNVBAYTAlVTMRAwDgYD\n" + + "VQQKEwdFeGFtcGxlggEAMAsGA1UdDwQEAwIBAjANBgkqhkiG9w0BAQQFAAOBgQAY\n" + + "eMnf5AHSNlyUlzXk8o2S0h4gCuvKX6C3kFfKuZcWvFAbx4yQOWLS2s15/nzR4+AP\n" + + "FGX3lgJjROyAh7fGedTQK+NFWwkM2ag1g3hXktnlnT1qHohi0w31nVBJxXEDO/Ck\n" + + "uJTpJGt8XxxbFaw5v7cHy7XuTAeU/sekvjEiNHW00Q==\n" + + "-----END CERTIFICATE-----"; + + private static X509Certificate cert; + private static PublicKey selfSignedCertPubKey; + private static PublicKey crlIssuerCertPubKey; + + public static void main(String[] args) throws Exception { + setup(); + + /* + * Verify certificate with its own public key. + * Should pass. + */ + verifyCert(selfSignedCertPubKey,"SunRsaSign"); + + /* + * Try to verify certificate with a provider that does not have a + * Signature implementation. + * Should fail with NoSuchAlgorithmException. + */ + try { + verifyCert(selfSignedCertPubKey, "SunPCSC"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (NoSuchAlgorithmException e) { + System.out.println("Caught the correct exception."); + } + + /* + * Try to verify certificate with a provider that has a Signature + * implementation but not of the right algorithm (MD5withRSA). + * Should fail with NoSuchAlgorithmException. + */ + try { + verifyCert(selfSignedCertPubKey, "SUN"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (NoSuchAlgorithmException e) { + System.out.println("Caught the correct exception."); + } + + /* + * Try to verify certificate with the wrong public key. + * Should fail with SignatureException. + */ + try { + verifyCert(crlIssuerCertPubKey, "SunRsaSign"); + throw new RuntimeException("Didn't catch the exception properly"); + } catch (SignatureException e) { + System.out.println("Caught the correct exception."); + } + } + + private static void setup() throws CertificateException, CRLException { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + /* Get public key of the CRL issuer cert */ + ByteArrayInputStream inputStream + = new ByteArrayInputStream(crlIssuerCertStr.getBytes()); + cert = (X509Certificate)cf.generateCertificate(inputStream); + crlIssuerCertPubKey = cert.getPublicKey(); + + /* Get public key of the self-signed Cert */ + inputStream = new ByteArrayInputStream(selfSignedCertStr.getBytes()); + selfSignedCertPubKey = cf.generateCertificate(inputStream).getPublicKey(); + } + + private static void verifyCert(PublicKey key, String providerName) + throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, SignatureException { + Provider provider = Security.getProvider(providerName); + cert.verify(key, provider); + } +}
--- a/test/sun/tools/jcmd/help_help.out Thu Aug 09 18:02:01 2012 -0700 +++ b/test/sun/tools/jcmd/help_help.out Fri Aug 10 10:15:52 2012 -0700 @@ -1,7 +1,7 @@ help For more information about a specific command use 'help <command>'. With no argument this will show a list of available commands. 'help all' will show help for all commands. -Impact: Low: +Impact: Low Syntax : help [options] [<command name>]
--- a/test/tools/launcher/Arrrghs.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/tools/launcher/Arrrghs.java Fri Aug 10 10:15:52 2012 -0700 @@ -24,7 +24,7 @@ /** * @test * @bug 5030233 6214916 6356475 6571029 6684582 6742159 4459600 6758881 6753938 - * 6894719 6968053 7151434 + * 6894719 6968053 7151434 7146424 * @summary Argument parsing validation. * @compile -XDignore.symbol.file Arrrghs.java * @run main Arrrghs @@ -36,7 +36,13 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class Arrrghs extends TestHelper { private Arrrghs(){} @@ -75,7 +81,7 @@ /* * This method detects the cookie in the output stream of the process. */ - private static boolean detectCookie(InputStream istream, + private boolean detectCookie(InputStream istream, String expectedArguments) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(istream)); boolean retval = false; @@ -105,7 +111,7 @@ return retval; } - private static boolean doTest0(ProcessBuilder pb, String expectedArguments) { + private boolean doReExecTest0(ProcessBuilder pb, String expectedArguments) { boolean retval = false; try { pb.redirectErrorStream(true); @@ -121,26 +127,27 @@ } /** - * This method return true if the expected and detected arguments are the same. + * This method returns true if the expected and detected arguments are the same. * Quoting could cause dissimilar testArguments and expected arguments. */ - static int doTest(String testArguments, String expectedPattern) { + int doReExecTest(String testArguments, String expectedPattern) { ProcessBuilder pb = new ProcessBuilder(javaCmd, VersionStr, testArguments); Map<String, String> env = pb.environment(); - env.put("_JAVA_LAUNCHER_DEBUG", "true"); - return doTest0(pb, testArguments) ? 0 : 1; + env.put(JLDEBUG_KEY, "true"); + return doReExecTest0(pb, testArguments) ? 0 : 1; } /** * A convenience method for identical test pattern and expected arguments */ - static int doTest(String testPattern) { - return doTest(testPattern, testPattern); + int doReExecTest(String testPattern) { + return doReExecTest(testPattern, testPattern); } - static void quoteParsingTests() { + @Test + void testQuoteParsingThroughReExec() { /* * Tests for 6214916 * These tests require that a JVM (any JVM) be installed in the system registry. @@ -154,103 +161,433 @@ } // Basic test - testExitValue += doTest("-a -b -c -d"); + testExitValue += doReExecTest("-a -b -c -d"); // Basic test with many spaces - testExitValue += doTest("-a -b -c -d"); + testExitValue += doReExecTest("-a -b -c -d"); // Quoted whitespace does matter ? - testExitValue += doTest("-a \"\"-b -c\"\" -d"); + testExitValue += doReExecTest("-a \"\"-b -c\"\" -d"); // Escaped quotes outside of quotes as literals - testExitValue += doTest("-a \\\"-b -c\\\" -d"); + testExitValue += doReExecTest("-a \\\"-b -c\\\" -d"); // Check for escaped quotes inside of quotes as literal - testExitValue += doTest("-a \"-b \\\"stuff\\\"\" -c -d"); + testExitValue += doReExecTest("-a \"-b \\\"stuff\\\"\" -c -d"); // A quote preceeded by an odd number of slashes is a literal quote - testExitValue += doTest("-a -b\\\\\\\" -c -d"); + testExitValue += doReExecTest("-a -b\\\\\\\" -c -d"); // A quote preceeded by an even number of slashes is a literal quote // see 6214916. - testExitValue += doTest("-a -b\\\\\\\\\" -c -d"); + testExitValue += doReExecTest("-a -b\\\\\\\\\" -c -d"); // Make sure that whitespace doesn't interfere with the removal of the // appropriate tokens. (space-tab-space preceeds -jre-restict-search). - testExitValue += doTest("-a -b \t -jre-restrict-search -c -d","-a -b -c -d"); + testExitValue += doReExecTest("-a -b \t -jre-restrict-search -c -d", "-a -b -c -d"); // Make sure that the mJRE tokens being stripped, aren't stripped if // they happen to appear as arguments to the main class. - testExitValue += doTest("foo -version:1.1+"); + testExitValue += doReExecTest("foo -version:1.1+"); + + System.out.println("Completed arguments quoting tests with " + + testExitValue + " errors"); + } + // the pattern we hope to see in the output + static final Pattern ArgPattern = Pattern.compile("\\s*argv\\[[0-9]*\\].*=.*"); + + void checkArgumentParsing(String inArgs, String... expArgs) throws IOException { + List<String> scratchpad = new ArrayList<>(); + scratchpad.add("set " + JLDEBUG_KEY + "=true"); + // GAK, -version needs to be added so that windows can flush its stderr + // exiting the process prematurely can terminate the stderr. + scratchpad.add(javaCmd + " -version " + inArgs); + File batFile = new File("atest.bat"); + java.nio.file.Files.deleteIfExists(batFile.toPath()); + createFile(batFile, scratchpad); + + TestResult tr = doExec(batFile.getName()); + + ArrayList<String> expList = new ArrayList<>(); + expList.add(javaCmd); + expList.add("-version"); + expList.addAll(Arrays.asList(expArgs)); + + List<String> gotList = new ArrayList<>(); + for (String x : tr.testOutput) { + Matcher m = ArgPattern.matcher(x); + if (m.matches()) { + String a[] = x.split("="); + gotList.add(a[a.length - 1].trim()); + } + } + if (!gotList.equals(expList)) { + System.out.println(tr); + System.out.println("Expected args:"); + System.out.println(expList); + System.out.println("Obtained args:"); + System.out.println(gotList); + throw new RuntimeException("Error: args do not match"); + } + System.out.println("\'" + inArgs + "\'" + " - Test passed"); + } + + /* + * This tests general quoting and are specific to Windows, *nixes + * need not worry about this, these have been tested with Windows + * implementation and those that are known to work are used against + * the java implementation. Note that the ProcessBuilder gets in the + * way when testing some of these arguments, therefore we need to + * create and execute a .bat file containing the arguments. + */ + @Test + void testArgumentParsing() throws IOException { + if (!isWindows) + return; + // no quotes + checkArgumentParsing("a b c d", "a", "b", "c", "d"); + + // single quotes + checkArgumentParsing("\"a b c d\"", "a b c d"); + + //double quotes + checkArgumentParsing("\"\"a b c d\"\"", "a", "b", "c", "d"); + + // triple quotes + checkArgumentParsing("\"\"\"a b c d\"\"\"", "\"a b c d\""); + + // a literal within single quotes + checkArgumentParsing("\"a\"b c d\"e\"", "ab", "c", "de"); + + // a literal within double quotes + checkArgumentParsing("\"\"a\"b c d\"e\"\"", "ab c de"); + + // a literal quote + checkArgumentParsing("a\\\"b", "a\"b"); + + // double back-slash + checkArgumentParsing("\"a b c d\\\\\"", "a b c d\\"); + + // triple back-slash + checkArgumentParsing("a\\\\\\\"b", "a\\\"b"); + + // dangling quote + checkArgumentParsing("\"a b c\"\"", "a b c\""); + + // expansions of white space separators + checkArgumentParsing("a b", "a", "b"); + checkArgumentParsing("a\tb", "a", "b"); + checkArgumentParsing("a \t b", "a", "b"); + + checkArgumentParsing("\"C:\\TEST A\\\\\"", "C:\\TEST A\\"); + checkArgumentParsing("\"\"C:\\TEST A\\\\\"\"", "C:\\TEST", "A\\"); + + // MS Windows tests + // triple back-slash + checkArgumentParsing("a\\\\\\d", "a\\\\\\d"); + + // triple back-slash in quotes + checkArgumentParsing("\"a\\\\\\d\"", "a\\\\\\d"); + + // slashes separating characters + checkArgumentParsing("X\\Y\\Z", "X\\Y\\Z"); + checkArgumentParsing("\\X\\Y\\Z", "\\X\\Y\\Z"); + + // literals within dangling quotes, etc. + checkArgumentParsing("\"a b c\" d e", "a b c", "d", "e"); + checkArgumentParsing("\"ab\\\"c\" \"\\\\\" d", "ab\"c", "\\", "d"); + checkArgumentParsing("a\\\\\\c d\"e f\"g h", "a\\\\\\c", "de fg", "h"); + checkArgumentParsing("a\\\\\\\"b c d", "a\\\"b", "c", "d"); + checkArgumentParsing("a\\\\\\\\\"g c\" d e", "a\\\\g c", "d", "e"); + + // treatment of back-slashes + checkArgumentParsing("*\\", "*\\"); + checkArgumentParsing("*/", "*/"); + checkArgumentParsing(".\\*", ".\\*"); + checkArgumentParsing("./*", "./*"); + checkArgumentParsing("..\\..\\*", "..\\..\\*"); + checkArgumentParsing("../../*", "../../*"); + checkArgumentParsing("..\\..\\", "..\\..\\"); + checkArgumentParsing("../../", "../../"); + } + + private void initEmptyDir(File emptyDir) throws IOException { + if (emptyDir.exists()) { + recursiveDelete(emptyDir); + } + emptyDir.mkdir(); + } + + private void initDirWithJavaFiles(File libDir) throws IOException { + + if (libDir.exists()) { + recursiveDelete(libDir); + } + libDir.mkdirs(); + ArrayList<String> scratchpad = new ArrayList<>(); + scratchpad.add("package lib;"); + scratchpad.add("public class Fbo {"); + scratchpad.add("public static void main(String... args){Foo.f();}"); + scratchpad.add("public static void f(){}"); + scratchpad.add("}"); + createFile(new File(libDir, "Fbo.java"), scratchpad); + + scratchpad.clear(); + scratchpad.add("package lib;"); + scratchpad.add("public class Foo {"); + scratchpad.add("public static void main(String... args){"); + scratchpad.add("for (String x : args) {"); + scratchpad.add("System.out.println(x);"); + scratchpad.add("}"); + scratchpad.add("Fbo.f();"); + scratchpad.add("}"); + scratchpad.add("public static void f(){}"); + scratchpad.add("}"); + createFile(new File(libDir, "Foo.java"), scratchpad); + } + + void checkArgumentWildcard(String inArgs, String... expArgs) throws IOException { + String[] in = {inArgs}; + checkArgumentWildcard(in, expArgs); - System.out.println("Completed arguments quoting tests with " + - testExitValue + " errors"); + // now add arbitrary arguments before and after + String[] outInArgs = { "-Q", inArgs, "-R"}; + + String[] outExpArgs = new String[expArgs.length + 2]; + outExpArgs[0] = "-Q"; + System.arraycopy(expArgs, 0, outExpArgs, 1, expArgs.length); + outExpArgs[expArgs.length + 1] = "-R"; + checkArgumentWildcard(outInArgs, outExpArgs); + } + + void checkArgumentWildcard(String[] inArgs, String[] expArgs) throws IOException { + ArrayList<String> argList = new ArrayList<>(); + argList.add(javaCmd); + argList.add("-cp"); + argList.add("lib" + File.separator + "*"); + argList.add("lib.Foo"); + argList.addAll(Arrays.asList(inArgs)); + String[] cmds = new String[argList.size()]; + argList.toArray(cmds); + TestResult tr = doExec(cmds); + if (!tr.isOK()) { + System.out.println(tr); + throw new RuntimeException("Error: classpath single entry wildcard entry"); + } + + ArrayList<String> expList = new ArrayList<>(); + expList.addAll(Arrays.asList(expArgs)); + + List<String> gotList = new ArrayList<>(); + for (String x : tr.testOutput) { + gotList.add(x.trim()); + } + if (!gotList.equals(expList)) { + System.out.println(tr); + System.out.println("Expected args:"); + System.out.println(expList); + System.out.println("Obtained args:"); + System.out.println(gotList); + throw new RuntimeException("Error: args do not match"); + } + System.out.print("\'"); + for (String x : inArgs) { + System.out.print(x + " "); + } + System.out.println("\'" + " - Test passed"); } /* + * These tests are not expected to work on *nixes, and are ignored. + */ + @Test + void testWildCardArgumentProcessing() throws IOException { + if (!isWindows) + return; + File cwd = new File("."); + File libDir = new File(cwd, "lib"); + initDirWithJavaFiles(libDir); + initEmptyDir(new File(cwd, "empty")); + + // test if javac (the command) can compile *.java + TestResult tr = doExec(javacCmd, libDir.getName() + File.separator + "*.java"); + if (!tr.isOK()) { + System.out.println(tr); + throw new RuntimeException("Error: compiling java wildcards"); + } + + // use the jar cmd to create jars using the ? wildcard + File jarFoo = new File(libDir, "Foo.jar"); + tr = doExec(jarCmd, "cvf", jarFoo.getAbsolutePath(), "lib" + File.separator + "F?o.class"); + if (!tr.isOK()) { + System.out.println(tr); + throw new RuntimeException("Error: creating jar with wildcards"); + } + + // now the litmus test!, this should work + checkArgumentWildcard("a", "a"); + + // test for basic expansion + checkArgumentWildcard("lib\\F*java", "lib\\Fbo.java", "lib\\Foo.java"); + + // basic expansion in quotes + checkArgumentWildcard("\"lib\\F*java\"", "lib\\F*java"); + + checkArgumentWildcard("lib\\**", "lib\\Fbo.class", "lib\\Fbo.java", + "lib\\Foo.class", "lib\\Foo.jar", "lib\\Foo.java"); + + checkArgumentWildcard("lib\\*?", "lib\\Fbo.class", "lib\\Fbo.java", + "lib\\Foo.class", "lib\\Foo.jar", "lib\\Foo.java"); + + checkArgumentWildcard("lib\\?*", "lib\\Fbo.class", "lib\\Fbo.java", + "lib\\Foo.class", "lib\\Foo.jar", "lib\\Foo.java"); + + checkArgumentWildcard("lib\\?", "lib\\?"); + + // test for basic expansion + checkArgumentWildcard("lib\\*java", "lib\\Fbo.java", "lib\\Foo.java"); + + // basic expansion in quotes + checkArgumentWildcard("\"lib\\*.java\"", "lib\\*.java"); + + // suffix expansion + checkArgumentWildcard("lib\\*.class", "lib\\Fbo.class", "lib\\Foo.class"); + + // suffix expansion in quotes + checkArgumentWildcard("\"lib\\*.class\"", "lib\\*.class"); + + // check for ? expansion now + checkArgumentWildcard("lib\\F?o.java", "lib\\Fbo.java", "lib\\Foo.java"); + + // check ? in quotes + checkArgumentWildcard("\"lib\\F?o.java\"", "lib\\F?o.java"); + + // check ? as suffixes + checkArgumentWildcard("lib\\F?o.????", "lib\\Fbo.java", "lib\\Foo.java"); + + // check ? in a leading role + checkArgumentWildcard("lib\\???.java", "lib\\Fbo.java", "lib\\Foo.java"); + checkArgumentWildcard("\"lib\\???.java\"", "lib\\???.java"); + + // check ? prefixed with - + checkArgumentWildcard("-?", "-?"); + + // check * prefixed with - + checkArgumentWildcard("-*", "-*"); + + // check on empty directory + checkArgumentWildcard("empty\\*", "empty\\*"); + checkArgumentWildcard("empty\\**", "empty\\**"); + checkArgumentWildcard("empty\\?", "empty\\?"); + checkArgumentWildcard("empty\\??", "empty\\??"); + checkArgumentWildcard("empty\\*?", "empty\\*?"); + checkArgumentWildcard("empty\\?*", "empty\\?*"); + + } + + void doArgumentCheck(String inArgs, String... expArgs) { + Map<String, String> env = new HashMap<>(); + env.put(JLDEBUG_KEY, "true"); + TestResult tr = doExec(env, javaCmd, inArgs); + System.out.println(tr); + int sindex = tr.testOutput.indexOf("Command line args:"); + if (sindex < 0) { + System.out.println(tr); + throw new RuntimeException("Error: no output"); + } + sindex++; // skip over the tag + List<String> gotList = new ArrayList<>(); + for (String x : tr.testOutput.subList(sindex, sindex + expArgs.length)) { + String a[] = x.split("="); + gotList.add(a[a.length - 1].trim()); + } + List<String> expList = Arrays.asList(expArgs); + if (!gotList.equals(expList)) { + System.out.println(tr); + System.out.println("Expected args:"); + System.out.println(expList); + System.out.println("Obtained args:"); + System.out.println(gotList); + throw new RuntimeException("Error: args do not match"); + } + } + + + /* * These tests are usually run on non-existent targets to check error results */ - static void runBasicErrorMessageTests() { + @Test + void testBasicErrorMessages() { // Tests for 5030233 TestResult tr = doExec(javaCmd, "-cp"); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); tr = doExec(javaCmd, "-classpath"); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); tr = doExec(javaCmd, "-jar"); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); tr = doExec(javacCmd, "-cp"); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // Test for 6356475 "REGRESSION:"java -X" from cmdline fails" tr = doExec(javaCmd, "-X"); tr.checkPositive(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); tr = doExec(javaCmd, "-help"); tr.checkPositive(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // 6753938, test for non-negative exit value for an incorrectly formed // command line, '% java' tr = doExec(javaCmd); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // 6753938, test for non-negative exit value for an incorrectly formed // command line, '% java -Xcomp' tr = doExec(javaCmd, "-Xcomp"); tr.checkNegative(); tr.isNotZeroOutput(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // 7151434, test for non-negative exit value for an incorrectly formed // command line, '% java -jar -W', note the bogus -W tr = doExec(javaCmd, "-jar", "-W"); tr.checkNegative(); tr.contains("Unrecognized option: -W"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); } /* * Tests various dispositions of the main method, these tests are limited * to English locales as they check for error messages that are localized. */ - static void runMainMethodTests() throws FileNotFoundException { + @Test + void testMainMethod() throws FileNotFoundException { if (!isEnglishLocale()) { return; } @@ -262,55 +599,65 @@ (String[])null); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("Error: Could not find or load main class MIA"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "MIA"); tr.contains("Error: Could not find or load main class MIA"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // incorrect method access createJar(new File("some.jar"), new File("Foo"), "private static void main(String[] args){}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("Error: Main method not found in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "Foo"); tr.contains("Error: Main method not found in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // incorrect return type createJar(new File("some.jar"), new File("Foo"), "public static int main(String[] args){return 1;}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("Error: Main method must return a value of type void in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "Foo"); tr.contains("Error: Main method must return a value of type void in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // incorrect parameter type createJar(new File("some.jar"), new File("Foo"), "public static void main(Object[] args){}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("Error: Main method not found in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "Foo"); tr.contains("Error: Main method not found in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // incorrect method type - non-static createJar(new File("some.jar"), new File("Foo"), "public void main(String[] args){}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("Error: Main method is not static in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "Foo"); tr.contains("Error: Main method is not static in class Foo"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // amongst a potpourri of kindred main methods, is the right one chosen ? createJar(new File("some.jar"), new File("Foo"), @@ -322,25 +669,29 @@ "public static void main(String[] args) {System.out.println(\"THE_CHOSEN_ONE\");}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.contains("THE_CHOSEN_ONE"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-cp", "some.jar", "Foo"); tr.contains("THE_CHOSEN_ONE"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // test for extraneous whitespace in the Main-Class attribute createJar(" Foo ", new File("some.jar"), new File("Foo"), "public static void main(String... args){}"); tr = doExec(javaCmd, "-jar", "some.jar"); tr.checkPositive(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); } /* * tests 6968053, ie. we turn on the -Xdiag (for now) flag and check if * the suppressed stack traces are exposed, ignore these tests for localized * locales, limiting to English only. */ - static void runDiagOptionTests() throws FileNotFoundException { + @Test + void testDiagOptions() throws FileNotFoundException { if (!isEnglishLocale()) { // only english version return; } @@ -351,48 +702,51 @@ tr = doExec(javaCmd, "-Xdiag", "-jar", "some.jar"); tr.contains("Error: Could not find or load main class MIA"); tr.contains("java.lang.ClassNotFoundException: MIA"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // use classpath to check tr = doExec(javaCmd, "-Xdiag", "-cp", "some.jar", "MIA"); tr.contains("Error: Could not find or load main class MIA"); tr.contains("java.lang.ClassNotFoundException: MIA"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); // a missing class on the classpath tr = doExec(javaCmd, "-Xdiag", "NonExistentClass"); tr.contains("Error: Could not find or load main class NonExistentClass"); tr.contains("java.lang.ClassNotFoundException: NonExistentClass"); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); } - static void test6894719() { + @Test + static void testJreRestrictSearchFlag() { // test both arguments to ensure they exist TestResult tr = null; tr = doExec(javaCmd, "-no-jre-restrict-search", "-version"); tr.checkPositive(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); tr = doExec(javaCmd, "-jre-restrict-search", "-version"); tr.checkPositive(); - System.out.println(tr); + if (!tr.testStatus) + System.out.println(tr); } /** * @param args the command line arguments * @throws java.io.FileNotFoundException */ - public static void main(String[] args) throws FileNotFoundException { + public static void main(String[] args) throws Exception { if (debug) { System.out.println("Starting Arrrghs tests"); } - quoteParsingTests(); - runBasicErrorMessageTests(); - runMainMethodTests(); - test6894719(); - runDiagOptionTests(); + Arrrghs a = new Arrrghs(); + a.run(args); if (testExitValue > 0) { System.out.println("Total of " + testExitValue + " failed"); System.exit(1);
--- a/test/tools/launcher/TestHelper.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/tools/launcher/TestHelper.java Fri Aug 10 10:15:52 2012 -0700 @@ -21,6 +21,12 @@ * questions. */ +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Method; +import java.util.regex.Pattern; import java.io.StringWriter; import java.io.PrintWriter; import java.util.Set; @@ -63,6 +69,8 @@ static final String javawCmd; static final String java64Cmd; static final String javacCmd; + static final String jarCmd; + static final JavaCompiler compiler; static final boolean debug = Boolean.getBoolean("TestHelper.Debug"); @@ -131,6 +139,15 @@ : new File(binDir, "javac"); javacCmd = javacCmdFile.getAbsolutePath(); + File jarCmdFile = (isWindows) + ? new File(binDir, "jar.exe") + : new File(binDir, "jar"); + jarCmd = jarCmdFile.getAbsolutePath(); + if (!jarCmdFile.canExecute()) { + throw new RuntimeException("java <" + TestHelper.jarCmd + + "> must exist and should be executable"); + } + if (isWindows) { File javawCmdFile = new File(binDir, "javaw.exe"); javawCmd = javawCmdFile.getAbsolutePath(); @@ -158,6 +175,37 @@ java64Cmd = null; } } + void run(String[] args) throws Exception { + int passed = 0, failed = 0; + final Pattern p = (args != null && args.length > 0) + ? Pattern.compile(args[0]) + : null; + for (Method m : this.getClass().getDeclaredMethods()) { + boolean selected = (p == null) + ? m.isAnnotationPresent(Test.class) + : p.matcher(m.getName()).matches(); + if (selected) { + try { + m.invoke(this, (Object[]) null); + System.out.println(m.getName() + ": OK"); + passed++; + System.out.printf("Passed: %d, Failed: %d, ExitValue: %d%n", + passed, failed, testExitValue); + } catch (Throwable ex) { + System.out.printf("Test %s failed: %s %n", m, ex.getCause()); + failed++; + } + } + } + System.out.printf("Total: Passed: %d, Failed %d%n", passed, failed); + if (failed > 0) { + throw new RuntimeException("Tests failed: " + failed); + } + if (passed == 0 && failed == 0) { + throw new AssertionError("No test(s) selected: passed = " + + passed + ", failed = " + failed + " ??????????"); + } + } /* * is a dual mode available in the test jdk @@ -395,6 +443,7 @@ List<String> testOutput; Map<String, String> env; Throwable t; + boolean testStatus; public TestResult(String str, int rv, List<String> oList, Map<String, String> env, Throwable t) { @@ -405,9 +454,12 @@ testOutput = oList; this.env = env; this.t = t; + testStatus = true; } void appendError(String x) { + testStatus = false; + testExitValue++; status.println(TEST_PREFIX + x); } @@ -418,14 +470,12 @@ void checkNegative() { if (exitValue == 0) { appendError("test must not return 0 exit value"); - testExitValue++; } } void checkPositive() { if (exitValue != 0) { appendError("test did not return 0 exit value"); - testExitValue++; } } @@ -436,7 +486,6 @@ boolean isZeroOutput() { if (!testOutput.isEmpty()) { appendError("No message from cmd please"); - testExitValue++; return false; } return true; @@ -445,7 +494,6 @@ boolean isNotZeroOutput() { if (testOutput.isEmpty()) { appendError("Missing message"); - testExitValue++; return false; } return true; @@ -454,6 +502,7 @@ @Override public String toString() { status.println("++++Begin Test Info++++"); + status.println("Test Status: " + (testStatus ? "PASS" : "FAIL")); status.println("++++Test Environment++++"); for (String x : env.keySet()) { indentStatus(x + "=" + env.get(x)); @@ -481,7 +530,6 @@ } } appendError("string <" + str + "> not found"); - testExitValue++; return false; } @@ -492,8 +540,13 @@ } } appendError("string <" + stringToMatch + "> not found"); - testExitValue++; return false; } } + /** + * Indicates that the annotated method is a test method. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public @interface Test {} }
--- a/test/tools/launcher/ToolsOpts.java Thu Aug 09 18:02:01 2012 -0700 +++ b/test/tools/launcher/ToolsOpts.java Fri Aug 10 10:15:52 2012 -0700 @@ -160,7 +160,7 @@ for (String arg[] : optionPatterns) { jpos = indexOfJoption(arg); //Build a cmd string for output in results reporting. - String cmdString = javacCmd + JBCP_PREPEND + sTestJar; + String cmdString = javacCmd + " " + JBCP_PREPEND + sTestJar; for (String opt : arg) { cmdString = cmdString.concat(" " + opt); }