Path: blob/master/src/java.base/macosx/native/libjli/java_md_macosx.m
67760 views
/*1* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include "java.h"26#include "jvm_md.h"27#include <dirent.h>28#include <dlfcn.h>29#include <fcntl.h>30#include <inttypes.h>31#include <stdio.h>32#include <string.h>33#include <stdlib.h>34#include <sys/stat.h>35#include <unistd.h>36#include <sys/types.h>37#include <sys/time.h>3839#include "manifest_info.h"4041/* Support Cocoa event loop on the main thread */42#include <Cocoa/Cocoa.h>43#include <objc/objc-runtime.h>44#include <objc/objc-auto.h>4546#include <errno.h>47#include <spawn.h>4849struct NSAppArgs {50int argc;51char **argv;52};5354#define JVM_DLL "libjvm.dylib"55#define JAVA_DLL "libjava.dylib"56/* FALLBACK avoids naming conflicts with system libraries57* (eg, ImageIO's libJPEG.dylib) */58#define LD_LIBRARY_PATH "DYLD_FALLBACK_LIBRARY_PATH"5960/*61* If a processor / os combination has the ability to run binaries of62* two data models and cohabitation of jre/jdk bits with both data63* models is supported, then DUAL_MODE is defined. MacOSX is a hybrid64* system in that, the universal library can contain all types of libraries65* 32/64 and client/server, thus the spawn is capable of linking with the66* appropriate library as requested.67*68* Notes:69* 1. VM. DUAL_MODE is disabled, and not supported, however, it is left here in70* for experimentation and perhaps enable it in the future.71* 2. At the time of this writing, the universal library contains only72* a server 64-bit server JVM.73* 3. "-client" command line option is supported merely as a command line flag,74* for, compatibility reasons, however, a server VM will be launched.75*/7677/*78* Flowchart of launcher execs and options processing on unix79*80* The selection of the proper vm shared library to open depends on81* several classes of command line options, including vm "flavor"82* options (-client, -server) and the data model options, -d32 and83* -d64, as well as a version specification which may have come from84* the command line or from the manifest of an executable jar file.85* The vm selection options are not passed to the running86* virtual machine; they must be screened out by the launcher.87*88* The version specification (if any) is processed first by the89* platform independent routine SelectVersion. This may result in90* the exec of the specified launcher version.91*92* Now, in most cases,the launcher will dlopen the target libjvm.so. All93* required libraries are loaded by the runtime linker, using the known paths94* baked into the shared libraries at compile time. Therefore,95* in most cases, the launcher will only exec, if the data models are96* mismatched, and will not set any environment variables, regardless of the97* data models.98*99*100*101* Main102* (incoming argv)103* |104* \|/105* CreateExecutionEnvironment106* (determines desired data model)107* |108* |109* \|/110* Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error)111* | |112* | |113* | \|/114* | YES115* | |116* | |117* | \|/118* | CheckJvmType119* | (removes -client, -server etc.)120* | |121* | |122* \|/ \|/123* YES Find the desired executable/library124* | |125* | |126* \|/ \|/127* CheckJvmType POINT A128* (removes -client, -server, etc.)129* |130* |131* \|/132* TranslateDashJArgs...133* (Prepare to pass args to vm)134* |135* |136* \|/137* ParseArguments138* (processes version options,139* creates argument list for vm,140* etc.)141* |142* |143* \|/144* POINT A145* |146* |147* \|/148* Path is desired JRE ? YES --> Continue149* NO150* |151* |152* \|/153* Paths have well known154* jvm paths ? --> NO --> Continue155* YES156* |157* |158* \|/159* Does libjvm.so exist160* in any of them ? --> NO --> Continue161* YES162* |163* |164* \|/165* Re-exec / Spawn166* |167* |168* \|/169* Main170*/171172/* Store the name of the executable once computed */173static char *execname = NULL;174175/*176* execname accessor from other parts of platform dependent logic177*/178const char *179GetExecName() {180return execname;181}182183/*184* Exports the JNI interface from libjli185*186* This allows client code to link against the .jre/.jdk bundles,187* and not worry about trying to pick a HotSpot to link against.188*189* Switching architectures is unsupported, since client code has190* made that choice before the JVM was requested.191*/192193static InvocationFunctions *sExportedJNIFunctions = NULL;194static char *sPreferredJVMType = NULL;195196static InvocationFunctions *GetExportedJNIFunctions() {197if (sExportedJNIFunctions != NULL) return sExportedJNIFunctions;198199char jrePath[PATH_MAX];200jboolean gotJREPath = GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE);201if (!gotJREPath) {202JLI_ReportErrorMessage("Failed to GetJREPath()");203return NULL;204}205206char *preferredJVM = sPreferredJVMType;207if (preferredJVM == NULL) {208#if defined(__i386__)209preferredJVM = "client";210#elif defined(__x86_64__)211preferredJVM = "server";212#elif defined(__aarch64__)213preferredJVM = "server";214#else215#error "Unknown architecture - needs definition"216#endif217}218219char jvmPath[PATH_MAX];220jboolean gotJVMPath = GetJVMPath(jrePath, preferredJVM, jvmPath, sizeof(jvmPath));221if (!gotJVMPath) {222JLI_ReportErrorMessage("Failed to GetJVMPath()");223return NULL;224}225226InvocationFunctions *fxns = malloc(sizeof(InvocationFunctions));227jboolean vmLoaded = LoadJavaVM(jvmPath, fxns);228if (!vmLoaded) {229JLI_ReportErrorMessage("Failed to LoadJavaVM()");230return NULL;231}232233return sExportedJNIFunctions = fxns;234}235236#ifndef STATIC_BUILD237238JNIEXPORT jint JNICALL239JNI_GetDefaultJavaVMInitArgs(void *args) {240InvocationFunctions *ifn = GetExportedJNIFunctions();241if (ifn == NULL) return JNI_ERR;242return ifn->GetDefaultJavaVMInitArgs(args);243}244245JNIEXPORT jint JNICALL246JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args) {247InvocationFunctions *ifn = GetExportedJNIFunctions();248if (ifn == NULL) return JNI_ERR;249return ifn->CreateJavaVM(pvm, penv, args);250}251252JNIEXPORT jint JNICALL253JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) {254InvocationFunctions *ifn = GetExportedJNIFunctions();255if (ifn == NULL) return JNI_ERR;256return ifn->GetCreatedJavaVMs(vmBuf, bufLen, nVMs);257}258#endif259260/*261* Allow JLI-aware launchers to specify a client/server preference262*/263JNIEXPORT void JNICALL264JLI_SetPreferredJVM(const char *prefJVM) {265if (sPreferredJVMType != NULL) {266free(sPreferredJVMType);267sPreferredJVMType = NULL;268}269270if (prefJVM == NULL) return;271sPreferredJVMType = strdup(prefJVM);272}273274static BOOL awtLoaded = NO;275static pthread_mutex_t awtLoaded_mutex = PTHREAD_MUTEX_INITIALIZER;276static pthread_cond_t awtLoaded_cv = PTHREAD_COND_INITIALIZER;277278JNIEXPORT void JNICALL279JLI_NotifyAWTLoaded()280{281pthread_mutex_lock(&awtLoaded_mutex);282awtLoaded = YES;283pthread_cond_signal(&awtLoaded_cv);284pthread_mutex_unlock(&awtLoaded_mutex);285}286287static int (*main_fptr)(int argc, char **argv) = NULL;288289/*290* Unwrap the arguments and re-run main()291*/292static void *apple_main (void *arg)293{294if (main_fptr == NULL) {295#ifdef STATIC_BUILD296extern int main(int argc, char **argv);297main_fptr = &main;298#else299main_fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");300#endif301if (main_fptr == NULL) {302JLI_ReportErrorMessageSys("error locating main entrypoint\n");303exit(1);304}305}306307struct NSAppArgs *args = (struct NSAppArgs *) arg;308exit(main_fptr(args->argc, args->argv));309}310311static void dummyTimer(CFRunLoopTimerRef timer, void *info) {}312313static void ParkEventLoop() {314// RunLoop needs at least one source, and 1e20 is pretty far into the future315CFRunLoopTimerRef t = CFRunLoopTimerCreate(kCFAllocatorDefault, 1.0e20, 0.0, 0, 0, dummyTimer, NULL);316CFRunLoopAddTimer(CFRunLoopGetCurrent(), t, kCFRunLoopDefaultMode);317CFRelease(t);318319// Park this thread in the main run loop.320int32_t result;321do {322result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, false);323} while (result != kCFRunLoopRunFinished);324}325326/*327* Mac OS X mandates that the GUI event loop run on very first thread of328* an application. This requires that we re-call Java's main() on a new329* thread, reserving the 'main' thread for Cocoa.330*/331static void MacOSXStartup(int argc, char *argv[]) {332// Thread already started?333static jboolean started = false;334if (started) {335return;336}337started = true;338339// Hand off arguments340struct NSAppArgs args;341args.argc = argc;342args.argv = argv;343344// Fire up the main thread345pthread_t main_thr;346if (pthread_create(&main_thr, NULL, &apple_main, &args) != 0) {347JLI_ReportErrorMessageSys("Could not create main thread: %s\n", strerror(errno));348exit(1);349}350if (pthread_detach(main_thr)) {351JLI_ReportErrorMessageSys("pthread_detach() failed: %s\n", strerror(errno));352exit(1);353}354355ParkEventLoop();356}357358void359CreateExecutionEnvironment(int *pargc, char ***pargv,360char jrepath[], jint so_jrepath,361char jvmpath[], jint so_jvmpath,362char jvmcfg[], jint so_jvmcfg) {363jboolean jvmpathExists;364365/* Compute/set the name of the executable */366SetExecname(*pargv);367368char * jvmtype = NULL;369int argc = *pargc;370char **argv = *pargv;371372/* Find out where the JRE is that we will be using. */373if (!GetJREPath(jrepath, so_jrepath, JNI_FALSE) ) {374JLI_ReportErrorMessage(JRE_ERROR1);375exit(2);376}377JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg",378jrepath, FILESEP, FILESEP);379/* Find the specified JVM type */380if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {381JLI_ReportErrorMessage(CFG_ERROR7);382exit(1);383}384385jvmpath[0] = '\0';386jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);387if (JLI_StrCmp(jvmtype, "ERROR") == 0) {388JLI_ReportErrorMessage(CFG_ERROR9);389exit(4);390}391392if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {393JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);394exit(4);395}396397/*398* Mac OS X requires the Cocoa event loop to be run on the "main"399* thread. Spawn off a new thread to run main() and pass400* this thread off to the Cocoa event loop.401*/402MacOSXStartup(argc, argv);403404/*405* we seem to have everything we need406*/407return;408}409410/*411* VM choosing is done by the launcher (java.c).412*/413static jboolean414GetJVMPath(const char *jrepath, const char *jvmtype,415char *jvmpath, jint jvmpathsize)416{417struct stat s;418419if (JLI_StrChr(jvmtype, '/')) {420JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype);421} else {422/*423* macosx client library is built thin, i386 only.424* 64 bit client requests must load server library425*/426JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtype);427}428429JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);430431#ifdef STATIC_BUILD432return JNI_TRUE;433#else434if (stat(jvmpath, &s) == 0) {435JLI_TraceLauncher("yes.\n");436return JNI_TRUE;437} else {438JLI_TraceLauncher("no.\n");439return JNI_FALSE;440}441#endif442}443444/*445* Find path to JRE based on .exe's location or registry settings.446*/447static jboolean448GetJREPath(char *path, jint pathsize, jboolean speculative)449{450char libjava[MAXPATHLEN];451452if (GetApplicationHome(path, pathsize)) {453/* Is JRE co-located with the application? */454#ifdef STATIC_BUILD455char jvm_cfg[MAXPATHLEN];456JLI_Snprintf(jvm_cfg, sizeof(jvm_cfg), "%s/lib/jvm.cfg", path);457if (access(jvm_cfg, F_OK) == 0) {458return JNI_TRUE;459}460#else461JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path);462if (access(libjava, F_OK) == 0) {463return JNI_TRUE;464}465#endif466/* ensure storage for path + /jre + NULL */467if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) {468JLI_TraceLauncher("Insufficient space to store JRE path\n");469return JNI_FALSE;470}471/* Does the app ship a private JRE in <apphome>/jre directory? */472JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path);473if (access(libjava, F_OK) == 0) {474JLI_StrCat(path, "/jre");475JLI_TraceLauncher("JRE path is %s\n", path);476return JNI_TRUE;477}478}479480/* try to find ourselves instead */481Dl_info selfInfo;482dladdr(&GetJREPath, &selfInfo);483484#ifdef STATIC_BUILD485char jvm_cfg[MAXPATHLEN];486char *p = NULL;487strncpy(jvm_cfg, selfInfo.dli_fname, MAXPATHLEN);488p = strrchr(jvm_cfg, '/'); *p = '\0';489p = strrchr(jvm_cfg, '/');490if (strcmp(p, "/.") == 0) {491*p = '\0';492p = strrchr(jvm_cfg, '/'); *p = '\0';493}494else *p = '\0';495strncpy(path, jvm_cfg, pathsize);496strncat(jvm_cfg, "/lib/jvm.cfg", MAXPATHLEN);497if (access(jvm_cfg, F_OK) == 0) {498return JNI_TRUE;499}500#endif501502char *realPathToSelf = realpath(selfInfo.dli_fname, path);503if (realPathToSelf != path) {504return JNI_FALSE;505}506507size_t pathLen = strlen(realPathToSelf);508if (pathLen == 0) {509return JNI_FALSE;510}511512const char lastPathComponent[] = "/lib/libjli.dylib";513size_t sizeOfLastPathComponent = sizeof(lastPathComponent) - 1;514if (pathLen < sizeOfLastPathComponent) {515return JNI_FALSE;516}517518size_t indexOfLastPathComponent = pathLen - sizeOfLastPathComponent;519if (0 == strncmp(realPathToSelf + indexOfLastPathComponent, lastPathComponent, sizeOfLastPathComponent)) {520realPathToSelf[indexOfLastPathComponent + 1] = '\0';521return JNI_TRUE;522}523524// If libjli.dylib is loaded from a macos bundle MacOS dir, find the JRE dir525// in ../Home.526const char altLastPathComponent[] = "/MacOS/libjli.dylib";527size_t sizeOfAltLastPathComponent = sizeof(altLastPathComponent) - 1;528if (pathLen < sizeOfLastPathComponent) {529return JNI_FALSE;530}531532size_t indexOfAltLastPathComponent = pathLen - sizeOfAltLastPathComponent;533if (0 == strncmp(realPathToSelf + indexOfAltLastPathComponent, altLastPathComponent, sizeOfAltLastPathComponent)) {534JLI_Snprintf(realPathToSelf + indexOfAltLastPathComponent, sizeOfAltLastPathComponent, "%s", "/Home");535if (access(realPathToSelf, F_OK) == 0) {536return JNI_TRUE;537}538}539540if (!speculative)541JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);542return JNI_FALSE;543}544545jboolean546LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)547{548Dl_info dlinfo;549void *libjvm;550551JLI_TraceLauncher("JVM path is %s\n", jvmpath);552553#ifndef STATIC_BUILD554libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);555#else556libjvm = dlopen(NULL, RTLD_FIRST);557#endif558if (libjvm == NULL) {559JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);560JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());561return JNI_FALSE;562}563564ifn->CreateJavaVM = (CreateJavaVM_t)565dlsym(libjvm, "JNI_CreateJavaVM");566if (ifn->CreateJavaVM == NULL) {567JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());568return JNI_FALSE;569}570571ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)572dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");573if (ifn->GetDefaultJavaVMInitArgs == NULL) {574JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());575return JNI_FALSE;576}577578ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)579dlsym(libjvm, "JNI_GetCreatedJavaVMs");580if (ifn->GetCreatedJavaVMs == NULL) {581JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());582return JNI_FALSE;583}584585return JNI_TRUE;586}587588/*589* Compute the name of the executable590*591* In order to re-exec securely we need the absolute path of the592* executable. On Solaris getexecname(3c) may not return an absolute593* path so we use dladdr to get the filename of the executable and594* then use realpath to derive an absolute path. From Solaris 9595* onwards the filename returned in DL_info structure from dladdr is596* an absolute pathname so technically realpath isn't required.597* On Linux we read the executable name from /proc/self/exe.598* As a fallback, and for platforms other than Solaris and Linux,599* we use FindExecName to compute the executable name.600*/601const char*602SetExecname(char **argv)603{604char* exec_path = NULL;605{606Dl_info dlinfo;607608#ifdef STATIC_BUILD609void *fptr;610fptr = (void *)&SetExecname;611#else612int (*fptr)();613fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");614#endif615if (fptr == NULL) {616JLI_ReportErrorMessage(DLL_ERROR3, dlerror());617return JNI_FALSE;618}619620if (dladdr((void*)fptr, &dlinfo)) {621char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);622if (resolved != NULL) {623exec_path = realpath(dlinfo.dli_fname, resolved);624if (exec_path == NULL) {625JLI_MemFree(resolved);626}627}628}629}630if (exec_path == NULL) {631exec_path = FindExecName(argv[0]);632}633execname = exec_path;634return exec_path;635}636637/* --- Splash Screen shared library support --- */638639static JavaVM* SetJavaVMValue()640{641JavaVM * jvm = NULL;642643// The handle is good for both the launcher and the libosxapp.dylib644void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);645if (handle) {646typedef JavaVM* (*JLI_GetJavaVMInstance_t)();647648JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance =649(JLI_GetJavaVMInstance_t)dlsym(handle,650"JLI_GetJavaVMInstance");651if (JLI_GetJavaVMInstance) {652jvm = JLI_GetJavaVMInstance();653}654655if (jvm) {656typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*);657658OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM =659(OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM");660if (OSXAPP_SetJavaVM) {661OSXAPP_SetJavaVM(jvm);662} else {663jvm = NULL;664}665}666667dlclose(handle);668}669670return jvm;671}672673static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");674675static void* hSplashLib = NULL;676677void* SplashProcAddress(const char* name) {678if (!hSplashLib) {679char jrePath[PATH_MAX];680if (!GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE)) {681JLI_ReportErrorMessage(JRE_ERROR1);682return NULL;683}684685char splashPath[PATH_MAX];686const int ret = JLI_Snprintf(splashPath, sizeof(splashPath),687"%s/lib/%s", jrePath, SPLASHSCREEN_SO);688if (ret >= (int)sizeof(splashPath)) {689JLI_ReportErrorMessage(JRE_ERROR11);690return NULL;691}692if (ret < 0) {693JLI_ReportErrorMessage(JRE_ERROR13);694return NULL;695}696697hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);698// It's OK if dlopen() fails. The splash screen library binary file699// might have been stripped out from the JRE image to reduce its size700// (e.g. on embedded platforms).701702if (hSplashLib) {703if (!SetJavaVMValue()) {704dlclose(hSplashLib);705hSplashLib = NULL;706}707}708}709if (hSplashLib) {710void* sym = dlsym(hSplashLib, name);711return sym;712} else {713return NULL;714}715}716717/*718* Signature adapter for pthread_create().719*/720static void* ThreadJavaMain(void* args) {721return (void*)(intptr_t)JavaMain(args);722}723724/*725* Block current thread and continue execution in a new thread.726*/727int728CallJavaMainInNewThread(jlong stack_size, void* args) {729int rslt;730pthread_t tid;731pthread_attr_t attr;732pthread_attr_init(&attr);733pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);734735if (stack_size > 0) {736pthread_attr_setstacksize(&attr, stack_size);737}738pthread_attr_setguardsize(&attr, 0); // no pthread guard page on java threads739740if (pthread_create(&tid, &attr, ThreadJavaMain, args) == 0) {741void* tmp;742pthread_join(tid, &tmp);743rslt = (int)(intptr_t)tmp;744} else {745/*746* Continue execution in current thread if for some reason (e.g. out of747* memory/LWP) a new thread can't be created. This will likely fail748* later in JavaMain as JNI_CreateJavaVM needs to create quite a749* few new threads, anyway, just give it a try..750*/751rslt = JavaMain(args);752}753754pthread_attr_destroy(&attr);755return rslt;756}757758static JavaVM* jvmInstance = NULL;759static jboolean sameThread = JNI_FALSE; /* start VM in current thread */760761/*762* Note there is a callback on this function from the splashscreen logic,763* this as well SetJavaVMValue() needs to be simplified.764*/765JNIEXPORT JavaVM* JNICALL766JLI_GetJavaVMInstance()767{768return jvmInstance;769}770771void772RegisterThread()773{774// stubbed out for windows and *nixes.775}776777static void778SetXDockArgForAWT(const char *arg)779{780char envVar[80];781if (strstr(arg, "-Xdock:name=") == arg) {782/*783* The APP_NAME_<pid> environment variable is used to pass784* an application name as specified with the -Xdock:name command785* line option from Java launcher code to the AWT code in order786* to assign this name to the app's dock tile on the Mac.787* The _<pid> part is added to avoid collisions with child processes.788*789* WARNING: This environment variable is an implementation detail and790* isn't meant for use outside of the core platform. The mechanism for791* passing this information from Java launcher to other modules may792* change drastically between update release, and it may even be793* removed or replaced with another mechanism.794*795* NOTE: It is used by SWT, and JavaFX.796*/797snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());798setenv(envVar, (arg + 12), 1);799}800801if (strstr(arg, "-Xdock:icon=") == arg) {802/*803* The APP_ICON_<pid> environment variable is used to pass804* an application icon as specified with the -Xdock:icon command805* line option from Java launcher code to the AWT code in order806* to assign this icon to the app's dock tile on the Mac.807* The _<pid> part is added to avoid collisions with child processes.808*809* WARNING: This environment variable is an implementation detail and810* isn't meant for use outside of the core platform. The mechanism for811* passing this information from Java launcher to other modules may812* change drastically between update release, and it may even be813* removed or replaced with another mechanism.814*815* NOTE: It is used by SWT, and JavaFX.816*/817snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());818setenv(envVar, (arg + 12), 1);819}820}821822static void823SetMainClassForAWT(JNIEnv *env, jclass mainClass) {824jclass classClass = NULL;825NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class"));826827jmethodID getCanonicalNameMID = NULL;828NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;"));829830jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID);831if ((*env)->ExceptionCheck(env) || NULL == mainClassString) {832/*833* Clears all errors caused by getCanonicalName() on the mainclass and834* leaves the JAVA_MAIN_CLASS__<pid> empty.835*/836(*env)->ExceptionClear(env);837return;838}839840const char *mainClassName = NULL;841NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL));842843char envVar[80];844/*845* The JAVA_MAIN_CLASS_<pid> environment variable is used to pass846* the name of a Java class whose main() method is invoked by847* the Java launcher code to start the application, to the AWT code848* in order to assign the name to the Apple menu bar when the app849* is active on the Mac.850* The _<pid> part is added to avoid collisions with child processes.851*852* WARNING: This environment variable is an implementation detail and853* isn't meant for use outside of the core platform. The mechanism for854* passing this information from Java launcher to other modules may855* change drastically between update release, and it may even be856* removed or replaced with another mechanism.857*858* NOTE: It is used by SWT, and JavaFX.859*/860snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid());861setenv(envVar, mainClassName, 1);862863(*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName);864}865866void867SetXStartOnFirstThreadArg()868{869// XXX: BEGIN HACK870// short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625>871// need a way to get AWT/Swing apps launched when spawned from Eclipse,872// which currently has no UI to not pass the -XstartOnFirstThread option873if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return;874// XXX: END HACK875876sameThread = JNI_TRUE;877// Set a variable that tells us we started on the main thread.878// This is used by the AWT during startup. (See LWCToolkit.m)879char envVar[80];880snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());881setenv(envVar, "1", 1);882}883884// MacOSX we may continue in the same thread885int886JVMInit(InvocationFunctions* ifn, jlong threadStackSize,887int argc, char **argv,888int mode, char *what, int ret) {889if (sameThread) {890JLI_TraceLauncher("In same thread\n");891// need to block this thread against the main thread892// so signals get caught correctly893__block int rslt = 0;894NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];895{896NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock: ^{897JavaMainArgs args;898args.argc = argc;899args.argv = argv;900args.mode = mode;901args.what = what;902args.ifn = *ifn;903rslt = JavaMain(&args);904}];905906/*907* We cannot use dispatch_sync here, because it blocks the main dispatch queue.908* Using the main NSRunLoop allows the dispatch queue to run properly once909* SWT (or whatever toolkit this is needed for) kicks off it's own NSRunLoop910* and starts running.911*/912[op performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];913}914[pool drain];915return rslt;916} else {917return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);918}919}920921/*922* Note the jvmInstance must be initialized first before entering into923* ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance.924*/925void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) {926jvmInstance = vm;927SetMainClassForAWT(env, mainClass);928CHECK_EXCEPTION_RETURN();929ShowSplashScreen();930}931932jboolean933ProcessPlatformOption(const char* arg)934{935if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) {936SetXStartOnFirstThreadArg();937return JNI_TRUE;938} else if (JLI_StrCCmp(arg, "-Xdock:") == 0) {939SetXDockArgForAWT(arg);940return JNI_TRUE;941}942// arguments we know not943return JNI_FALSE;944}945946947