Path: blob/master/src/java.base/macosx/native/libjli/java_md_macosx.m
41119 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#ifndef TARGET_IOS42/* Support Cocoa event loop on the main thread */43#include <Cocoa/Cocoa.h>44#include <objc/objc-runtime.h>45#include <objc/objc-auto.h>46#endif4748#include <errno.h>49#include <spawn.h>5051struct NSAppArgs {52int argc;53char **argv;54};5556#define JVM_DLL "libjvm.dylib"57#define JAVA_DLL "libjava.dylib"58/* FALLBACK avoids naming conflicts with system libraries59* (eg, ImageIO's libJPEG.dylib) */60#define LD_LIBRARY_PATH "DYLD_FALLBACK_LIBRARY_PATH"6162/*63* If a processor / os combination has the ability to run binaries of64* two data models and cohabitation of jre/jdk bits with both data65* models is supported, then DUAL_MODE is defined. MacOSX is a hybrid66* system in that, the universal library can contain all types of libraries67* 32/64 and client/server, thus the spawn is capable of linking with the68* appropriate library as requested.69*70* Notes:71* 1. VM. DUAL_MODE is disabled, and not supported, however, it is left here in72* for experimentation and perhaps enable it in the future.73* 2. At the time of this writing, the universal library contains only74* a server 64-bit server JVM.75* 3. "-client" command line option is supported merely as a command line flag,76* for, compatibility reasons, however, a server VM will be launched.77*/7879/*80* Flowchart of launcher execs and options processing on unix81*82* The selection of the proper vm shared library to open depends on83* several classes of command line options, including vm "flavor"84* options (-client, -server) and the data model options, -d32 and85* -d64, as well as a version specification which may have come from86* the command line or from the manifest of an executable jar file.87* The vm selection options are not passed to the running88* virtual machine; they must be screened out by the launcher.89*90* The version specification (if any) is processed first by the91* platform independent routine SelectVersion. This may result in92* the exec of the specified launcher version.93*94* Now, in most cases,the launcher will dlopen the target libjvm.so. All95* required libraries are loaded by the runtime linker, using the known paths96* baked into the shared libraries at compile time. Therefore,97* in most cases, the launcher will only exec, if the data models are98* mismatched, and will not set any environment variables, regardless of the99* data models.100*101*102*103* Main104* (incoming argv)105* |106* \|/107* CreateExecutionEnvironment108* (determines desired data model)109* |110* |111* \|/112* Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error)113* | |114* | |115* | \|/116* | YES117* | |118* | |119* | \|/120* | CheckJvmType121* | (removes -client, -server etc.)122* | |123* | |124* \|/ \|/125* YES Find the desired executable/library126* | |127* | |128* \|/ \|/129* CheckJvmType POINT A130* (removes -client, -server, etc.)131* |132* |133* \|/134* TranslateDashJArgs...135* (Prepare to pass args to vm)136* |137* |138* \|/139* ParseArguments140* (processes version options,141* creates argument list for vm,142* etc.)143* |144* |145* \|/146* POINT A147* |148* |149* \|/150* Path is desired JRE ? YES --> Continue151* NO152* |153* |154* \|/155* Paths have well known156* jvm paths ? --> NO --> Continue157* YES158* |159* |160* \|/161* Does libjvm.so exist162* in any of them ? --> NO --> Continue163* YES164* |165* |166* \|/167* Re-exec / Spawn168* |169* |170* \|/171* Main172*/173174/* Store the name of the executable once computed */175static char *execname = NULL;176177/*178* execname accessor from other parts of platform dependent logic179*/180const char *181GetExecName() {182return execname;183}184185/*186* Exports the JNI interface from libjli187*188* This allows client code to link against the .jre/.jdk bundles,189* and not worry about trying to pick a HotSpot to link against.190*191* Switching architectures is unsupported, since client code has192* made that choice before the JVM was requested.193*/194195static InvocationFunctions *sExportedJNIFunctions = NULL;196static char *sPreferredJVMType = NULL;197198static InvocationFunctions *GetExportedJNIFunctions() {199if (sExportedJNIFunctions != NULL) return sExportedJNIFunctions;200201char jrePath[PATH_MAX];202jboolean gotJREPath = GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE);203if (!gotJREPath) {204JLI_ReportErrorMessage("Failed to GetJREPath()");205return NULL;206}207208char *preferredJVM = sPreferredJVMType;209if (preferredJVM == NULL) {210#if defined(__i386__)211preferredJVM = "client";212#elif defined(__x86_64__)213preferredJVM = "server";214#elif defined(__aarch64__)215preferredJVM = "server";216#elif defined(__arm64__)217preferredJVM = "zero";218#else219#error "Unknown architecture - needs definition"220#endif221}222223char jvmPath[PATH_MAX];224jboolean gotJVMPath = GetJVMPath(jrePath, preferredJVM, jvmPath, sizeof(jvmPath));225if (!gotJVMPath) {226JLI_ReportErrorMessage("Failed to GetJVMPath()");227return NULL;228}229230InvocationFunctions *fxns = malloc(sizeof(InvocationFunctions));231jboolean vmLoaded = LoadJavaVM(jvmPath, fxns);232if (!vmLoaded) {233JLI_ReportErrorMessage("Failed to LoadJavaVM()");234return NULL;235}236237return sExportedJNIFunctions = fxns;238}239240#ifndef STATIC_BUILD241242JNIEXPORT jint JNICALL243JNI_GetDefaultJavaVMInitArgs(void *args) {244InvocationFunctions *ifn = GetExportedJNIFunctions();245if (ifn == NULL) return JNI_ERR;246return ifn->GetDefaultJavaVMInitArgs(args);247}248249JNIEXPORT jint JNICALL250JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args) {251InvocationFunctions *ifn = GetExportedJNIFunctions();252if (ifn == NULL) return JNI_ERR;253return ifn->CreateJavaVM(pvm, penv, args);254}255256JNIEXPORT jint JNICALL257JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) {258InvocationFunctions *ifn = GetExportedJNIFunctions();259if (ifn == NULL) return JNI_ERR;260return ifn->GetCreatedJavaVMs(vmBuf, bufLen, nVMs);261}262#endif263264/*265* Allow JLI-aware launchers to specify a client/server preference266*/267JNIEXPORT void JNICALL268JLI_SetPreferredJVM(const char *prefJVM) {269if (sPreferredJVMType != NULL) {270free(sPreferredJVMType);271sPreferredJVMType = NULL;272}273274if (prefJVM == NULL) return;275sPreferredJVMType = strdup(prefJVM);276}277278#ifdef TARGET_IOS279static jboolean awtLoaded = 0;280#else281static BOOL awtLoaded = NO;282#endif283static pthread_mutex_t awtLoaded_mutex = PTHREAD_MUTEX_INITIALIZER;284static pthread_cond_t awtLoaded_cv = PTHREAD_COND_INITIALIZER;285286JNIEXPORT void JNICALL287JLI_NotifyAWTLoaded()288{289pthread_mutex_lock(&awtLoaded_mutex);290#ifdef TARGET_IOS291awtLoaded = 1;292#else293awtLoaded = YES;294#endif295pthread_cond_signal(&awtLoaded_cv);296pthread_mutex_unlock(&awtLoaded_mutex);297}298299static int (*main_fptr)(int argc, char **argv) = NULL;300301/*302* Unwrap the arguments and re-run main()303*/304static void *apple_main (void *arg)305{306if (main_fptr == NULL) {307#ifdef STATIC_BUILD308extern int main(int argc, char **argv);309main_fptr = &main;310#else311main_fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");312#endif313if (main_fptr == NULL) {314JLI_ReportErrorMessageSys("error locating main entrypoint\n");315exit(1);316}317}318319struct NSAppArgs *args = (struct NSAppArgs *) arg;320exit(main_fptr(args->argc, args->argv));321}322323#ifndef TARGET_IOS324static void dummyTimer(CFRunLoopTimerRef timer, void *info) {}325326static void ParkEventLoop() {327// RunLoop needs at least one source, and 1e20 is pretty far into the future328CFRunLoopTimerRef t = CFRunLoopTimerCreate(kCFAllocatorDefault, 1.0e20, 0.0, 0, 0, dummyTimer, NULL);329CFRunLoopAddTimer(CFRunLoopGetCurrent(), t, kCFRunLoopDefaultMode);330CFRelease(t);331332// Park this thread in the main run loop.333int32_t result;334do {335result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, false);336} while (result != kCFRunLoopRunFinished);337}338#endif339340/*341* Mac OS X mandates that the GUI event loop run on very first thread of342* an application. This requires that we re-call Java's main() on a new343* thread, reserving the 'main' thread for Cocoa.344*/345static void MacOSXStartup(int argc, char *argv[]) {346// Thread already started?347static jboolean started = false;348if (started) {349return;350}351started = true;352353// Hand off arguments354struct NSAppArgs args;355args.argc = argc;356args.argv = argv;357358// Fire up the main thread359pthread_t main_thr;360if (pthread_create(&main_thr, NULL, &apple_main, &args) != 0) {361JLI_ReportErrorMessageSys("Could not create main thread: %s\n", strerror(errno));362exit(1);363}364if (pthread_detach(main_thr)) {365JLI_ReportErrorMessageSys("pthread_detach() failed: %s\n", strerror(errno));366exit(1);367}368369#ifndef TARGET_IOS370ParkEventLoop();371#endif372}373374void375CreateExecutionEnvironment(int *pargc, char ***pargv,376char jrepath[], jint so_jrepath,377char jvmpath[], jint so_jvmpath,378char jvmcfg[], jint so_jvmcfg) {379jboolean jvmpathExists;380381/* Compute/set the name of the executable */382SetExecname(*pargv);383384char * jvmtype = NULL;385int argc = *pargc;386char **argv = *pargv;387388/* Find out where the JRE is that we will be using. */389if (!GetJREPath(jrepath, so_jrepath, JNI_FALSE) ) {390JLI_ReportErrorMessage(JRE_ERROR1);391exit(2);392}393JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg",394jrepath, FILESEP, FILESEP);395/* Find the specified JVM type */396if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {397JLI_ReportErrorMessage(CFG_ERROR7);398exit(1);399}400401jvmpath[0] = '\0';402jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);403if (JLI_StrCmp(jvmtype, "ERROR") == 0) {404JLI_ReportErrorMessage(CFG_ERROR9);405exit(4);406}407408if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {409JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);410exit(4);411}412413/*414* Mac OS X requires the Cocoa event loop to be run on the "main"415* thread. Spawn off a new thread to run main() and pass416* this thread off to the Cocoa event loop.417*/418MacOSXStartup(argc, argv);419420/*421* we seem to have everything we need422*/423return;424}425426/*427* VM choosing is done by the launcher (java.c).428*/429static jboolean430GetJVMPath(const char *jrepath, const char *jvmtype,431char *jvmpath, jint jvmpathsize)432{433struct stat s;434435if (JLI_StrChr(jvmtype, '/')) {436JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype);437} else {438/*439* macosx client library is built thin, i386 only.440* 64 bit client requests must load server library441*/442JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtype);443}444445JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);446447#ifdef STATIC_BUILD448return JNI_TRUE;449#else450if (stat(jvmpath, &s) == 0) {451JLI_TraceLauncher("yes.\n");452return JNI_TRUE;453} else {454JLI_TraceLauncher("no.\n");455return JNI_FALSE;456}457#endif458}459460/*461* Find path to JRE based on .exe's location or registry settings.462*/463static jboolean464GetJREPath(char *path, jint pathsize, jboolean speculative)465{466char libjava[MAXPATHLEN];467468if (GetApplicationHome(path, pathsize)) {469/* Is JRE co-located with the application? */470#ifdef STATIC_BUILD471char jvm_cfg[MAXPATHLEN];472JLI_Snprintf(jvm_cfg, sizeof(jvm_cfg), "%s/lib/jvm.cfg", path);473if (access(jvm_cfg, F_OK) == 0) {474return JNI_TRUE;475}476#else477JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path);478if (access(libjava, F_OK) == 0) {479return JNI_TRUE;480}481#endif482/* ensure storage for path + /jre + NULL */483if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) {484JLI_TraceLauncher("Insufficient space to store JRE path\n");485return JNI_FALSE;486}487/* Does the app ship a private JRE in <apphome>/jre directory? */488JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path);489if (access(libjava, F_OK) == 0) {490JLI_StrCat(path, "/jre");491JLI_TraceLauncher("JRE path is %s\n", path);492return JNI_TRUE;493}494}495496/* try to find ourselves instead */497Dl_info selfInfo;498dladdr(&GetJREPath, &selfInfo);499500#ifdef STATIC_BUILD501char jvm_cfg[MAXPATHLEN];502char *p = NULL;503strncpy(jvm_cfg, selfInfo.dli_fname, MAXPATHLEN);504p = strrchr(jvm_cfg, '/'); *p = '\0';505p = strrchr(jvm_cfg, '/');506if (strcmp(p, "/.") == 0) {507*p = '\0';508p = strrchr(jvm_cfg, '/'); *p = '\0';509}510else *p = '\0';511strncpy(path, jvm_cfg, pathsize);512strncat(jvm_cfg, "/lib/jvm.cfg", MAXPATHLEN);513if (access(jvm_cfg, F_OK) == 0) {514return JNI_TRUE;515}516#endif517518char *realPathToSelf = realpath(selfInfo.dli_fname, path);519if (realPathToSelf != path) {520return JNI_FALSE;521}522523size_t pathLen = strlen(realPathToSelf);524if (pathLen == 0) {525return JNI_FALSE;526}527528const char lastPathComponent[] = "/lib/libjli.dylib";529size_t sizeOfLastPathComponent = sizeof(lastPathComponent) - 1;530if (pathLen < sizeOfLastPathComponent) {531return JNI_FALSE;532}533534size_t indexOfLastPathComponent = pathLen - sizeOfLastPathComponent;535if (0 == strncmp(realPathToSelf + indexOfLastPathComponent, lastPathComponent, sizeOfLastPathComponent)) {536realPathToSelf[indexOfLastPathComponent + 1] = '\0';537return JNI_TRUE;538}539540// If libjli.dylib is loaded from a macos bundle MacOS dir, find the JRE dir541// in ../Home.542const char altLastPathComponent[] = "/MacOS/libjli.dylib";543size_t sizeOfAltLastPathComponent = sizeof(altLastPathComponent) - 1;544if (pathLen < sizeOfLastPathComponent) {545return JNI_FALSE;546}547548size_t indexOfAltLastPathComponent = pathLen - sizeOfAltLastPathComponent;549if (0 == strncmp(realPathToSelf + indexOfAltLastPathComponent, altLastPathComponent, sizeOfAltLastPathComponent)) {550JLI_Snprintf(realPathToSelf + indexOfAltLastPathComponent, sizeOfAltLastPathComponent, "%s", "/Home");551if (access(realPathToSelf, F_OK) == 0) {552return JNI_TRUE;553}554}555556if (!speculative)557JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);558return JNI_FALSE;559}560561jboolean562LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)563{564Dl_info dlinfo;565void *libjvm;566567JLI_TraceLauncher("JVM path is %s\n", jvmpath);568569#ifndef STATIC_BUILD570libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);571#else572libjvm = dlopen(NULL, RTLD_FIRST);573#endif574if (libjvm == NULL) {575JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);576JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());577return JNI_FALSE;578}579580ifn->CreateJavaVM = (CreateJavaVM_t)581dlsym(libjvm, "JNI_CreateJavaVM");582if (ifn->CreateJavaVM == NULL) {583JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());584return JNI_FALSE;585}586587ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)588dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");589if (ifn->GetDefaultJavaVMInitArgs == NULL) {590JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());591return JNI_FALSE;592}593594ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)595dlsym(libjvm, "JNI_GetCreatedJavaVMs");596if (ifn->GetCreatedJavaVMs == NULL) {597JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());598return JNI_FALSE;599}600601return JNI_TRUE;602}603604/*605* Compute the name of the executable606*607* In order to re-exec securely we need the absolute path of the608* executable. On Solaris getexecname(3c) may not return an absolute609* path so we use dladdr to get the filename of the executable and610* then use realpath to derive an absolute path. From Solaris 9611* onwards the filename returned in DL_info structure from dladdr is612* an absolute pathname so technically realpath isn't required.613* On Linux we read the executable name from /proc/self/exe.614* As a fallback, and for platforms other than Solaris and Linux,615* we use FindExecName to compute the executable name.616*/617const char*618SetExecname(char **argv)619{620char* exec_path = NULL;621{622Dl_info dlinfo;623624#ifdef STATIC_BUILD625void *fptr;626fptr = (void *)&SetExecname;627#else628int (*fptr)();629fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");630#endif631if (fptr == NULL) {632JLI_ReportErrorMessage(DLL_ERROR3, dlerror());633return JNI_FALSE;634}635636if (dladdr((void*)fptr, &dlinfo)) {637char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);638if (resolved != NULL) {639exec_path = realpath(dlinfo.dli_fname, resolved);640if (exec_path == NULL) {641JLI_MemFree(resolved);642}643}644}645}646if (exec_path == NULL) {647exec_path = FindExecName(argv[0]);648}649execname = exec_path;650return exec_path;651}652653/* --- Splash Screen shared library support --- */654655static JavaVM* SetJavaVMValue()656{657JavaVM * jvm = NULL;658659// The handle is good for both the launcher and the libosxapp.dylib660void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);661if (handle) {662typedef JavaVM* (*JLI_GetJavaVMInstance_t)();663664JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance =665(JLI_GetJavaVMInstance_t)dlsym(handle,666"JLI_GetJavaVMInstance");667if (JLI_GetJavaVMInstance) {668jvm = JLI_GetJavaVMInstance();669}670671if (jvm) {672typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*);673674OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM =675(OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM");676if (OSXAPP_SetJavaVM) {677OSXAPP_SetJavaVM(jvm);678} else {679jvm = NULL;680}681}682683dlclose(handle);684}685686return jvm;687}688689static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");690691static void* hSplashLib = NULL;692693void* SplashProcAddress(const char* name) {694if (!hSplashLib) {695char jrePath[PATH_MAX];696if (!GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE)) {697JLI_ReportErrorMessage(JRE_ERROR1);698return NULL;699}700701char splashPath[PATH_MAX];702const int ret = JLI_Snprintf(splashPath, sizeof(splashPath),703"%s/lib/%s", jrePath, SPLASHSCREEN_SO);704if (ret >= (int)sizeof(splashPath)) {705JLI_ReportErrorMessage(JRE_ERROR11);706return NULL;707}708if (ret < 0) {709JLI_ReportErrorMessage(JRE_ERROR13);710return NULL;711}712713hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);714// It's OK if dlopen() fails. The splash screen library binary file715// might have been stripped out from the JRE image to reduce its size716// (e.g. on embedded platforms).717718if (hSplashLib) {719if (!SetJavaVMValue()) {720dlclose(hSplashLib);721hSplashLib = NULL;722}723}724}725if (hSplashLib) {726void* sym = dlsym(hSplashLib, name);727return sym;728} else {729return NULL;730}731}732733/*734* Signature adapter for pthread_create().735*/736static void* ThreadJavaMain(void* args) {737return (void*)(intptr_t)JavaMain(args);738}739740/*741* Block current thread and continue execution in a new thread.742*/743int744CallJavaMainInNewThread(jlong stack_size, void* args) {745int rslt;746pthread_t tid;747pthread_attr_t attr;748pthread_attr_init(&attr);749pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);750751if (stack_size > 0) {752pthread_attr_setstacksize(&attr, stack_size);753}754pthread_attr_setguardsize(&attr, 0); // no pthread guard page on java threads755756if (pthread_create(&tid, &attr, ThreadJavaMain, args) == 0) {757void* tmp;758pthread_join(tid, &tmp);759rslt = (int)(intptr_t)tmp;760} else {761/*762* Continue execution in current thread if for some reason (e.g. out of763* memory/LWP) a new thread can't be created. This will likely fail764* later in JavaMain as JNI_CreateJavaVM needs to create quite a765* few new threads, anyway, just give it a try..766*/767rslt = JavaMain(args);768}769770pthread_attr_destroy(&attr);771return rslt;772}773774static JavaVM* jvmInstance = NULL;775static jboolean sameThread = JNI_FALSE; /* start VM in current thread */776777/*778* Note there is a callback on this function from the splashscreen logic,779* this as well SetJavaVMValue() needs to be simplified.780*/781JNIEXPORT JavaVM* JNICALL782JLI_GetJavaVMInstance()783{784return jvmInstance;785}786787void788RegisterThread()789{790// stubbed out for windows and *nixes.791}792793static void794SetXDockArgForAWT(const char *arg)795{796char envVar[80];797if (strstr(arg, "-Xdock:name=") == arg) {798/*799* The APP_NAME_<pid> environment variable is used to pass800* an application name as specified with the -Xdock:name command801* line option from Java launcher code to the AWT code in order802* to assign this name to the app's dock tile on the Mac.803* The _<pid> part is added to avoid collisions with child processes.804*805* WARNING: This environment variable is an implementation detail and806* isn't meant for use outside of the core platform. The mechanism for807* passing this information from Java launcher to other modules may808* change drastically between update release, and it may even be809* removed or replaced with another mechanism.810*811* NOTE: It is used by SWT, and JavaFX.812*/813snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());814setenv(envVar, (arg + 12), 1);815}816817if (strstr(arg, "-Xdock:icon=") == arg) {818/*819* The APP_ICON_<pid> environment variable is used to pass820* an application icon as specified with the -Xdock:icon command821* line option from Java launcher code to the AWT code in order822* to assign this icon to the app's dock tile on the Mac.823* The _<pid> part is added to avoid collisions with child processes.824*825* WARNING: This environment variable is an implementation detail and826* isn't meant for use outside of the core platform. The mechanism for827* passing this information from Java launcher to other modules may828* change drastically between update release, and it may even be829* removed or replaced with another mechanism.830*831* NOTE: It is used by SWT, and JavaFX.832*/833snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());834setenv(envVar, (arg + 12), 1);835}836}837838static void839SetMainClassForAWT(JNIEnv *env, jclass mainClass) {840jclass classClass = NULL;841NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class"));842843jmethodID getCanonicalNameMID = NULL;844NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;"));845846jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID);847if ((*env)->ExceptionCheck(env) || NULL == mainClassString) {848/*849* Clears all errors caused by getCanonicalName() on the mainclass and850* leaves the JAVA_MAIN_CLASS__<pid> empty.851*/852(*env)->ExceptionClear(env);853return;854}855856const char *mainClassName = NULL;857NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL));858859char envVar[80];860/*861* The JAVA_MAIN_CLASS_<pid> environment variable is used to pass862* the name of a Java class whose main() method is invoked by863* the Java launcher code to start the application, to the AWT code864* in order to assign the name to the Apple menu bar when the app865* is active on the Mac.866* The _<pid> part is added to avoid collisions with child processes.867*868* WARNING: This environment variable is an implementation detail and869* isn't meant for use outside of the core platform. The mechanism for870* passing this information from Java launcher to other modules may871* change drastically between update release, and it may even be872* removed or replaced with another mechanism.873*874* NOTE: It is used by SWT, and JavaFX.875*/876snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid());877setenv(envVar, mainClassName, 1);878879(*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName);880}881882void883SetXStartOnFirstThreadArg()884{885// XXX: BEGIN HACK886// short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625>887// need a way to get AWT/Swing apps launched when spawned from Eclipse,888// which currently has no UI to not pass the -XstartOnFirstThread option889if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return;890// XXX: END HACK891892sameThread = JNI_TRUE;893// Set a variable that tells us we started on the main thread.894// This is used by the AWT during startup. (See LWCToolkit.m)895char envVar[80];896snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());897setenv(envVar, "1", 1);898}899900// MacOSX we may continue in the same thread901int902JVMInit(InvocationFunctions* ifn, jlong threadStackSize,903int argc, char **argv,904int mode, char *what, int ret) {905#ifndef TARGET_IOS906if (sameThread) {907JLI_TraceLauncher("In same thread\n");908// need to block this thread against the main thread909// so signals get caught correctly910__block int rslt = 0;911NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];912{913NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock: ^{914JavaMainArgs args;915args.argc = argc;916args.argv = argv;917args.mode = mode;918args.what = what;919args.ifn = *ifn;920rslt = JavaMain(&args);921}];922923/*924* We cannot use dispatch_sync here, because it blocks the main dispatch queue.925* Using the main NSRunLoop allows the dispatch queue to run properly once926* SWT (or whatever toolkit this is needed for) kicks off it's own NSRunLoop927* and starts running.928*/929[op performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];930}931[pool drain];932return rslt;933} else {934return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);935}936#else937return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);938#endif939}940941/*942* Note the jvmInstance must be initialized first before entering into943* ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance.944*/945void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) {946jvmInstance = vm;947SetMainClassForAWT(env, mainClass);948CHECK_EXCEPTION_RETURN();949ShowSplashScreen();950}951952jboolean953ProcessPlatformOption(const char* arg)954{955if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) {956SetXStartOnFirstThreadArg();957return JNI_TRUE;958} else if (JLI_StrCCmp(arg, "-Xdock:") == 0) {959SetXDockArgForAWT(arg);960return JNI_TRUE;961}962// arguments we know not963return JNI_FALSE;964}965966967