java.c 67.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * 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.
 *
19 20 21
 * 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.
D
duke 已提交
22 23 24 25
 *
 */

/*
S
sla 已提交
26
 * Gamma (Hotspot internal engineering test) launcher based on 6.0u22 JDK,
D
duke 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 * search "GAMMA" for gamma specific changes.
 *
 * GAMMA: gamma launcher is much simpler than regular java launcher in that
 *        JVM is either statically linked in or it is installed in the
 *        same directory where the launcher exists, so we don't have to
 *        worry about choosing the right JVM based on command line flag, jar
 *        file and/or ergonomics. Intead of removing unused logic from source
 *        they are commented out with #ifndef GAMMA, hopefully it'll be easier
 *        to maintain this file in sync with regular JDK launcher.
 */

/*
 * Shared source for 'java' command line tool.
 *
 * If JAVA_ARGS is defined, then acts as a launcher for applications. For
 * instance, the JDK command line tools such as javac and javadoc (see
 * makefiles for more details) are built with this program.  Any arguments
 * prefixed with '-J' will be passed directly to the 'java' command.
 */

#ifdef GAMMA
#  ifdef JAVA_ARGS
#    error Do NOT define JAVA_ARGS when building gamma launcher
#  endif
#  if !defined(LINK_INTO_AOUT) && !defined(LINK_INTO_LIBJVM)
#    error Either LINK_INTO_AOUT or LINK_INTO_LIBJVM must be defined
#  endif
#endif

/*
 * One job of the launcher is to remove command line options which the
 * vm does not understand and will not process.  These options include
 * options which select which style of vm is run (e.g. -client and
 * -server) as well as options which select the data model to use.
 * Additionally, for tools which invoke an underlying vm "-J-foo"
 * options are turned into "-foo" options to the vm.  This option
 * filtering is handled in a number of places in the launcher, some of
 * it in machine-dependent code.  In this file, the function
S
sla 已提交
65
 * CheckJVMType removes vm style options and TranslateApplicationArgs
D
duke 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
 * removes "-J" prefixes.  On unix platforms, the
 * CreateExecutionEnvironment function from the unix java_md.c file
 * processes and removes -d<n> options.  However, in case
 * CreateExecutionEnvironment does not need to exec because
 * LD_LIBRARY_PATH is set acceptably and the data model does not need
 * to be changed, ParseArguments will screen out the redundant -d<n>
 * options and prevent them from being passed to the vm; this is done
 * by using the machine-dependent call
 * RemovableMachineDependentOption.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <jni.h>
S
sla 已提交
82
#include <jvm.h>
D
duke 已提交
83 84 85 86
#include "java.h"
#ifndef GAMMA
#include "manifest_info.h"
#include "version_comp.h"
S
sla 已提交
87
#include "splashscreen.h"
D
duke 已提交
88
#endif
S
sla 已提交
89
#include "wildcard.h"
D
duke 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

#ifndef FULL_VERSION
#define FULL_VERSION JDK_MAJOR_VERSION "." JDK_MINOR_VERSION
#endif

/*
 * The following environment variable is used to influence the behavior
 * of the jre exec'd through the SelectVersion routine.  The command line
 * options which specify the version are not passed to the exec'd version,
 * because that jre may be an older version which wouldn't recognize them.
 * This environment variable is known to this (and later) version and serves
 * to suppress the version selection code.  This is not only for efficiency,
 * but also for correctness, since any command line options have been
 * removed which would cause any value found in the manifest to be used.
 * This would be incorrect because the command line options are defined
 * to take precedence.
 *
 * The value associated with this environment variable is the MainClass
 * name from within the executable jar file (if any). This is strictly a
 * performance enhancement to avoid re-reading the jar file manifest.
 *
 * A NOTE TO DEVELOPERS: For performance reasons it is important that
 * the program image remain relatively small until after SelectVersion
 * CreateExecutionEnvironment have finished their possibly recursive
 * processing. Watch everything, but resist all temptations to use Java
 * interfaces.
 */
#define ENV_ENTRY "_JAVA_VERSION_SET"

S
sla 已提交
119 120 121 122 123
#ifndef GAMMA
#define SPLASH_FILE_ENV_ENTRY "_JAVA_SPLASH_FILE"
#define SPLASH_JAR_ENV_ENTRY "_JAVA_SPLASH_JAR"
#endif

D
duke 已提交
124 125 126 127 128
static jboolean printVersion = JNI_FALSE; /* print and exit */
static jboolean showVersion = JNI_FALSE;  /* print but continue */
static char *progname;
jboolean _launcher_debug = JNI_FALSE;

S
sla 已提交
129 130 131 132 133 134 135 136 137 138 139
#ifndef GAMMA
/*
 * Entries for splash screen environment variables.
 * putenv is performed in SelectVersion. We need
 * them in memory until UnsetEnv, so they are made static
 * global instead of auto local.
 */
static char* splash_file_entry = NULL;
static char* splash_jar_entry = NULL;
#endif

D
duke 已提交
140 141 142 143 144 145 146 147 148
/*
 * List of VM options to be specified when the VM is created.
 */
static JavaVMOption *options;
static int numOptions, maxOptions;

/*
 * Prototypes for functions internal to launcher.
 */
S
sla 已提交
149
static void SetClassPath(const char *s);
D
duke 已提交
150 151
static void SelectVersion(int argc, char **argv, char **main_class);
static jboolean ParseArguments(int *pargc, char ***pargv, char **pjarfile,
S
sla 已提交
152
                               char **pclassname, int *pret, const char *jvmpath);
D
duke 已提交
153 154 155 156 157 158 159 160 161 162
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 LoadClass(JNIEnv *env, char *name);
static jstring GetMainClassName(JNIEnv *env, char *jarname);
static void SetJavaCommandLineProp(char* classname, char* jarfile, int argc, char** argv);
static void SetJavaLauncherProp(void);

#ifdef JAVA_ARGS
S
sla 已提交
163
static void TranslateApplicationArgs(int *pargc, char ***pargv);
D
duke 已提交
164 165 166 167 168
static jboolean AddApplicationOptions(void);
#endif

static void PrintJavaVersion(JNIEnv *env);
static void PrintUsage(void);
S
sla 已提交
169
static jint PrintXUsage(const char *jvmpath);
D
duke 已提交
170 171 172

static void SetPaths(int argc, char **argv);

S
sla 已提交
173 174
#ifndef GAMMA

D
duke 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/* Maximum supported entries from jvm.cfg. */
#define INIT_MAX_KNOWN_VMS      10
/* Values for vmdesc.flag */
#define VM_UNKNOWN              -1
#define VM_KNOWN                 0
#define VM_ALIASED_TO            1
#define VM_WARN                  2
#define VM_ERROR                 3
#define VM_IF_SERVER_CLASS       4
#define VM_IGNORE                5
struct vmdesc {
    char *name;
    int flag;
    char *alias;
    char *server_class;
};
static struct vmdesc *knownVMs = NULL;
static int knownVMsCount = 0;
static int knownVMsLimit = 0;

static void GrowKnownVMs();
static int  KnownVMIndex(const char* name);
static void FreeKnownVMs();
S
sla 已提交
198 199 200
static void ShowSplashScreen();

#endif /* ifndef GAMMA */
D
duke 已提交
201 202 203 204 205 206

jboolean ServerClassMachine();

/* flag which if set suppresses error messages from the launcher */
static int noExitErrorMessage = 0;

S
sla 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
/*
 * 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 */

int JNICALL JavaMain(void * args); /* entry point                  */

struct JavaMainArgs {
  int     argc;
  char ** argv;
  char *  jarfile;
  char *  classname;
  InvocationFunctions ifn;
};

D
duke 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
/*
 * Entry point.
 */
int
main(int argc, char ** argv)
{
    char *jarfile = 0;
    char *classname = 0;
    char *s = 0;
    char *main_class = NULL;
    int ret;
    InvocationFunctions ifn;
    jlong start, end;
    char jrepath[MAXPATHLEN], jvmpath[MAXPATHLEN];
    char ** original_argv = argv;

    if (getenv("_JAVA_LAUNCHER_DEBUG") != 0) {
        _launcher_debug = JNI_TRUE;
        printf("----_JAVA_LAUNCHER_DEBUG----\n");
    }

#ifndef GAMMA
    /*
     * Make sure the specified version of the JRE is running.
     *
     * There are three things to note about the SelectVersion() routine:
     *  1) If the version running isn't correct, this routine doesn't
     *     return (either the correct version has been exec'd or an error
     *     was issued).
     *  2) Argc and Argv in this scope are *not* altered by this routine.
     *     It is the responsibility of subsequent code to ignore the
     *     arguments handled by this routine.
     *  3) As a side-effect, the variable "main_class" is guaranteed to
     *     be set (if it should ever be set).  This isn't exactly the
     *     poster child for structured programming, but it is a small
     *     price to pay for not processing a jar file operand twice.
     *     (Note: This side effect has been disabled.  See comment on
     *     bugid 5030265 below.)
     */
    SelectVersion(argc, argv, &main_class);
#endif /* ifndef GAMMA */

    /* copy original argv */
    {
      int i;
S
sla 已提交
268
      original_argv = (char**)JLI_MemAlloc(sizeof(char*)*(argc+1));
D
duke 已提交
269 270 271 272 273 274 275 276
      for(i = 0; i < argc+1; i++)
        original_argv[i] = argv[i];
    }

    CreateExecutionEnvironment(&argc, &argv,
                               jrepath, sizeof(jrepath),
                               jvmpath, sizeof(jvmpath),
                               original_argv);
S
sla 已提交
277

D
duke 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    ifn.CreateJavaVM = 0;
    ifn.GetDefaultJavaVMInitArgs = 0;

    if (_launcher_debug)
      start = CounterGet();
    if (!LoadJavaVM(jvmpath, &ifn)) {
      exit(6);
    }
    if (_launcher_debug) {
      end   = CounterGet();
      printf("%ld micro seconds to LoadJavaVM\n",
             (long)(jint)Counter2Micros(end-start));
    }

#ifdef JAVA_ARGS  /* javac, jar and friends. */
    progname = "java";
#else             /* java, oldjava, javaw and friends */
#ifdef PROGNAME
    progname = PROGNAME;
#else
    progname = *argv;
    if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
        progname = s + 1;
    }
#endif /* PROGNAME */
#endif /* JAVA_ARGS */
    ++argv;
    --argc;

#ifdef JAVA_ARGS
    /* Preprocess wrapper arguments */
S
sla 已提交
309
    TranslateApplicationArgs(&argc, &argv);
D
duke 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    if (!AddApplicationOptions()) {
        exit(1);
    }
#endif

    /* Set default CLASSPATH */
    if ((s = getenv("CLASSPATH")) == 0) {
        s = ".";
    }
#ifndef JAVA_ARGS
    SetClassPath(s);
#endif

    /*
     *  Parse command line options; if the return value of
     *  ParseArguments is false, the program should exit.
     */
S
sla 已提交
327
    if (!ParseArguments(&argc, &argv, &jarfile, &classname, &ret, jvmpath)) {
D
duke 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340
      exit(ret);
    }

    /* Override class path if -jar flag was specified */
    if (jarfile != 0) {
        SetClassPath(jarfile);
    }

    /* set the -Dsun.java.command pseudo property */
    SetJavaCommandLineProp(classname, jarfile, argc, argv);

    /* Set the -Dsun.java.launcher pseudo property */
    SetJavaLauncherProp();
S
sla 已提交
341 342 343 344 345 346 347

    /* set the -Dsun.java.launcher.* platform properties */
    SetJavaLauncherPlatformProps();

#ifndef GAMMA
    /* Show the splash screen if needed */
    ShowSplashScreen();
D
duke 已提交
348 349 350 351 352 353 354
#endif

    /*
     * Done with all command line processing and potential re-execs so
     * clean up the environment.
     */
    (void)UnsetEnv(ENV_ENTRY);
S
sla 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
#ifndef GAMMA
    (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
    (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);

    JLI_MemFree(splash_jar_entry);
    JLI_MemFree(splash_file_entry);
#endif

    /*
     * If user doesn't specify stack size, check if VM has a preference.
     * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
     * return its default stack size through the init args structure.
     */
    if (threadStackSize == 0) {
      struct JDK1_1InitArgs args1_1;
      memset((void*)&args1_1, 0, sizeof(args1_1));
      args1_1.version = JNI_VERSION_1_1;
      ifn.GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
      if (args1_1.javaStackSize > 0) {
         threadStackSize = args1_1.javaStackSize;
      }
    }

    { /* Create a new thread to create JVM and invoke main method */
      struct JavaMainArgs args;

      args.argc = argc;
      args.argv = argv;
      args.jarfile = jarfile;
      args.classname = classname;
      args.ifn = ifn;

      return ContinueInNewThread(JavaMain, threadStackSize, (void*)&args);
    }
}

int JNICALL
JavaMain(void * _args)
{
    struct JavaMainArgs *args = (struct JavaMainArgs *)_args;
    int argc = args->argc;
    char **argv = args->argv;
    char *jarfile = args->jarfile;
    char *classname = args->classname;
    InvocationFunctions ifn = args->ifn;

    JavaVM *vm = 0;
    JNIEnv *env = 0;
    jstring mainClassName;
    jclass mainClass;
    jmethodID mainID;
    jobjectArray mainArgs;
    int ret = 0;
    jlong start, end;

    /*
     * Error message to print or display; by default the message will
     * only be displayed in a window.
     */
    char * message = "Fatal exception occurred.  Program will exit.";
    jboolean messageDest = JNI_FALSE;
D
duke 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

    /* Initialize the virtual machine */

    if (_launcher_debug)
        start = CounterGet();
    if (!InitializeJVM(&vm, &env, &ifn)) {
        ReportErrorMessage("Could not create the Java virtual machine.",
                           JNI_TRUE);
        exit(1);
    }

    if (printVersion || showVersion) {
        PrintJavaVersion(env);
        if ((*env)->ExceptionOccurred(env)) {
            ReportExceptionDescription(env);
            goto leave;
        }
        if (printVersion) {
            ret = 0;
            message = NULL;
            goto leave;
        }
        if (showVersion) {
            fprintf(stderr, "\n");
        }
    }

    /* If the user specified neither a class name nor a JAR file */
    if (jarfile == 0 && classname == 0) {
        PrintUsage();
        message = NULL;
        goto leave;
    }

#ifndef GAMMA
    FreeKnownVMs();  /* after last possible PrintUsage() */
#endif

    if (_launcher_debug) {
        end   = CounterGet();
        printf("%ld micro seconds to InitializeJVM\n",
               (long)(jint)Counter2Micros(end-start));
    }

    /* At this stage, argc/argv have the applications' arguments */
    if (_launcher_debug) {
        int i = 0;
        printf("Main-Class is '%s'\n", classname ? classname : "");
        printf("Apps' argc is %d\n", argc);
        for (; i < argc; i++) {
            printf("    argv[%2d] = '%s'\n", i, argv[i]);
        }
    }

    ret = 1;

    /*
     * Get the application's main class.
     *
     * See bugid 5030265.  The Main-Class name has already been parsed
     * from the manifest, but not parsed properly for UTF-8 support.
     * Hence the code here ignores the value previously extracted and
     * uses the pre-existing code to reextract the value.  This is
     * possibly an end of release cycle expedient.  However, it has
     * also been discovered that passing some character sets through
     * the environment has "strange" behavior on some variants of
     * Windows.  Hence, maybe the manifest parsing code local to the
     * launcher should never be enhanced.
     *
     * Hence, future work should either:
     *     1)   Correct the local parsing code and verify that the
     *          Main-Class attribute gets properly passed through
     *          all environments,
     *     2)   Remove the vestages of maintaining main_class through
     *          the environment (and remove these comments).
     */
    if (jarfile != 0) {
        mainClassName = GetMainClassName(env, jarfile);
        if ((*env)->ExceptionOccurred(env)) {
            ReportExceptionDescription(env);
            goto leave;
        }
        if (mainClassName == NULL) {
          const char * format = "Failed to load Main-Class manifest "
                                "attribute from\n%s";
S
sla 已提交
501
          message = (char*)JLI_MemAlloc((strlen(format) + strlen(jarfile)) *
D
duke 已提交
502 503 504 505 506 507 508 509 510 511 512
                                    sizeof(char));
          sprintf(message, format, jarfile);
          messageDest = JNI_TRUE;
          goto leave;
        }
        classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0);
        if (classname == NULL) {
            ReportExceptionDescription(env);
            goto leave;
        }
        mainClass = LoadClass(env, classname);
S
sla 已提交
513 514
        if(mainClass == NULL) { /* exception occured */
            const char * format = "Could not find the main class: %s. Program will exit.";
D
duke 已提交
515
            ReportExceptionDescription(env);
S
sla 已提交
516 517 518 519
            message = (char *)JLI_MemAlloc((strlen(format) +
                                            strlen(classname)) * sizeof(char) );
            messageDest = JNI_TRUE;
            sprintf(message, format, classname);
D
duke 已提交
520 521 522 523 524 525 526
            goto leave;
        }
        (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
    } else {
      mainClassName = NewPlatformString(env, classname);
      if (mainClassName == NULL) {
        const char * format = "Failed to load Main Class: %s";
S
sla 已提交
527
        message = (char *)JLI_MemAlloc((strlen(format) + strlen(classname)) *
D
duke 已提交
528 529 530 531 532 533 534 535 536 537 538
                                   sizeof(char) );
        sprintf(message, format, classname);
        messageDest = JNI_TRUE;
        goto leave;
      }
      classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0);
      if (classname == NULL) {
        ReportExceptionDescription(env);
        goto leave;
      }
      mainClass = LoadClass(env, classname);
S
sla 已提交
539 540
      if(mainClass == NULL) { /* exception occured */
        const char * format = "Could not find the main class: %s.  Program will exit.";
D
duke 已提交
541
        ReportExceptionDescription(env);
S
sla 已提交
542 543 544 545
        message = (char *)JLI_MemAlloc((strlen(format) +
                                        strlen(classname)) * sizeof(char) );
        messageDest = JNI_TRUE;
        sprintf(message, format, classname);
D
duke 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        goto leave;
      }
      (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
    }

    /* Get the application's main method */
    mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                                       "([Ljava/lang/String;)V");
    if (mainID == NULL) {
        if ((*env)->ExceptionOccurred(env)) {
            ReportExceptionDescription(env);
        } else {
          message = "No main method found in specified class.";
          messageDest = JNI_TRUE;
        }
        goto leave;
    }

    {    /* Make sure the main method is public */
        jint mods;
        jmethodID mid;
        jobject obj = (*env)->ToReflectedMethod(env, mainClass,
                                                mainID, JNI_TRUE);

        if( obj == NULL) { /* exception occurred */
            ReportExceptionDescription(env);
            goto leave;
        }

        mid =
          (*env)->GetMethodID(env,
                              (*env)->GetObjectClass(env, obj),
                              "getModifiers", "()I");
        if ((*env)->ExceptionOccurred(env)) {
            ReportExceptionDescription(env);
            goto leave;
        }

        mods = (*env)->CallIntMethod(env, obj, mid);
        if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
            message = "Main method not public.";
            messageDest = JNI_TRUE;
            goto leave;
        }
    }

    /* Build argument array */
    mainArgs = NewPlatformStringArray(env, argv, argc);
    if (mainArgs == NULL) {
        ReportExceptionDescription(env);
        goto leave;
    }

    /* Invoke main method. */
    (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

    /*
     * The launcher's exit code (in the absence of calls to
     * System.exit) will be non-zero if main threw an exception.
     */
    ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;

    /*
     * Detach the main thread so that it appears to have ended when
     * the application's main method exits.  This will invoke the
     * uncaught exception handler machinery if main threw an
     * exception.  An uncaught exception handler cannot change the
     * launcher's return code except by calling System.exit.
     */
    if ((*vm)->DetachCurrentThread(vm) != 0) {
        message = "Could not detach main thread.";
        messageDest = JNI_TRUE;
        ret = 1;
        goto leave;
    }

    message = NULL;

 leave:
    /*
     * Wait for all non-daemon threads to end, then destroy the VM.
     * This will actually create a trivial new Java waiter thread
     * named "DestroyJavaVM", but this will be seen as a different
     * thread from the one that executed main, even though they are
     * the same C thread.  This allows mainThread.join() and
     * mainThread.isAlive() to work as expected.
     */
    (*vm)->DestroyJavaVM(vm);

    if(message != NULL && !noExitErrorMessage)
      ReportErrorMessage(message, messageDest);
    return ret;
}

#ifndef GAMMA
/*
 * Checks the command line options to find which JVM type was
 * specified.  If no command line option was given for the JVM type,
 * the default type is used.  The environment variable
 * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
 * checked as ways of specifying which JVM type to invoke.
 */
char *
CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
    int i, argi;
    int argc;
    char **newArgv;
    int newArgvIdx = 0;
    int isVMType;
    int jvmidx = -1;
    char *jvmtype = getenv("JDK_ALTERNATE_VM");

    argc = *pargc;

    /* To make things simpler we always copy the argv array */
S
sla 已提交
661
    newArgv = JLI_MemAlloc((argc + 1) * sizeof(char *));
D
duke 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

    /* The program name is always present */
    newArgv[newArgvIdx++] = (*argv)[0];

    for (argi = 1; argi < argc; argi++) {
        char *arg = (*argv)[argi];
        isVMType = 0;

#ifdef JAVA_ARGS
        if (arg[0] != '-') {
            newArgv[newArgvIdx++] = arg;
            continue;
        }
#else
        if (strcmp(arg, "-classpath") == 0 ||
            strcmp(arg, "-cp") == 0) {
            newArgv[newArgvIdx++] = arg;
            argi++;
            if (argi < argc) {
                newArgv[newArgvIdx++] = (*argv)[argi];
            }
            continue;
        }
        if (arg[0] != '-') break;
#endif

        /* Did the user pass an explicit VM type? */
        i = KnownVMIndex(arg);
        if (i >= 0) {
            jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
            isVMType = 1;
            *pargc = *pargc - 1;
        }

        /* Did the user specify an "alternate" VM? */
        else if (strncmp(arg, "-XXaltjvm=", 10) == 0 || strncmp(arg, "-J-XXaltjvm=", 12) == 0) {
            isVMType = 1;
            jvmtype = arg+((arg[1]=='X')? 10 : 12);
            jvmidx = -1;
        }

        if (!isVMType) {
            newArgv[newArgvIdx++] = arg;
        }
    }

    /*
     * Finish copying the arguments if we aborted the above loop.
     * NOTE that if we aborted via "break" then we did NOT copy the
     * last argument above, and in addition argi will be less than
     * argc.
     */
    while (argi < argc) {
        newArgv[newArgvIdx++] = (*argv)[argi];
        argi++;
    }

    /* argv is null-terminated */
    newArgv[newArgvIdx] = 0;

    /* Copy back argv */
    *argv = newArgv;
    *pargc = newArgvIdx;

    /* use the default VM type if not specified (no alias processing) */
    if (jvmtype == NULL) {
      char* result = knownVMs[0].name+1;
      /* Use a different VM type if we are on a server class machine? */
      if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
          (ServerClassMachine() == JNI_TRUE)) {
        result = knownVMs[0].server_class+1;
      }
      if (_launcher_debug) {
        printf("Default VM: %s\n", result);
      }
      return result;
    }

    /* if using an alternate VM, no alias processing */
    if (jvmidx < 0)
      return jvmtype;

    /* Resolve aliases first */
    {
      int loopCount = 0;
      while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
        int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);

        if (loopCount > knownVMsCount) {
          if (!speculative) {
            ReportErrorMessage("Error: Corrupt jvm.cfg file; cycle in alias list.",
                               JNI_TRUE);
            exit(1);
          } else {
            return "ERROR";
            /* break; */
          }
        }

        if (nextIdx < 0) {
          if (!speculative) {
            ReportErrorMessage2("Error: Unable to resolve VM alias %s",
                                knownVMs[jvmidx].alias, JNI_TRUE);
            exit(1);
          } else {
            return "ERROR";
          }
        }
        jvmidx = nextIdx;
        jvmtype = knownVMs[jvmidx].name+1;
        loopCount++;
      }
    }

    switch (knownVMs[jvmidx].flag) {
    case VM_WARN:
        if (!speculative) {
            fprintf(stderr, "Warning: %s VM not supported; %s VM will be used\n",
                    jvmtype, knownVMs[0].name + 1);
        }
        /* fall through */
    case VM_IGNORE:
        jvmtype = knownVMs[jvmidx=0].name + 1;
        /* fall through */
    case VM_KNOWN:
        break;
    case VM_ERROR:
        if (!speculative) {
            ReportErrorMessage2("Error: %s VM not supported", jvmtype, JNI_TRUE);
            exit(1);
        } else {
            return "ERROR";
        }
    }

    return jvmtype;
}
#endif /* ifndef GAMMA */

S
sla 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
# define KB (1024UL)
# define MB (1024UL * KB)
# define GB (1024UL * MB)

/* copied from HotSpot function "atomll()" */
static int
parse_stack_size(const char *s, jlong *result) {
  jlong n = 0;
  int args_read = sscanf(s, jlong_format_specifier(), &n);
  if (args_read != 1) {
    return 0;
  }
  while (*s != '\0' && *s >= '0' && *s <= '9') {
    s++;
  }
  // 4705540: illegal if more characters are found after the first non-digit
  if (strlen(s) > 1) {
    return 0;
  }
  switch (*s) {
    case 'T': case 't':
      *result = n * GB * KB;
      return 1;
    case 'G': case 'g':
      *result = n * GB;
      return 1;
    case 'M': case 'm':
      *result = n * MB;
      return 1;
    case 'K': case 'k':
      *result = n * KB;
      return 1;
    case '\0':
      *result = n;
      return 1;
    default:
      /* Create JVM with default stack and let VM handle malformed -Xss string*/
      return 0;
  }
}

D
duke 已提交
842 843 844
/*
 * Adds a new VM option with the given given name and value.
 */
S
sla 已提交
845
void
D
duke 已提交
846 847 848 849 850 851 852 853 854
AddOption(char *str, void *info)
{
    /*
     * Expand options array if needed to accommodate at least one more
     * VM option.
     */
    if (numOptions >= maxOptions) {
        if (options == 0) {
            maxOptions = 4;
S
sla 已提交
855
            options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
D
duke 已提交
856 857 858
        } else {
            JavaVMOption *tmp;
            maxOptions *= 2;
S
sla 已提交
859
            tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
D
duke 已提交
860
            memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
S
sla 已提交
861
            JLI_MemFree(options);
D
duke 已提交
862 863 864 865 866
            options = tmp;
        }
    }
    options[numOptions].optionString = str;
    options[numOptions++].extraInfo = info;
S
sla 已提交
867 868 869 870 871 872 873

    if (strncmp(str, "-Xss", 4) == 0) {
      jlong tmp;
      if (parse_stack_size(str + 4, &tmp)) {
        threadStackSize = tmp;
      }
    }
D
duke 已提交
874 875 876
}

static void
S
sla 已提交
877
SetClassPath(const char *s)
D
duke 已提交
878
{
S
sla 已提交
879 880 881
    char *def;
    s = JLI_WildcardExpandClasspath(s);
    def = JLI_MemAlloc(strlen(s) + 40);
D
duke 已提交
882 883 884 885 886 887 888 889 890 891
    sprintf(def, "-Djava.class.path=%s", s);
    AddOption(def, NULL);
}

#ifndef GAMMA
/*
 * The SelectVersion() routine ensures that an appropriate version of
 * the JRE is running.  The specification for the appropriate version
 * is obtained from either the manifest of a jar file (preferred) or
 * from command line options.
S
sla 已提交
892 893
 * The routine also parses splash screen command line options and
 * passes on their values in private environment variables.
D
duke 已提交
894 895 896 897 898 899 900 901 902 903 904
 */
static void
SelectVersion(int argc, char **argv, char **main_class)
{
    char    *arg;
    char    **new_argv;
    char    **new_argp;
    char    *operand;
    char    *version = NULL;
    char    *jre = NULL;
    int     jarflag = 0;
S
sla 已提交
905
    int     headlessflag = 0;
D
duke 已提交
906 907 908
    int     restrict_search = -1;               /* -1 implies not known */
    manifest_info info;
    char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
S
sla 已提交
909 910
    char    *splash_file_name = NULL;
    char    *splash_jar_name = NULL;
D
duke 已提交
911 912 913 914 915 916 917 918 919 920
    char    *env_in;
    int     res;

    /*
     * If the version has already been selected, set *main_class
     * with the value passed through the environment (if any) and
     * simply return.
     */
    if ((env_in = getenv(ENV_ENTRY)) != NULL) {
        if (*env_in != '\0')
S
sla 已提交
921
            *main_class = JLI_StringDup(env_in);
D
duke 已提交
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
        return;
    }

    /*
     * Scan through the arguments for options relevant to multiple JRE
     * support.  For reference, the command line syntax is defined as:
     *
     * SYNOPSIS
     *      java [options] class [argument...]
     *
     *      java [options] -jar file.jar [argument...]
     *
     * As the scan is performed, make a copy of the argument list with
     * the version specification options (new to 1.5) removed, so that
     * a version less than 1.5 can be exec'd.
S
sla 已提交
937 938 939 940 941
     *
     * Note that due to the syntax of the native Windows interface
     * CreateProcess(), processing similar to the following exists in
     * the Windows platform specific routine ExecJRE (in java_md.c).
     * Changes here should be reproduced there.
D
duke 已提交
942
     */
S
sla 已提交
943
    new_argv = JLI_MemAlloc((argc + 1) * sizeof(char*));
D
duke 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    new_argv[0] = argv[0];
    new_argp = &new_argv[1];
    argc--;
    argv++;
    while ((arg = *argv) != 0 && *arg == '-') {
        if (strncmp(arg, "-version:", 9) == 0) {
            version = arg + 9;
        } else if (strcmp(arg, "-jre-restrict-search") == 0) {
            restrict_search = 1;
        } else if (strcmp(arg, "-no-jre-restrict-search") == 0) {
            restrict_search = 0;
        } else {
            if (strcmp(arg, "-jar") == 0)
                jarflag = 1;
            /* deal with "unfortunate" classpath syntax */
            if ((strcmp(arg, "-classpath") == 0 || strcmp(arg, "-cp") == 0) &&
              (argc >= 2)) {
                *new_argp++ = arg;
                argc--;
                argv++;
                arg = *argv;
            }
S
sla 已提交
966 967 968 969 970 971 972 973 974 975 976 977

            /*
             * Checking for headless toolkit option in the some way as AWT does:
             * "true" means true and any other value means false
             */
            if (strcmp(arg, "-Djava.awt.headless=true") == 0) {
                headlessflag = 1;
            } else if (strncmp(arg, "-Djava.awt.headless=", 20) == 0) {
                headlessflag = 0;
            } else if (strncmp(arg, "-splash:", 8) == 0) {
                splash_file_name = arg+8;
            }
D
duke 已提交
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
            *new_argp++ = arg;
        }
        argc--;
        argv++;
    }
    if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
        operand = NULL;
    } else {
        argc--;
        *new_argp++ = operand = *argv++;
    }
    while (argc-- > 0)  /* Copy over [argument...] */
        *new_argp++ = *argv++;
    *new_argp = NULL;

    /*
     * If there is a jar file, read the manifest. If the jarfile can't be
     * read, the manifest can't be read from the jar file, or the manifest
     * is corrupt, issue the appropriate error messages and exit.
     *
     * Even if there isn't a jar file, construct a manifest_info structure
     * containing the command line information.  It's a convenient way to carry
     * this data around.
     */
    if (jarflag && operand) {
S
sla 已提交
1003
        if ((res = JLI_ParseManifest(operand, &info)) != 0) {
D
duke 已提交
1004 1005 1006 1007 1008 1009 1010 1011
            if (res == -1)
                ReportErrorMessage2("Unable to access jarfile %s",
                  operand, JNI_TRUE);
            else
                ReportErrorMessage2("Invalid or corrupt jarfile %s",
                  operand, JNI_TRUE);
            exit(1);
        }
S
sla 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

        /*
         * Command line splash screen option should have precedence
         * over the manifest, so the manifest data is used only if
         * splash_file_name has not been initialized above during command
         * line parsing
         */
        if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
            splash_file_name = info.splashscreen_image_file_name;
            splash_jar_name = operand;
        }
D
duke 已提交
1023 1024 1025 1026 1027 1028 1029
    } else {
        info.manifest_version = NULL;
        info.main_class = NULL;
        info.jre_version = NULL;
        info.jre_restrict_search = 0;
    }

S
sla 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    /*
     * Passing on splash screen info in environment variables
     */
    if (splash_file_name && !headlessflag) {
        char* splash_file_entry = JLI_MemAlloc(strlen(SPLASH_FILE_ENV_ENTRY "=")+strlen(splash_file_name)+1);
        strcpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
        strcat(splash_file_entry, splash_file_name);
        putenv(splash_file_entry);
    }
    if (splash_jar_name && !headlessflag) {
        char* splash_jar_entry = JLI_MemAlloc(strlen(SPLASH_JAR_ENV_ENTRY "=")+strlen(splash_jar_name)+1);
        strcpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
        strcat(splash_jar_entry, splash_jar_name);
        putenv(splash_jar_entry);
    }

D
duke 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    /*
     * The JRE-Version and JRE-Restrict-Search values (if any) from the
     * manifest are overwritten by any specified on the command line.
     */
    if (version != NULL)
        info.jre_version = version;
    if (restrict_search != -1)
        info.jre_restrict_search = restrict_search;

    /*
     * "Valid" returns (other than unrecoverable errors) follow.  Set
     * main_class as a side-effect of this routine.
     */
    if (info.main_class != NULL)
S
sla 已提交
1060
        *main_class = JLI_StringDup(info.main_class);
D
duke 已提交
1061 1062 1063 1064 1065 1066

    /*
     * If no version selection information is found either on the command
     * line or in the manifest, simply return.
     */
    if (info.jre_version == NULL) {
S
sla 已提交
1067 1068
        JLI_FreeManifest();
        JLI_MemFree(new_argv);
D
duke 已提交
1069 1070 1071 1072 1073 1074
        return;
    }

    /*
     * Check for correct syntax of the version specification (JSR 56).
     */
S
sla 已提交
1075
    if (!JLI_ValidVersionString(info.jre_version)) {
D
duke 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        ReportErrorMessage2("Syntax error in version specification \"%s\"",
          info.jre_version, JNI_TRUE);
        exit(1);
    }

    /*
     * Find the appropriate JVM on the system. Just to be as forgiving as
     * possible, if the standard algorithms don't locate an appropriate
     * jre, check to see if the one running will satisfy the requirements.
     * This can happen on systems which haven't been set-up for multiple
     * JRE support.
     */
    jre = LocateJRE(&info);
    if (_launcher_debug)
        printf("JRE-Version = %s, JRE-Restrict-Search = %s Selected = %s\n",
          (info.jre_version?info.jre_version:"null"),
          (info.jre_restrict_search?"true":"false"), (jre?jre:"null"));
    if (jre == NULL) {
S
sla 已提交
1094 1095 1096
        if (JLI_AcceptableRelease(FULL_VERSION, info.jre_version)) {
            JLI_FreeManifest();
            JLI_MemFree(new_argv);
D
duke 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            return;
        } else {
            ReportErrorMessage2(
              "Unable to locate JRE meeting specification \"%s\"",
              info.jre_version, JNI_TRUE);
            exit(1);
        }
    }

    /*
     * If I'm not the chosen one, exec the chosen one.  Returning from
     * ExecJRE indicates that I am indeed the chosen one.
     *
     * The private environment variable _JAVA_VERSION_SET is used to
     * prevent the chosen one from re-reading the manifest file and
     * using the values found within to override the (potential) command
     * line flags stripped from argv (because the target may not
     * understand them).  Passing the MainClass value is an optimization
     * to avoid locating, expanding and parsing the manifest extra
     * times.
     */
S
sla 已提交
1118 1119 1120 1121 1122 1123 1124 1125
    if (info.main_class != NULL) {
        if (strlen(info.main_class) <= MAXNAMELEN) {
            (void)strcat(env_entry, info.main_class);
        } else {
            ReportErrorMessage("Error: main-class: attribute exceeds system limits\n", JNI_TRUE);
            exit(1);
        }
    }
D
duke 已提交
1126 1127
    (void)putenv(env_entry);
    ExecJRE(jre, new_argv);
S
sla 已提交
1128 1129
    JLI_FreeManifest();
    JLI_MemFree(new_argv);
D
duke 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    return;
}
#endif /* ifndef GAMMA */

/*
 * Parses command line arguments.  Returns JNI_FALSE if launcher
 * should exit without starting vm (e.g. certain version and usage
 * options); returns JNI_TRUE if vm needs to be started to process
 * given options.  *pret (the launcher process return value) is set to
 * 0 for a normal exit.
 */
static jboolean
ParseArguments(int *pargc, char ***pargv, char **pjarfile,
S
sla 已提交
1143
                       char **pclassname, int *pret, const char *jvmpath)
D
duke 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
{
    int argc = *pargc;
    char **argv = *pargv;
    jboolean jarflag = JNI_FALSE;
    char *arg;

    *pret = 1;
    while ((arg = *argv) != 0 && *arg == '-') {
        argv++; --argc;
        if (strcmp(arg, "-classpath") == 0 || strcmp(arg, "-cp") == 0) {
            if (argc < 1) {
                ReportErrorMessage2("%s requires class path specification",
                                    arg, JNI_TRUE);
                PrintUsage();
                return JNI_FALSE;
            }
            SetClassPath(*argv);
            argv++; --argc;
        } else if (strcmp(arg, "-jar") == 0) {
            jarflag = JNI_TRUE;
        } else if (strcmp(arg, "-help") == 0 ||
                   strcmp(arg, "-h") == 0 ||
                   strcmp(arg, "-?") == 0) {
            PrintUsage();
            *pret = 0;
            return JNI_FALSE;
        } else if (strcmp(arg, "-version") == 0) {
            printVersion = JNI_TRUE;
            return JNI_TRUE;
        } else if (strcmp(arg, "-showversion") == 0) {
            showVersion = JNI_TRUE;
        } else if (strcmp(arg, "-X") == 0) {
S
sla 已提交
1176
            *pret = PrintXUsage(jvmpath);
D
duke 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
            return JNI_FALSE;
/*
 * The following case provide backward compatibility with old-style
 * command line options.
 */
        } else if (strcmp(arg, "-fullversion") == 0) {
            fprintf(stderr, "%s full version \"%s\"\n", progname,
                    FULL_VERSION);
            *pret = 0;
            return JNI_FALSE;
        } else if (strcmp(arg, "-verbosegc") == 0) {
            AddOption("-verbose:gc", NULL);
        } else if (strcmp(arg, "-t") == 0) {
            AddOption("-Xt", NULL);
        } else if (strcmp(arg, "-tm") == 0) {
            AddOption("-Xtm", NULL);
        } else if (strcmp(arg, "-debug") == 0) {
            AddOption("-Xdebug", NULL);
        } else if (strcmp(arg, "-noclassgc") == 0) {
            AddOption("-Xnoclassgc", NULL);
        } else if (strcmp(arg, "-Xfuture") == 0) {
            AddOption("-Xverify:all", NULL);
        } else if (strcmp(arg, "-verify") == 0) {
            AddOption("-Xverify:all", NULL);
        } else if (strcmp(arg, "-verifyremote") == 0) {
            AddOption("-Xverify:remote", NULL);
        } else if (strcmp(arg, "-noverify") == 0) {
            AddOption("-Xverify:none", NULL);
        } else if (strcmp(arg, "-XXsuppressExitMessage") == 0) {
            noExitErrorMessage = 1;
        } else if (strncmp(arg, "-prof", 5) == 0) {
            char *p = arg + 5;
S
sla 已提交
1209
            char *tmp = JLI_MemAlloc(strlen(arg) + 50);
D
duke 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            if (*p) {
                sprintf(tmp, "-Xrunhprof:cpu=old,file=%s", p + 1);
            } else {
                sprintf(tmp, "-Xrunhprof:cpu=old,file=java.prof");
            }
            AddOption(tmp, NULL);
        } else if (strncmp(arg, "-ss", 3) == 0 ||
                   strncmp(arg, "-oss", 4) == 0 ||
                   strncmp(arg, "-ms", 3) == 0 ||
                   strncmp(arg, "-mx", 3) == 0) {
S
sla 已提交
1220
            char *tmp = JLI_MemAlloc(strlen(arg) + 6);
D
duke 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
            sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
            AddOption(tmp, NULL);
        } else if (strcmp(arg, "-checksource") == 0 ||
                   strcmp(arg, "-cs") == 0 ||
                   strcmp(arg, "-noasyncgc") == 0) {
            /* No longer supported */
            fprintf(stderr,
                    "Warning: %s option is no longer supported.\n",
                    arg);
        } else if (strncmp(arg, "-version:", 9) == 0 ||
                   strcmp(arg, "-no-jre-restrict-search") == 0 ||
S
sla 已提交
1232 1233
                   strcmp(arg, "-jre-restrict-search") == 0 ||
                   strncmp(arg, "-splash:", 8) == 0) {
D
duke 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
            ; /* Ignore machine independent options already handled */
        } else if (RemovableMachineDependentOption(arg) ) {
            ; /* Do not pass option to vm. */
        }
        else {
            AddOption(arg, NULL);
        }
    }

    if (--argc >= 0) {
        if (jarflag) {
            *pjarfile = *argv++;
            *pclassname = 0;
        } else {
            *pjarfile = 0;
            *pclassname = *argv++;
        }
        *pargc = argc;
        *pargv = argv;
    }

    return JNI_TRUE;
}

/*
 * Initializes the Java Virtual Machine. Also frees options array when
 * finished.
 */
static jboolean
InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
{
    JavaVMInitArgs args;
    jint r;

    memset(&args, 0, sizeof(args));
    args.version  = JNI_VERSION_1_2;
    args.nOptions = numOptions;
    args.options  = options;
    args.ignoreUnrecognized = JNI_FALSE;

    if (_launcher_debug) {
        int i = 0;
        printf("JavaVM args:\n    ");
        printf("version 0x%08lx, ", (long)args.version);
        printf("ignoreUnrecognized is %s, ",
               args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
        printf("nOptions is %ld\n", (long)args.nOptions);
        for (i = 0; i < numOptions; i++)
            printf("    option[%2d] = '%s'\n",
                   i, args.options[i].optionString);
    }

    r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
S
sla 已提交
1287
    JLI_MemFree(options);
D
duke 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    return r == JNI_OK;
}


#define NULL_CHECK0(e) if ((e) == 0) return 0
#define NULL_CHECK(e) if ((e) == 0) return

static jstring platformEncoding = NULL;
static jstring getPlatformEncoding(JNIEnv *env) {
    if (platformEncoding == NULL) {
        jstring propname = (*env)->NewStringUTF(env, "sun.jnu.encoding");
        if (propname) {
            jclass cls;
            jmethodID mid;
S
sla 已提交
1302
            NULL_CHECK0 (cls = (*env)->FindClass(env, "java/lang/System"));
D
duke 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
            NULL_CHECK0 (mid = (*env)->GetStaticMethodID(
                                   env, cls,
                                   "getProperty",
                                   "(Ljava/lang/String;)Ljava/lang/String;"));
            platformEncoding = (*env)->CallStaticObjectMethod (
                                    env, cls, mid, propname);
        }
    }
    return platformEncoding;
}

static jboolean isEncodingSupported(JNIEnv *env, jstring enc) {
    jclass cls;
    jmethodID mid;
S
sla 已提交
1317
    NULL_CHECK0 (cls = (*env)->FindClass(env, "java/nio/charset/Charset"));
D
duke 已提交
1318 1319 1320 1321
    NULL_CHECK0 (mid = (*env)->GetStaticMethodID(
                           env, cls,
                           "isSupported",
                           "(Ljava/lang/String;)Z"));
S
sla 已提交
1322
    return (*env)->CallStaticBooleanMethod(env, cls, mid, enc);
D
duke 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
}

/*
 * Returns a new Java string object for the specified platform string.
 */
static jstring
NewPlatformString(JNIEnv *env, char *s)
{
    int len = (int)strlen(s);
    jclass cls;
    jmethodID mid;
    jbyteArray ary;
    jstring enc;

    if (s == NULL)
        return 0;
    enc = getPlatformEncoding(env);

    ary = (*env)->NewByteArray(env, len);
    if (ary != 0) {
        jstring str = 0;
        (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
        if (!(*env)->ExceptionOccurred(env)) {
            if (isEncodingSupported(env, enc) == JNI_TRUE) {
S
sla 已提交
1347
                NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String"));
D
duke 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
                NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
                                          "([BLjava/lang/String;)V"));
                str = (*env)->NewObject(env, cls, mid, ary, enc);
            } else {
                /*If the encoding specified in sun.jnu.encoding is not
                  endorsed by "Charset.isSupported" we have to fall back
                  to use String(byte[]) explicitly here without specifying
                  the encoding name, in which the StringCoding class will
                  pickup the iso-8859-1 as the fallback converter for us.
                */
S
sla 已提交
1358
                NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String"));
D
duke 已提交
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
                NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
                                          "([B)V"));
                str = (*env)->NewObject(env, cls, mid, ary);
            }
            (*env)->DeleteLocalRef(env, ary);
            return str;
        }
    }
    return 0;
}

/*
 * Returns a new array of Java string objects for the specified
 * array of platform strings.
 */
static jobjectArray
NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
{
    jarray cls;
    jarray ary;
    int i;

S
sla 已提交
1381
    NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String"));
D
duke 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
    for (i = 0; i < strc; i++) {
        jstring str = NewPlatformString(env, *strv++);
        NULL_CHECK0(str);
        (*env)->SetObjectArrayElement(env, ary, i, str);
        (*env)->DeleteLocalRef(env, str);
    }
    return ary;
}

/*
 * Loads a class, convert the '.' to '/'.
 */
static jclass
LoadClass(JNIEnv *env, char *name)
{
S
sla 已提交
1398
    char *buf = JLI_MemAlloc(strlen(name) + 1);
D
duke 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    char *s = buf, *t = name, c;
    jclass cls;
    jlong start, end;

    if (_launcher_debug)
        start = CounterGet();

    do {
        c = *t++;
        *s++ = (c == '.') ? '/' : c;
    } while (c != '\0');
    cls = (*env)->FindClass(env, buf);
S
sla 已提交
1411
    JLI_MemFree(buf);
D
duke 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435

    if (_launcher_debug) {
        end   = CounterGet();
        printf("%ld micro seconds to load main class\n",
               (long)(jint)Counter2Micros(end-start));
        printf("----_JAVA_LAUNCHER_DEBUG----\n");
    }

    return cls;
}


/*
 * Returns the main class name for the specified jar file.
 */
static jstring
GetMainClassName(JNIEnv *env, char *jarname)
{
#define MAIN_CLASS "Main-Class"
    jclass cls;
    jmethodID mid;
    jobject jar, man, attr;
    jstring str, result = 0;

S
sla 已提交
1436
    NULL_CHECK0(cls = (*env)->FindClass(env, "java/util/jar/JarFile"));
D
duke 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
                                          "(Ljava/lang/String;)V"));
    NULL_CHECK0(str = NewPlatformString(env, jarname));
    NULL_CHECK0(jar = (*env)->NewObject(env, cls, mid, str));
    NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "getManifest",
                                          "()Ljava/util/jar/Manifest;"));
    man = (*env)->CallObjectMethod(env, jar, mid);
    if (man != 0) {
        NULL_CHECK0(mid = (*env)->GetMethodID(env,
                                    (*env)->GetObjectClass(env, man),
                                    "getMainAttributes",
                                    "()Ljava/util/jar/Attributes;"));
        attr = (*env)->CallObjectMethod(env, man, mid);
        if (attr != 0) {
            NULL_CHECK0(mid = (*env)->GetMethodID(env,
                                    (*env)->GetObjectClass(env, attr),
                                    "getValue",
                                    "(Ljava/lang/String;)Ljava/lang/String;"));
            NULL_CHECK0(str = NewPlatformString(env, MAIN_CLASS));
            result = (*env)->CallObjectMethod(env, attr, mid, str);
        }
    }
    return result;
}

#ifdef JAVA_ARGS
static char *java_args[] = JAVA_ARGS;
static char *app_classpath[] = APP_CLASSPATH;

/*
S
sla 已提交
1467 1468 1469
 * For tools, convert command line args thus:
 *   javac -cp foo:foo/"*" -J-ms32m ...
 *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
D
duke 已提交
1470 1471
 */
static void
S
sla 已提交
1472
TranslateApplicationArgs(int *pargc, char ***pargv)
D
duke 已提交
1473 1474 1475 1476 1477
{
    const int NUM_ARGS = (sizeof(java_args) / sizeof(char *));
    int argc = *pargc;
    char **argv = *pargv;
    int nargc = argc + NUM_ARGS;
S
sla 已提交
1478
    char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
D
duke 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    int i;

    *pargc = nargc;
    *pargv = nargv;

    /* Copy the VM arguments (i.e. prefixed with -J) */
    for (i = 0; i < NUM_ARGS; i++) {
        char *arg = java_args[i];
        if (arg[0] == '-' && arg[1] == 'J') {
            *nargv++ = arg + 2;
        }
    }

    for (i = 0; i < argc; i++) {
        char *arg = argv[i];
        if (arg[0] == '-' && arg[1] == 'J') {
            if (arg[2] == '\0') {
                ReportErrorMessage("Error: the -J option should not be "
                                   "followed by a space.", JNI_TRUE);
                exit(1);
            }
            *nargv++ = arg + 2;
        }
    }

    /* Copy the rest of the arguments */
    for (i = 0; i < NUM_ARGS; i++) {
        char *arg = java_args[i];
        if (arg[0] != '-' || arg[1] != 'J') {
            *nargv++ = arg;
        }
    }
    for (i = 0; i < argc; i++) {
        char *arg = argv[i];
S
sla 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        if (arg[0] == '-') {
            if (arg[1] == 'J')
                continue;
#ifdef EXPAND_CLASSPATH_WILDCARDS
            if (arg[1] == 'c'
                && (strcmp(arg, "-cp") == 0 ||
                    strcmp(arg, "-classpath") == 0)
                && i < argc - 1) {
                *nargv++ = arg;
                *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
                i++;
                continue;
            }
#endif
D
duke 已提交
1527
        }
S
sla 已提交
1528
        *nargv++ = arg;
D
duke 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
    }
    *nargv = 0;
}

/*
 * For our tools, we try to add 3 VM options:
 *      -Denv.class.path=<envcp>
 *      -Dapplication.home=<apphome>
 *      -Djava.class.path=<appcp>
 * <envcp>   is the user's setting of CLASSPATH -- for instance the user
 *           tells javac where to find binary classes through this environment
 *           variable.  Notice that users will be able to compile against our
 *           tools classes (sun.tools.javac.Main) only if they explicitly add
 *           tools.jar to CLASSPATH.
 * <apphome> is the directory where the application is installed.
 * <appcp>   is the classpath to where our apps' classfiles are.
 */
static jboolean
AddApplicationOptions()
{
    const int NUM_APP_CLASSPATH = (sizeof(app_classpath) / sizeof(char *));
S
sla 已提交
1550
    char *envcp, *appcp, *apphome;
D
duke 已提交
1551 1552 1553 1554 1555
    char home[MAXPATHLEN]; /* application home */
    char separator[] = { PATH_SEPARATOR, '\0' };
    int size, i;
    int strlenHome;

S
sla 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564
    {
        const char *s = getenv("CLASSPATH");
        if (s) {
            s = (char *) JLI_WildcardExpandClasspath(s);
            /* 40 for -Denv.class.path= */
            envcp = (char *)JLI_MemAlloc(strlen(s) + 40);
            sprintf(envcp, "-Denv.class.path=%s", s);
            AddOption(envcp, NULL);
        }
D
duke 已提交
1565 1566 1567 1568 1569 1570 1571 1572
    }

    if (!GetApplicationHome(home, sizeof(home))) {
        ReportErrorMessage("Can't determine application home", JNI_TRUE);
        return JNI_FALSE;
    }

    /* 40 for '-Dapplication.home=' */
S
sla 已提交
1573
    apphome = (char *)JLI_MemAlloc(strlen(home) + 40);
D
duke 已提交
1574 1575 1576 1577 1578 1579 1580 1581 1582
    sprintf(apphome, "-Dapplication.home=%s", home);
    AddOption(apphome, NULL);

    /* How big is the application's classpath? */
    size = 40;                                 /* 40: "-Djava.class.path=" */
    strlenHome = (int)strlen(home);
    for (i = 0; i < NUM_APP_CLASSPATH; i++) {
        size += strlenHome + (int)strlen(app_classpath[i]) + 1; /* 1: separator */
    }
S
sla 已提交
1583
    appcp = (char *)JLI_MemAlloc(size + 1);
D
duke 已提交
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    strcpy(appcp, "-Djava.class.path=");
    for (i = 0; i < NUM_APP_CLASSPATH; i++) {
        strcat(appcp, home);                    /* c:\program files\myapp */
        strcat(appcp, app_classpath[i]);        /* \lib\myapp.jar         */
        strcat(appcp, separator);               /* ;                      */
    }
    appcp[strlen(appcp)-1] = '\0';  /* remove trailing path separator */
    AddOption(appcp, NULL);
    return JNI_TRUE;
}
S
sla 已提交
1594
#endif /* JAVA_ARGS */
D
duke 已提交
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

/*
 * inject the -Dsun.java.command pseudo property into the args structure
 * this pseudo property is used in the HotSpot VM to expose the
 * Java class name and arguments to the main method to the VM. The
 * HotSpot VM uses this pseudo property to store the Java class name
 * (or jar file name) and the arguments to the class's main method
 * to the instrumentation memory region. The sun.java.command pseudo
 * property is not exported by HotSpot to the Java layer.
 */
void
SetJavaCommandLineProp(char *classname, char *jarfile,
                       int argc, char **argv)
{

    int i = 0;
    size_t len = 0;
    char* javaCommand = NULL;
    char* dashDstr = "-Dsun.java.command=";

    if (classname == NULL && jarfile == NULL) {
        /* unexpected, one of these should be set. just return without
         * setting the property
         */
        return;
    }

    /* if the class name is not set, then use the jarfile name */
    if (classname == NULL) {
        classname = jarfile;
    }

    /* determine the amount of memory to allocate assuming
     * the individual components will be space separated
     */
    len = strlen(classname);
    for (i = 0; i < argc; i++) {
        len += strlen(argv[i]) + 1;
    }

    /* allocate the memory */
S
sla 已提交
1636
    javaCommand = (char*) JLI_MemAlloc(len + strlen(dashDstr) + 1);
D
duke 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657

    /* build the -D string */
    *javaCommand = '\0';
    strcat(javaCommand, dashDstr);
    strcat(javaCommand, classname);

    for (i = 0; i < argc; i++) {
        /* the components of the string are space separated. In
         * the case of embedded white space, the relationship of
         * the white space separated components to their true
         * positional arguments will be ambiguous. This issue may
         * be addressed in a future release.
         */
        strcat(javaCommand, " ");
        strcat(javaCommand, argv[i]);
    }

    AddOption(javaCommand, NULL);
}

/*
S
sla 已提交
1658 1659
 * JVM would like to know if it's created by a standard Sun launcher, or by
 * user native application, the following property indicates the former.
D
duke 已提交
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
 */
void SetJavaLauncherProp() {
  AddOption("-Dsun.java.launcher=" LAUNCHER_TYPE, NULL);
}

/*
 * Prints the version information from the java.version and other properties.
 */
static void
PrintJavaVersion(JNIEnv *env)
{
    jclass ver;
    jmethodID print;

S
sla 已提交
1674
    NULL_CHECK(ver = (*env)->FindClass(env, "sun/misc/Version"));
D
duke 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    NULL_CHECK(print = (*env)->GetStaticMethodID(env, ver, "print", "()V"));

    (*env)->CallStaticVoidMethod(env, ver, print);
}

/*
 * Prints default usage message.
 */
static void
PrintUsage(void)
{
S
sla 已提交
1686
#ifndef GAMMA
D
duke 已提交
1687
    int i;
S
sla 已提交
1688
#endif
D
duke 已提交
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770

    fprintf(stdout,
        "Usage: %s [-options] class [args...]\n"
        "           (to execute a class)\n"
        "   or  %s [-options] -jar jarfile [args...]\n"
        "           (to execute a jar file)\n"
        "\n"
        "where options include:\n",
        progname,
        progname);

#ifndef GAMMA
    PrintMachineDependentOptions();

    if ((knownVMs[0].flag == VM_KNOWN) ||
        (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
      fprintf(stdout, "    %s\t  to select the \"%s\" VM\n",
              knownVMs[0].name, knownVMs[0].name+1);
    }
    for (i=1; i<knownVMsCount; i++) {
        if (knownVMs[i].flag == VM_KNOWN)
            fprintf(stdout, "    %s\t  to select the \"%s\" VM\n",
                    knownVMs[i].name, knownVMs[i].name+1);
    }
    for (i=1; i<knownVMsCount; i++) {
        if (knownVMs[i].flag == VM_ALIASED_TO)
            fprintf(stdout, "    %s\t  is a synonym for "
                    "the \"%s\" VM  [deprecated]\n",
                    knownVMs[i].name, knownVMs[i].alias+1);
    }
    /* The first known VM is the default */
    {
      const char* defaultVM   = knownVMs[0].name+1;
      const char* punctuation = ".";
      const char* reason      = "";
      if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
          (ServerClassMachine() == JNI_TRUE)) {
        defaultVM = knownVMs[0].server_class+1;
        punctuation = ", ";
        reason = "because you are running on a server-class machine.\n";
      }
      fprintf(stdout, "                  The default VM is %s%s\n",
              defaultVM, punctuation);
      fprintf(stdout, "                  %s\n",
              reason);
    }
#endif /* ifndef GAMMA */

    fprintf(stdout,
"    -cp <class search path of directories and zip/jar files>\n"
"    -classpath <class search path of directories and zip/jar files>\n"
"                  A %c separated list of directories, JAR archives,\n"
"                  and ZIP archives to search for class files.\n"
"    -D<name>=<value>\n"
"                  set a system property\n"
"    -verbose[:class|gc|jni]\n"
"                  enable verbose output\n"
"    -version      print product version and exit\n"
"    -version:<value>\n"
"                  require the specified version to run\n"
"    -showversion  print product version and continue\n"
"    -jre-restrict-search | -jre-no-restrict-search\n"
"                  include/exclude user private JREs in the version search\n"
"    -? -help      print this help message\n"
"    -X            print help on non-standard options\n"
"    -ea[:<packagename>...|:<classname>]\n"
"    -enableassertions[:<packagename>...|:<classname>]\n"
"                  enable assertions\n"
"    -da[:<packagename>...|:<classname>]\n"
"    -disableassertions[:<packagename>...|:<classname>]\n"
"                  disable assertions\n"
"    -esa | -enablesystemassertions\n"
"                  enable system assertions\n"
"    -dsa | -disablesystemassertions\n"
"                  disable system assertions\n"
"    -agentlib:<libname>[=<options>]\n"
"                  load native agent library <libname>, e.g. -agentlib:hprof\n"
"                    see also, -agentlib:jdwp=help and -agentlib:hprof=help\n"
"    -agentpath:<pathname>[=<options>]\n"
"                  load native agent library by full pathname\n"
"    -javaagent:<jarpath>[=<options>]\n"
"                  load Java programming language agent, see java.lang.instrument\n"
S
sla 已提交
1771 1772
"    -splash:<imagepath>\n"
"                  show splash screen with specified image\n"
D
duke 已提交
1773 1774 1775 1776 1777 1778 1779 1780

            ,PATH_SEPARATOR);
}

/*
 * Print usage message for -X options.
 */
static jint
S
sla 已提交
1781
PrintXUsage(const char *jvmpath)
D
duke 已提交
1782
{
S
sla 已提交
1783 1784 1785 1786 1787
    /*
       A 32 bit cushion to prevent buffer overrun, noting that
       fopen(3C) may fail if the buffer exceeds MAXPATHLEN.
    */
    char path[MAXPATHLEN+32];
D
duke 已提交
1788 1789 1790
    char buf[128];
    size_t n;
    FILE *fp;
S
sla 已提交
1791
    static const char Xusage_txt[] = "/Xusage.txt";
D
duke 已提交
1792

S
sla 已提交
1793 1794 1795
    strcpy(path, jvmpath);
    /* Note the FILE_SEPARATOR is platform dependent */
    strcpy(strrchr(path, FILE_SEPARATOR), Xusage_txt);
D
duke 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
    fp = fopen(path, "r");
    if (fp == 0) {
        fprintf(stderr, "Can't open %s\n", path);
        return 1;
    }
    while ((n = fread(buf, 1, sizeof(buf), fp)) != 0) {
        fwrite(buf, 1, n, stdout);
    }
    fclose(fp);
    return 0;
}

#ifndef GAMMA
/*
 * Read the jvm.cfg file and fill the knownJVMs[] array.
 *
 * The functionality of the jvm.cfg file is subject to change without
 * notice and the mechanism will be removed in the future.
 *
 * The lexical structure of the jvm.cfg file is as follows:
 *
 *     jvmcfg         :=  { vmLine }
 *     vmLine         :=  knownLine
 *                    |   aliasLine
 *                    |   warnLine
 *                    |   ignoreLine
 *                    |   errorLine
 *                    |   predicateLine
 *                    |   commentLine
 *     knownLine      :=  flag  "KNOWN"                  EOL
 *     warnLine       :=  flag  "WARN"                   EOL
 *     ignoreLine     :=  flag  "IGNORE"                 EOL
 *     errorLine      :=  flag  "ERROR"                  EOL
 *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
 *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
 *     commentLine    :=  "#" text                       EOL
 *     flag           :=  "-" identifier
 *
 * The semantics are that when someone specifies a flag on the command line:
 * - if the flag appears on a knownLine, then the identifier is used as
 *   the name of the directory holding the JVM library (the name of the JVM).
 * - if the flag appears as the first flag on an aliasLine, the identifier
 *   of the second flag is used as the name of the JVM.
 * - if the flag appears on a warnLine, the identifier is used as the
 *   name of the JVM, but a warning is generated.
 * - if the flag appears on an ignoreLine, the identifier is recognized as the
 *   name of a JVM, but the identifier is ignored and the default vm used
 * - if the flag appears on an errorLine, an error is generated.
 * - if the flag appears as the first flag on a predicateLine, and
 *   the machine on which you are running passes the predicate indicated,
 *   then the identifier of the second flag is used as the name of the JVM,
 *   otherwise the identifier of the first flag is used as the name of the JVM.
 * If no flag is given on the command line, the first vmLine of the jvm.cfg
 * file determines the name of the JVM.
 * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
 * since they only make sense if someone hasn't specified the name of the
 * JVM on the command line.
 *
 * The intent of the jvm.cfg file is to allow several JVM libraries to
 * be installed in different subdirectories of a single JRE installation,
 * for space-savings and convenience in testing.
 * The intent is explicitly not to provide a full aliasing or predicate
 * mechanism.
 */
jint
ReadKnownVMs(const char *jrepath, char * arch, jboolean speculative)
{
    FILE *jvmCfg;
    char jvmCfgName[MAXPATHLEN+20];
    char line[MAXPATHLEN+20];
    int cnt = 0;
    int lineno = 0;
    jlong start, end;
    int vmType;
    char *tmpPtr;
S
sla 已提交
1871 1872
    char *altVMName = NULL;
    char *serverClassVMName = NULL;
D
duke 已提交
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    static char *whiteSpace = " \t";
    if (_launcher_debug) {
        start = CounterGet();
    }

    strcpy(jvmCfgName, jrepath);
    strcat(jvmCfgName, FILESEP "lib" FILESEP);
    strcat(jvmCfgName, arch);
    strcat(jvmCfgName, FILESEP "jvm.cfg");

    jvmCfg = fopen(jvmCfgName, "r");
    if (jvmCfg == NULL) {
      if (!speculative) {
        ReportErrorMessage2("Error: could not open `%s'", jvmCfgName,
                            JNI_TRUE);
        exit(1);
      } else {
        return -1;
      }
    }
    while (fgets(line, sizeof(line), jvmCfg) != NULL) {
        vmType = VM_UNKNOWN;
        lineno++;
        if (line[0] == '#')
            continue;
        if (line[0] != '-') {
            fprintf(stderr, "Warning: no leading - on line %d of `%s'\n",
                    lineno, jvmCfgName);
        }
        if (cnt >= knownVMsLimit) {
            GrowKnownVMs(cnt);
        }
        line[strlen(line)-1] = '\0'; /* remove trailing newline */
        tmpPtr = line + strcspn(line, whiteSpace);
        if (*tmpPtr == 0) {
            fprintf(stderr, "Warning: missing VM type on line %d of `%s'\n",
                    lineno, jvmCfgName);
        } else {
S
sla 已提交
1911
            /* Null-terminate this string for JLI_StringDup below */
D
duke 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
            *tmpPtr++ = 0;
            tmpPtr += strspn(tmpPtr, whiteSpace);
            if (*tmpPtr == 0) {
                fprintf(stderr, "Warning: missing VM type on line %d of `%s'\n",
                        lineno, jvmCfgName);
            } else {
                if (!strncmp(tmpPtr, "KNOWN", strlen("KNOWN"))) {
                    vmType = VM_KNOWN;
                } else if (!strncmp(tmpPtr, "ALIASED_TO", strlen("ALIASED_TO"))) {
                    tmpPtr += strcspn(tmpPtr, whiteSpace);
                    if (*tmpPtr != 0) {
                        tmpPtr += strspn(tmpPtr, whiteSpace);
                    }
                    if (*tmpPtr == 0) {
                        fprintf(stderr, "Warning: missing VM alias on line %d of `%s'\n",
                                lineno, jvmCfgName);
                    } else {
                        /* Null terminate altVMName */
                        altVMName = tmpPtr;
                        tmpPtr += strcspn(tmpPtr, whiteSpace);
                        *tmpPtr = 0;
                        vmType = VM_ALIASED_TO;
                    }
                } else if (!strncmp(tmpPtr, "WARN", strlen("WARN"))) {
                    vmType = VM_WARN;
                } else if (!strncmp(tmpPtr, "IGNORE", strlen("IGNORE"))) {
                    vmType = VM_IGNORE;
                } else if (!strncmp(tmpPtr, "ERROR", strlen("ERROR"))) {
                    vmType = VM_ERROR;
                } else if (!strncmp(tmpPtr,
                                    "IF_SERVER_CLASS",
                                    strlen("IF_SERVER_CLASS"))) {
                    tmpPtr += strcspn(tmpPtr, whiteSpace);
                    if (*tmpPtr != 0) {
                        tmpPtr += strspn(tmpPtr, whiteSpace);
                    }
                    if (*tmpPtr == 0) {
                        fprintf(stderr, "Warning: missing server class VM on line %d of `%s'\n",
                                lineno, jvmCfgName);
                    } else {
                        /* Null terminate server class VM name */
                        serverClassVMName = tmpPtr;
                        tmpPtr += strcspn(tmpPtr, whiteSpace);
                        *tmpPtr = 0;
                        vmType = VM_IF_SERVER_CLASS;
                    }
                } else {
                    fprintf(stderr, "Warning: unknown VM type on line %d of `%s'\n",
                            lineno, &jvmCfgName[0]);
                    vmType = VM_KNOWN;
                }
            }
        }

        if (_launcher_debug)
            printf("jvm.cfg[%d] = ->%s<-\n", cnt, line);
        if (vmType != VM_UNKNOWN) {
S
sla 已提交
1969
            knownVMs[cnt].name = JLI_StringDup(line);
D
duke 已提交
1970 1971 1972 1973 1974
            knownVMs[cnt].flag = vmType;
            switch (vmType) {
            default:
                break;
            case VM_ALIASED_TO:
S
sla 已提交
1975
                knownVMs[cnt].alias = JLI_StringDup(altVMName);
D
duke 已提交
1976 1977 1978 1979 1980 1981
                if (_launcher_debug) {
                    printf("    name: %s  vmType: %s  alias: %s\n",
                           knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
                }
                break;
            case VM_IF_SERVER_CLASS:
S
sla 已提交
1982
                knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName);
D
duke 已提交
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
                if (_launcher_debug) {
                    printf("    name: %s  vmType: %s  server_class: %s\n",
                           knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
                }
                break;
            }
            cnt++;
        }
    }
    fclose(jvmCfg);
    knownVMsCount = cnt;

    if (_launcher_debug) {
        end   = CounterGet();
        printf("%ld micro seconds to parse jvm.cfg\n",
               (long)(jint)Counter2Micros(end-start));
    }

    return cnt;
}


static void
GrowKnownVMs(int minimum)
{
    struct vmdesc* newKnownVMs;
    int newMax;

    newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
    if (newMax <= minimum) {
        newMax = minimum;
    }
S
sla 已提交
2015
    newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
D
duke 已提交
2016 2017 2018
    if (knownVMs != NULL) {
        memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
    }
S
sla 已提交
2019
    JLI_MemFree(knownVMs);
D
duke 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    knownVMs = newKnownVMs;
    knownVMsLimit = newMax;
}


/* Returns index of VM or -1 if not found */
static int
KnownVMIndex(const char* name)
{
    int i;
    if (strncmp(name, "-J", 2) == 0) name += 2;
    for (i = 0; i < knownVMsCount; i++) {
        if (!strcmp(name, knownVMs[i].name)) {
            return i;
        }
    }
    return -1;
}

static void
FreeKnownVMs()
{
    int i;
    for (i = 0; i < knownVMsCount; i++) {
S
sla 已提交
2044
        JLI_MemFree(knownVMs[i].name);
D
duke 已提交
2045 2046
        knownVMs[i].name = NULL;
    }
S
sla 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
    JLI_MemFree(knownVMs);
}


/*
 * Displays the splash screen according to the jar file name
 * and image file names stored in environment variables
 */
static void
ShowSplashScreen()
{
    const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
    const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
    int data_size;
    void *image_data;
    if (jar_name) {
        image_data = JLI_JarUnpackFile(jar_name, file_name, &data_size);
        if (image_data) {
            DoSplashInit();
            DoSplashLoadMemory(image_data, data_size);
            JLI_MemFree(image_data);
        }
    } else if (file_name) {
        DoSplashInit();
        DoSplashLoadFile(file_name);
    } else {
        return;
    }
    DoSplashSetFileJarName(file_name, jar_name);
D
duke 已提交
2076 2077 2078
}

#endif /* ifndef GAMMA */