7146424: Wildcard expansion for single entry classpath

Reviewed-by: dholmes, darcy, jjh, sherman
diff --git a/jdk/make/common/Program.gmk b/jdk/make/common/Program.gmk
index ff32f4b..2ebcecf 100644
--- a/jdk/make/common/Program.gmk
+++ b/jdk/make/common/Program.gmk
@@ -153,7 +153,6 @@
   ifndef LOCAL_RESOURCE_FILE
 	@$(ECHO) $(OBJDIR)/$(PROGRAM).res >> $@
   endif # LOCAL_RESOURCE_FILE
-	@$(ECHO) setargv.obj >> $@
 	@$(ECHO) Created $@ 
 
   $(ACTUAL_PROGRAM):: $(OBJDIR)/$(PROGRAM)$(EXE_SUFFIX)
diff --git a/jdk/make/java/jli/Makefile b/jdk/make/java/jli/Makefile
index 1bc98d6..4d9de79 100644
--- a/jdk/make/java/jli/Makefile
+++ b/jdk/make/java/jli/Makefile
@@ -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)
diff --git a/jdk/make/java/jli/mapfile-vers b/jdk/make/java/jli/mapfile-vers
index 5ff5edb..08ccd41 100644
--- a/jdk/make/java/jli/mapfile-vers
+++ b/jdk/make/java/jli/mapfile-vers
@@ -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
@@ -35,9 +35,8 @@
 		JLI_ReportErrorMessageSys;
 		JLI_ReportMessage;
 		JLI_ReportExceptionDescription;
-#		JNI_CreateJavaVM;
-#		JNI_GetCreatedJavaVMs;
-#		JNI_GetDefaultJavaVMInitArgs;
+		JLI_GetStdArgs;
+		JLI_GetStdArgc;
 	local:
 		*;
 };
diff --git a/jdk/src/share/bin/java.c b/jdk/src/share/bin/java.c
index 3133258..07af739 100644
--- a/jdk/src/share/bin/java.c
+++ b/jdk/src/share/bin/java.c
@@ -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. */
@@ -1113,8 +1111,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"));
@@ -1158,7 +1157,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;
@@ -1203,7 +1202,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;
diff --git a/jdk/src/share/bin/java.h b/jdk/src/share/bin/java.h
index 5bf3db3..ad1a1ff 100644
--- a/jdk/src/share/bin/java.h
+++ b/jdk/src/share/bin/java.h
@@ -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
diff --git a/jdk/src/share/bin/jli_util.c b/jdk/src/share/bin/jli_util.c
index 2117449..75195f3 100644
--- a/jdk/src/share/bin/jli_util.c
+++ b/jdk/src/share/bin/jli_util.c
@@ -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);
    }
 }
 
diff --git a/jdk/src/share/bin/jli_util.h b/jdk/src/share/bin/jli_util.h
index 7601e93..af1ce47 100644
--- a/jdk/src/share/bin/jli_util.h
+++ b/jdk/src/share/bin/jli_util.h
@@ -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
@@ -27,7 +27,10 @@
 #define _JLI_UTIL_H
 
 #include <stdlib.h>
+#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);
@@ -35,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))
@@ -56,8 +67,10 @@
 #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>
 #define JLI_StrCaseCmp(p1, p2)          strcasecmp((p1), (p2))
 #define JLI_StrNCaseCmp(p1, p2, p3)     strncasecmp((p1), (p2), (p3))
 #define JLI_Snprintf                    snprintf
diff --git a/jdk/src/share/bin/main.c b/jdk/src/share/bin/main.c
index a4d9052..677eb69 100644
--- a/jdk/src/share/bin/main.c
+++ b/jdk/src/share/bin/main.c
@@ -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,
diff --git a/jdk/src/share/bin/wildcard.c b/jdk/src/share/bin/wildcard.c
index 5ad8f76..9ed1b49 100644
--- a/jdk/src/share/bin/wildcard.c
+++ b/jdk/src/share/bin/wildcard.c
@@ -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",
diff --git a/jdk/src/share/classes/sun/launcher/LauncherHelper.java b/jdk/src/share/classes/sun/launcher/LauncherHelper.java
index dc532da..b58e3ca 100644
--- a/jdk/src/share/classes/sun/launcher/LauncherHelper.java
+++ b/jdk/src/share/classes/sun/launcher/LauncherHelper.java
@@ -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,11 +430,11 @@
         if (msgKey != null) {
             ostream.println(getLocalizedMessage(msgKey, args));
         }
-        if (sun.misc.VM.getSavedProperty(diagprop) != null) {
+        if (trace) {
             if (t != null) {
                 t.printStackTrace();
             } else {
-                Thread.currentThread().dumpStack();
+                Thread.dumpStack();
             }
         }
         System.exit(1);
@@ -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 + '}';
+        }
+    }
 }
+
diff --git a/jdk/src/share/classes/sun/launcher/resources/launcher.properties b/jdk/src/share/classes/sun/launcher/resources/launcher.properties
index cd06f83..c9de635 100644
--- a/jdk/src/share/classes/sun/launcher/resources/launcher.properties
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher.properties
@@ -43,7 +43,7 @@
 \                  and ZIP archives to search for class files.\n\
 \    -D<name>=<value>\n\
 \                  set a system property\n\
-\    -verbose[:class|gc|jni]\n\
+\    -verbose:[class|gc|jni]\n\
 \                  enable verbose output\n\
 \    -version      print product version and exit\n\
 \    -version:<value>\n\
@@ -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
diff --git a/jdk/src/solaris/bin/java_md_common.c b/jdk/src/solaris/bin/java_md_common.c
index 9ed63d1..fb446db 100644
--- a/jdk/src/solaris/bin/java_md_common.c
+++ b/jdk/src/solaris/bin/java_md_common.c
@@ -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);
+}
diff --git a/jdk/src/windows/bin/java_md.c b/jdk/src/windows/bin/java_md.c
index a301ff7..e236cab 100644
--- a/jdk/src/windows/bin/java_md.c
+++ b/jdk/src/windows/bin/java_md.c
@@ -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;
+}
diff --git a/jdk/test/tools/launcher/Arrrghs.java b/jdk/test/tools/launcher/Arrrghs.java
index b8dbf56..e93bd3e 100644
--- a/jdk/test/tools/launcher/Arrrghs.java
+++ b/jdk/test/tools/launcher/Arrrghs.java
@@ -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.
@@ -155,96 +162,425 @@
 
 
         // 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");
+        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);
+
+        // 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);
     }
 
     /*
      * 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;
         }
@@ -256,55 +592,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"),
@@ -316,25 +662,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;
         }
@@ -345,48 +695,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);
diff --git a/jdk/test/tools/launcher/TestHelper.java b/jdk/test/tools/launcher/TestHelper.java
index 3e9442c..c799a13 100644
--- a/jdk/test/tools/launcher/TestHelper.java
+++ b/jdk/test/tools/launcher/TestHelper.java
@@ -21,6 +21,14 @@
  * 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;
 import java.io.BufferedReader;
 import java.io.File;
@@ -55,11 +63,14 @@
     static final File TEST_SOURCES_DIR;
 
     static final String JAVAHOME = System.getProperty("java.home");
+    static final String JAVA_BIN;
     static final boolean isSDK = JAVAHOME.endsWith("jre");
     static final String javaCmd;
     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");
@@ -84,8 +95,10 @@
     static final String JAVA_FILE_EXT  = ".java";
     static final String CLASS_FILE_EXT = ".class";
     static final String JAR_FILE_EXT   = ".jar";
+    static final String EXE_FILE_EXT   = ".exe";
     static final String JLDEBUG_KEY     = "_JAVA_LAUNCHER_DEBUG";
     static final String EXPECTED_MARKER = "TRACER_MARKER:About to EXEC";
+    static final String TEST_PREFIX     = "###TestError###: ";
 
     static int testExitValue = 0;
 
@@ -111,6 +124,7 @@
         compiler = ToolProvider.getSystemJavaCompiler();
         File binDir = (isSDK) ? new File((new File(JAVAHOME)).getParentFile(), "bin")
             : new File(JAVAHOME, "bin");
+        JAVA_BIN = binDir.getAbsolutePath();
         File javaCmdFile = (isWindows)
                 ? new File(binDir, "java.exe")
                 : new File(binDir, "java");
@@ -125,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();
@@ -152,6 +175,35 @@
             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++;
+                } catch (Throwable ex) {
+                    System.out.printf("Test %s failed: %s %n", m, ex.getCause());
+                    failed++;
+                }
+            }
+        }
+        System.out.printf("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
@@ -383,35 +435,46 @@
      * of use methods to check the test results.
      */
     static class TestResult {
-        StringBuilder status;
+        PrintWriter status;
+        StringWriter sw;
         int exitValue;
         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) {
-            status = new StringBuilder("Executed command: " + str + "\n");
+            sw = new StringWriter();
+            status = new PrintWriter(sw);
+            status.println("Executed command: " + str + "\n");
             exitValue = rv;
             testOutput = oList;
             this.env = env;
             this.t = t;
+            testStatus = true;
         }
 
-        void appendStatus(String x) {
-            status = status.append("  " + x + "\n");
+        void appendError(String x) {
+            status.println(TEST_PREFIX + x);
+        }
+
+        void indentStatus(String x) {
+            status.println("  " + x);
         }
 
         void checkNegative() {
             if (exitValue == 0) {
-                appendStatus("Error: test must not return 0 exit value");
+                appendError("test must not return 0 exit value");
+                testStatus = false;
                 testExitValue++;
             }
         }
 
         void checkPositive() {
             if (exitValue != 0) {
-                appendStatus("Error: test did not return 0 exit value");
+                testStatus = false;
+                appendError("test did not return 0 exit value");
                 testExitValue++;
             }
         }
@@ -422,7 +485,8 @@
 
         boolean isZeroOutput() {
             if (!testOutput.isEmpty()) {
-                appendStatus("Error: No message from cmd please");
+                testStatus = false;
+                appendError("No message from cmd please");
                 testExitValue++;
                 return false;
             }
@@ -431,7 +495,8 @@
 
         boolean isNotZeroOutput() {
             if (testOutput.isEmpty()) {
-                appendStatus("Error: Missing message");
+                testStatus = false;
+                appendError("Missing message");
                 testExitValue++;
                 return false;
             }
@@ -440,22 +505,26 @@
 
         @Override
         public String toString() {
-            status.append("++++Begin Test Info++++\n");
-            status.append("++++Test Environment++++\n");
+            status.println("++++Begin Test Info++++");
+            status.println("Test Status: " + (testStatus ? "PASS" : "FAIL"));
+            status.println("++++Test Environment++++");
             for (String x : env.keySet()) {
-                status.append(x).append("=").append(env.get(x)).append("\n");
+                indentStatus(x + "=" + env.get(x));
             }
-            status.append("++++Test Output++++\n");
+            status.println("++++Test Output++++");
             for (String x : testOutput) {
-                appendStatus(x);
+                indentStatus(x);
             }
-            status.append("++++Test Stack Trace++++\n");
-            status.append(t.toString());
+            status.println("++++Test Stack Trace++++");
+            status.println(t.toString());
             for (StackTraceElement e : t.getStackTrace()) {
-                status.append(e.toString());
+                indentStatus(e.toString());
             }
-            status.append("++++End of Test Info++++\n");
-            return status.toString();
+            status.println("++++End of Test Info++++");
+            status.flush();
+            String out = sw.toString();
+            status.close();
+            return out;
         }
 
         boolean contains(String str) {
@@ -464,7 +533,7 @@
                     return true;
                 }
             }
-            appendStatus("Error: string <" + str + "> not found");
+            appendError("string <" + str + "> not found");
             testExitValue++;
             return false;
         }
@@ -475,9 +544,15 @@
                     return true;
                 }
             }
-            appendStatus("Error: string <" + stringToMatch + "> not found");
+            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 {}
 }
diff --git a/jdk/test/tools/launcher/ToolsOpts.java b/jdk/test/tools/launcher/ToolsOpts.java
new file mode 100644
index 0000000..4535990
--- /dev/null
+++ b/jdk/test/tools/launcher/ToolsOpts.java
@@ -0,0 +1,217 @@
+/*
+ * 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
+ * @summary Test options patterns for javac,javah,javap and javadoc using
+ * javac as a test launcher. Create a dummy javac and intercept options to check
+ * reception of options as passed through the launcher without having to launch
+ * javac. Only -J and -cp ./* options should be consumed by the launcher.
+ * @run main ToolsOpts
+ * @author ssides
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ToolsOpts extends TestHelper {
+    static final String JBCP_PREPEND = "-J-Xbootclasspath/p:";
+    private static File testJar = null;
+    static String[][] optionPatterns = {
+        {"-J-Xmx128m"},
+        {"-J-version"},
+        {"-J-XshowSettings:vm"},
+        {"-J-Xdiag"},
+        {"-J-showversion"},
+        {"-J-version", "-option"},
+        {"-option"},
+        {"-option:sub"},
+        {"-option:sub-"},
+        {"-option:sub1,sub2"}, // -option:list
+        {"-option:{sub1,sub2,sub3}"}, // -option:{list}
+        {"-option:{{sub1,sub2,sub3}}"},// -option:{{list}}
+        {"-option/c:/export/date/tmp"},
+        {"-option=value"},
+        {"-Dpk1.pk2.pk3"}, // dot in option
+        {"-Dpk1.pk2=value"}, // dot in option followed by =value
+        {"@<filename>"},
+        {"-option", "http://site.com", "http://site.org"},
+        {"-option", "name", "p1:p2.."},
+        {"-All these non-options show launchers pass options as is to tool."},
+        {"-option"},
+        {"-option:sub"},
+        {"-option:sub-"},
+        {"-option", "<path>"},
+        {"-option", "<file>"},
+        {"-option", "<dir>"},
+        {"-option", "http://a/b/c/g;x?y#s"},
+        {"-option", "<html code>"},
+        {"-option", "name1:name2"},
+        {"-option", "3"},
+        {"option1", "-J-version", "option2"},
+        {"option1", "-J-version", "-J-XshowSettings:vm", "option2"},};
+
+    static void init() throws IOException {
+        if (testJar != null) {
+            return;
+        }
+
+        // A tool which simulates com.sun.tools.javac.Main argument processing,
+        // intercepts options passed via the javac launcher.
+        final String mainJava = "Main" + JAVA_FILE_EXT;
+        testJar = new File("test" + JAR_FILE_EXT);
+        List<String> contents = new ArrayList<>();
+        contents.add("package com.sun.tools.javac;");
+        contents.add("public class Main {");
+        contents.add("    public static void main(String... args) {\n");
+        contents.add("       for (String x : args) {\n");
+        contents.add("           if(x.compareTo(\" \")!=0)\n");
+        contents.add("               System.out.println(x);\n");
+        contents.add("       }\n");
+        contents.add("    }\n");
+        contents.add("}\n");
+        createFile(new File(mainJava), contents);
+
+        // compile and jar Main.java into test.jar
+        compile("-d", ".", mainJava);
+            createJar("cvf", testJar.getAbsolutePath(), "com");
+        }
+
+    static void pass(String msg) {
+        System.out.println("pass: " + msg);
+    }
+
+    static void errout(String msg) {
+        System.err.println(msg);
+    }
+
+    // Return position of -J option or -1 is does not contain a -J option.
+    static int indexOfJoption(String[] opts) {
+        for (int i = 0; i < opts.length; i++) {
+            if (opts[i].startsWith("-J")) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /*
+     * Check that J options a) are not passed to tool, and b) do the right thing,
+     * that is, they should be passed to java launcher and work as expected.
+     */
+    static void checkJoptionOutput(TestResult tr, String[] opts) throws IOException {
+        // Check -J-version options are not passed but do what they should.
+        String jopts = "";
+        for (String pat : opts) {
+            jopts = jopts.concat(pat + " ");
+            if (tr.contains("-J")) {
+                throw new RuntimeException(
+                        "failed: output should not contain option " + pat);
+            }
+            if (pat.compareTo("-J-version") == 0 ||
+                    pat.compareTo("-J-showversion") == 0) {
+                if (!tr.contains("java version") &&
+                        !tr.contains("openjdk version")) {
+                    throw new RuntimeException("failed: " + pat +
+                            " should display a version string.");
+                }
+            } else if (pat.compareTo("-J-XshowSettings:VM") == 0) {
+                if (!tr.contains("VM settings")) {
+                    throw new RuntimeException("failed: " + pat +
+                            " should have display VM settings.");
+                }
+            }
+        }
+        pass("Joption check: " + jopts);
+    }
+
+    /*
+     * Feed each option pattern in optionPatterns array to javac launcher with
+     * checking program preempting javac. Check that option received by 'dummy'
+     * javac is the one passed on the command line.
+     */
+    static void runTestOptions() throws IOException {
+        init();
+        TestResult tr = null;
+        String sTestJar = testJar.getAbsolutePath();
+        int jpos = -1;
+        for (String arg[] : optionPatterns) {
+            jpos = indexOfJoption(arg);
+            //Build a cmd string for output in results reporting.
+            String cmdString = javacCmd + " " + JBCP_PREPEND + sTestJar;
+            for (String opt : arg) {
+                cmdString = cmdString.concat(" " + opt);
+            }
+            switch (arg.length) {
+                case 1:
+                    tr = doExec(javacCmd, JBCP_PREPEND + sTestJar,
+                            arg[0]);
+                    break;
+                case 2:
+                    tr = doExec(javacCmd, JBCP_PREPEND + sTestJar,
+                            arg[0], arg[1]);
+                    break;
+                case 3:
+                    tr = doExec(javacCmd, JBCP_PREPEND + sTestJar,
+                            arg[0], arg[1], arg[2]);
+                    break;
+                case 4:
+                    tr = doExec(javacCmd, JBCP_PREPEND + sTestJar,
+                            arg[0], arg[1], arg[2], arg[3]);
+                    break;
+                default:
+                    tr = null;
+                    break;
+            }
+
+            String[] output = tr.testOutput.toArray(new String[tr.testOutput.size()]);
+            //-Joptions should not be passed to tool
+            if (jpos > -1) {
+                checkJoptionOutput(tr, arg);
+                if (tr.contains(arg[jpos])) {
+                    throw new RuntimeException(
+                            "failed! Should not have passed -J option to tool.\n"
+                            + "CMD: " + cmdString);
+                }
+            } else {
+                //check that each non -J option was passed to tool.
+                for (int i = 0; i < arg.length; i++) {
+                    if (output[i].compareTo(arg[i]) != 0) {
+                        throw new RuntimeException(
+                                "failed! CMD: " + cmdString + "\n   case:" +
+                                output[i] + " != " + arg[i]);
+                    } else {
+                        pass("check " + output[i] + " == " + arg[i]);
+                    }
+                }
+            }
+            pass(cmdString);
+        }
+    }
+
+    public static void main(String... args) throws IOException {
+        runTestOptions();
+    }
+}