void CreateJavaVM(char *classpath, jint (JNICALL *printfn)(FILE *fp, const char *format, va_list args)) { #ifdef USE_JDK12 if (!gJavaVM && !gJavaEnv) { JavaVMOption options[2]; JavaVMInitArgs vm_args; int nOptions = 1; options[0].name = "classpath"; if (!classpath) options[0].value.p = getenv("CLASSPATH"); else options[0].value.p = classpath; if (printfn) { options[1].name = "vfprintf"; options[1].value.p = printfn; nOptions++; } vm_args.version = JNI_VERSION_1_2; vm_args.options = options; vm_args.nOptions = nOptions; vm_args.result = NULL; JNI_CreateJavaVM(&gJavaVM, (void **)&gJavaEnv, (void *)&vm_args); assert(gJavaVM && gJavaEnv); } #else if (!gJavaVM && !gJavaEnv) { JDK1_1InitArgs vm_args; JNI_GetDefaultJavaVMInitArgs(&vm_args); if (!classpath) vm_args.classpath = getenv("CLASSPATH"); else vm_args.classpath = classpath; if (printfn) vm_args.vfprintf = printfn; JNI_CreateJavaVM(&gJavaVM, &gJavaEnv, &vm_args); assert(gJavaVM && gJavaEnv); } #endif }
static JSBool default_create_java_vm(SystemJavaVM* *jvm, JNIEnv* *initialEnv, void* initargs) { jint err; const char* user_classpath = (const char*)initargs; char* full_classpath = NULL; /* No Java VM supplied, so create our own */ JDK1_1InitArgs vm_args; memset(&vm_args, 0, sizeof(vm_args)); /* Magic constant indicates JRE version 1.1 */ vm_args.version = 0x00010001; JNI_GetDefaultJavaVMInitArgs(&vm_args); /* Prepend the classpath argument to the default JVM classpath */ if (user_classpath) { #if defined(XP_UNIX) || defined(XP_BEOS) full_classpath = JS_smprintf("%s:%s", user_classpath, vm_args.classpath); #else full_classpath = JS_smprintf("%s;%s", user_classpath, vm_args.classpath); #endif if (!full_classpath) { return JS_FALSE; } vm_args.classpath = (char*)full_classpath; } err = JNI_CreateJavaVM((JavaVM**)jvm, initialEnv, &vm_args); if (full_classpath) JS_smprintf_free(full_classpath); return err == 0; }
int main(void) { JavaVMInitArgs vmargs; JavaVM *vm; void *env; JavaVMOption myoptions[1]; /* set up libtool/libltdl dlopen emulation */ LTDL_SET_PRELOADED_SYMBOLS(); myoptions[0].optionString = concatString("-Xbootclasspath:", getenv("BOOTCLASSPATH")); vmargs.version = JNI_VERSION_1_2; if (JNI_GetDefaultJavaVMInitArgs (&vmargs) < 0) { fprintf(stderr, " Cannot retrieve default arguments\n"); return 1; } vmargs.nOptions = 1; vmargs.options = myoptions; if (JNI_CreateJavaVM (&vm, &env, &vmargs) < 0) { fprintf(stderr, " Cannot create the Java VM\n"); return 1; } (*vm)->DestroyJavaVM(vm); return 0; }
JavaInterface::JavaInterface( const char *pzComponentPath, const char *pzComponentSettings) : BaseInterface(pzComponentPath, pzComponentSettings) { if (m_jvm) return; JNIEnv *env; #ifdef _WIN32 MS_JDK1_1InitArgs vm_args; JNI_GetDefaultJavaVMInitArgs(&vm_args); vm_args.nVersion = 0x00010001; vm_args.pcszClasspath = (char *)(const char *)m_strComponentPath; int nRet = JNI_CreateJavaVM(&m_jvm, &env, &vm_args); if (nRet < 0) { throw GException("JavaIntegration", 1,nRet); } #else #ifdef _DYNAMIC_JAVA_LINK_ JavaVMInitArgs vm_args; void *dllHandle = _OPENLIB("libjvm.so"); if (dllHandle) { JavaVMOption options[3]; GString strTemp; strTemp.Format("-Djava.class.path=%s",(const char *)m_strComponentPath); options[0].optionString = "-Djava.compiler=NONE"; // disable JIT options[1].optionString = (char *)(const char *)strTemp; vm_args.options = options; vm_args.version = JNI_VERSION_1_2; vm_args.nOptions = 2; vm_args.ignoreUnrecognized = JNI_FALSE; void *pfn2 = 0; ExceptionHandlerScope duration; XML_TRY { pfn2 = (void *)_PROCADDRESS(dllHandle, "JNI_CreateJavaVM"); } XML_CATCH(ex) { throw GException("JavaIntegration", 6, getenv("LD_LIBRARY_PATH")); } if (pfn2) { cout << "Creating VM\n"; int nRet = ((fnJNI_CreateJavaVM)pfn2)(&m_jvm, (void **) &env, &vm_args); if (nRet < 0) { throw GException("JavaIntegration", 1,nRet); } else { cout << "Created Java Interpreter\n"; } } } else { throw GException("JavaIntegration", 5, getenv("LD_LIBRARY_PATH"));
int init_testing_framework () { JavaVM *jvm; JDK1_1InitArgs vm_args; vm_args.version = 0x00010001; JNI_GetDefaultJavaVMInitArgs (&vm_args); vm_args.classpath = getenv ("CLASSPATH"); if (JNI_CreateJavaVM (&jvm, &env, &vm_args) < 0) return -1; test_class = (*env)->FindClass (env, "gnu/test/Test"); if (test_class == NULL) { fprintf (stderr, "Unable to locate gnu.test.Test\n"); return -1; } test_class = (*env)->NewGlobalRef (env, test_class); result_class = (*env)->FindClass (env, "gnu/test/Result"); if (result_class == NULL) { fprintf (stderr, "Unable to locate gnu.test.Result\n"); return -1; } result_class = (*env)->NewGlobalRef (env, result_class); test_mid = (*env)->GetMethodID (env, test_class, "test", "()Lgnu/test/Result;"); test_name_mid = (*env)->GetMethodID (env, test_class, "getName", "()Ljava/lang/String;"); if (test_mid == NULL || test_name_mid == NULL) { fprintf (stderr, "Malformed gnu.test.Test class\n"); return -1; } result_name_mid = (*env)->GetMethodID (env, result_class, "getName", "()Ljava/lang/String;"); result_msg_mid = (*env)->GetMethodID (env, result_class, "getMsg", "()Ljava/lang/String;"); if (result_name_mid == NULL || result_msg_mid == NULL) { fprintf (stderr, "Malformed gnu.test.Result class\n"); return -1; } gh_new_procedure1_0 ("test", perform_test); return 0; }
/* * This method will attach the current JavaRTI to the JVM, storing a reference * to the JNIEnv in the instance variable. If there is an error during this * process, an RTIinternalError will be thrown. */ void JavaRTI::attachToJVM() throw( HLA::RTIinternalError ) { logger->debug( "Attaching to JVM" ); JavaVMInitArgs vmArgs; JNI_GetDefaultJavaVMInitArgs( &vmArgs ); jint result = Runtime::getRuntime()->jvm->AttachCurrentThread( (void**)&jnienv, &vmArgs ); if( result == 0 ) { logger->info( "Attached to JVM" ); } else { logger->fatal( "Couldn't attach to JVM" ); throw HLA::RTIinternalError( "couldn't attach to JVM" ); } }
static void init_const_AJavaVM(){ JDK1_1InitArgs vm_args; jint res; JNI_GetDefaultJavaVMInitArgs(&vm_args); vm_args.version = 0x00010001; vm_args.classpath = getenv("CLASSPATH"); vm_args.minHeapSize = 2 * MEGABYTE; vm_args.maxHeapSize = 48 * MEGABYTE; /* vm_args.nativeStackSize = 4 * MEGABYTE; */ /* vm_args.javaStackSize = 2 * MEGABYTE; */ vm_args.checkSource = 0; vm_args.verifyMode = 0; vm_args.exit = vmExits; vm_args.abort = vmAborts; vm_args.enableClassGC = 1; vm_args.disableAsyncGC = 0; vm_args.enableVerboseGC = 0; res = JNI_CreateJavaVM(&jvm,&javabind_env,&vm_args); if (res < 0) { HLT("Can't create Java VM"); } javabind_last_exception = NULL; javabind_exception_ans = declare_failure_answer("JavaVM exception"); javabind_class_java_lang_String = javabind_FindClass("java/lang/String"); javabind_class_java_lang_Object = javabind_FindClass("java/lang/Object"); javabind_class_java_lang_Class = javabind_FindClass("java/lang/Class"); javabind_equals_method = javabind_GetMethodID(javabind_class_java_lang_Object, "equals", "(Ljava/lang/Object;)Z"); if (javabind_equals_method == NULL){ HLT("cannot bind Object.equals"); } javabind_getName_method = javabind_GetMethodID(javabind_class_java_lang_Class, "getName", "()Ljava/lang/String;"); if (javabind_getName_method == NULL){ HLT("cannot bind Class.getNames"); } }
//@{ bool java_initialize() { JNIEnv *environment; JavaVMInitArgs arguments; jint result; // Obtain default arguments parameter for a Java 1.6 virtual machine. memset(&arguments, 0, sizeof(arguments)); arguments.version = JNI_REQUIRED; result = JNI_GetDefaultJavaVMInitArgs(&arguments); if(result != JNI_OK) return false; // Create a Java 1.6 virtual machine. result = JNI_CreateJavaVM(&virtual_machine, (void**)&environment, &arguments); if(result != JNI_OK) return false; // Detach the current thread from the virtual machine and return. java_detach(); return true; }
main(int argc, char **argv) { JNIEnv *env; int i, rc, numJavaThreads; jsize numJVM; JavaVM **jvmBuf; jint res; jclass cls; jmethodID mid; jstring jstr; jclass stringClass; jobjectArray args; jfieldID fid; pthread_t first_th; pthread_t second_th; /*************************************************** * Test JNI_CreateJavaVM */ #ifdef JNI_VERSION_1_2 JavaVMInitArgs vm_args; JavaVMOption options[1]; options[0].optionString = "-Djava.class.path=" USER_CLASSPATH; vm_args.version = 0x00010002; vm_args.options = options; vm_args.nOptions = 1; vm_args.ignoreUnrecognized = TRUE; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); #else JDK1_1InitArgs vm_args; char classpath[1024]; vm_args.version = 0x00010001; JNI_GetDefaultJavaVMInitArgs(&vm_args); /* Append USER_CLASSPATH to the default system class path */ /* sprintf(classpath, "%s%c%s", vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH); */ sprintf(classpath,"%s", USER_CLASSPATH); /* just hardcode the path for now */ vm_args.classpath = classpath; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, &env, &vm_args); #endif /* JNI_VERSION_1_2 */ main_pass = 1; thread_pass = 1; verbose_mode = 0; if (argc > 1) { /* argv++; */ if (!strcmp(argv[1], "-verbose")) { verbose_mode = 1; } } if (res < 0) { fprintf(stderr, "FAIL: AttachJVM, cannot create Java VM from C\n"); exit(1); } else { if (verbose_mode) printf("C: JVM created, now spawning threads ...\n"); } /*************************************************** * Now with a JNIEnv, try a few JNI functions */ cls = (*env)->FindClass(env, "myMain"); if (cls == 0) { if (verbose_mode) printf("ERROR: cannot find class myMain\n"); main_pass = 0; goto destroy; } else { if (verbose_mode) printf("FindClass returns %d \n", cls); } mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V"); if (mid == 0) { if (verbose_mode) printf("ERROR: GetStaticMethodID fails\n"); main_pass = 0; goto destroy; } else { if (verbose_mode) printf("GetStaticMethodID returns %d\n", mid); } jstr = (*env)->NewStringUTF(env, " main thread from C!"); if (jstr == 0) { if (verbose_mode) printf("ERROR: NewStringUTF fails\n"); main_pass = 0; goto destroy; } else { if (verbose_mode) printf("NewStringUTF returns %d\n", jstr); } stringClass = (*env)->FindClass(env, "java/lang/String"); args = (*env)->NewObjectArray(env, 1, stringClass, jstr); if (args == 0) { if (verbose_mode) printf("ERROR: NewObjectArray fails\n"); main_pass = 0; goto destroy; } else { if (verbose_mode) printf("NewObjectArray returns %d\n", args); } (*env)->CallStaticVoidMethod(env, cls, mid, args); if ((*env)->ExceptionOccurred(env)) { if (verbose_mode) { printf("ERROR: CallStaticVoidMethod fails\n"); (*env)->ExceptionDescribe(env); } main_pass = 0; } else { if (verbose_mode) printf("CallStaticVoidMethod succeeds.\n"); } /*************************************************** * Now create the threads and let them do some more Java work * pass the thread number to every thread */ pthread_create(&first_th, NULL, thread_fun, (void *) 0); pthread_create(&second_th, NULL, thread_fun, (void *) 1); /* wait for the pthreads to finish */ pthread_join(first_th, NULL); pthread_join(second_th, NULL); /* sleep(60); */ if (verbose_mode) printf("C: threads are done, taking down JVM.\n"); /*************************************************** * Test GetCreatedJVMs */ numJVM = 0; jvmBuf = (JavaVM **) malloc(sizeof(JavaVM *) * BUFLEN); rc = JNI_GetCreatedJavaVMs(jvmBuf, BUFLEN, &numJVM); if (rc!=0) { if (verbose_mode) printf("AttachJVM: ERROR calling GetCreatedJavaVMs\n"); main_pass = 0; } else { if (numJVM>1) { if (verbose_mode) printf("AttachJVM: ERROR GetCreatedJavaVMs returns more than one JVM instance\n"); main_pass = 0; } else if (numJVM==0) { if (verbose_mode) printf("AttachJVM: ERROR GetCreatedJavaVMs returns none \n"); main_pass = 0; } else if (jvmBuf[0]==jvm) { if (verbose_mode) printf("AttachJVM: GetCreatedJavaVMs succeeds\n"); } } /*************************************************** * Test DestroyJavaVM */ destroy: rc = (*jvm)->DestroyJavaVM(jvm); if (rc!=0) { if (verbose_mode) printf("C: DestroyJavaVM returns with -1 as expected \n"); } else { if (verbose_mode) printf("C: Unexpected return value from DestroyJavaVM\n"); main_pass = 0; } /*************************************************** * Check tests */ for (i=0; i<NUM_THREAD; i++) { if (threads_result[i]==0) thread_pass = 0; } if (main_pass && thread_pass) fprintf(stdout, "PASS: AttachJVM\n"); else fprintf(stdout, "FAIL: AttachJVM\n"); }
_DLL_EXPORT PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwnames[] = { "classpath", "initialheap", "maxheap", "maxstack", "vmargs", NULL }; char *classpath = NULL; char *initialheap = NULL, *maxheap = NULL, *maxstack = NULL; PyObject *vmargs = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zzzzO", kwnames, &classpath, &initialheap, &maxheap, &maxstack, &vmargs)) return NULL; if (env->vm) { PyObject *module_cp = NULL; if (initialheap || maxheap || maxstack || vmargs) { PyErr_SetString(PyExc_ValueError, "JVM is already running, options are ineffective"); return NULL; } if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp != NULL) classpath = PyString_AsString(module_cp); } if (classpath && classpath[0]) env->setClassPath(classpath); Py_XDECREF(module_cp); return getVMEnv(self); } else { JavaVMInitArgs vm_args; JavaVMOption vm_options[32]; JNIEnv *vm_env; JavaVM *vm; unsigned int nOptions = 0; PyObject *module_cp = NULL; vm_args.version = JNI_VERSION_1_4; JNI_GetDefaultJavaVMInitArgs(&vm_args); if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp != NULL) classpath = PyString_AsString(module_cp); } #ifdef _jcc_lib PyObject *jcc = PyImport_ImportModule("jcc"); PyObject *cp = PyObject_GetAttrString(jcc, "CLASSPATH"); if (classpath) add_paths("-Djava.class.path=", PyString_AsString(cp), classpath, &vm_options[nOptions++]); else add_option("-Djava.class.path=", PyString_AsString(cp), &vm_options[nOptions++]); Py_DECREF(cp); Py_DECREF(jcc); #else if (classpath) add_option("-Djava.class.path=", classpath, &vm_options[nOptions++]); #endif Py_XDECREF(module_cp); if (initialheap) add_option("-Xms", initialheap, &vm_options[nOptions++]); if (maxheap) add_option("-Xmx", maxheap, &vm_options[nOptions++]); if (maxstack) add_option("-Xss", maxstack, &vm_options[nOptions++]); if (vmargs != NULL && PyString_Check(vmargs)) { #ifdef _MSC_VER char *buf = _strdup(PyString_AS_STRING(vmargs)); #else char *buf = strdup(PyString_AS_STRING(vmargs)); #endif char *sep = ","; char *option; for (option = strtok(buf, sep); option != NULL; option = strtok(NULL, sep)) { if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { free(buf); for (unsigned int i = 0; i < nOptions; i++) delete vm_options[i].optionString; PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); return NULL; } } free(buf); } else if (vmargs != NULL && PySequence_Check(vmargs)) { PyObject *fast = PySequence_Fast(vmargs, "error converting vmargs to a tuple"); if (fast == NULL) return NULL; for (int i = 0; i < PySequence_Fast_GET_SIZE(fast); ++i) { PyObject *arg = PySequence_Fast_GET_ITEM(fast, i); if (PyString_Check(arg)) { char *option = PyString_AS_STRING(arg); if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { for (unsigned int j = 0; j < nOptions; j++) delete vm_options[j].optionString; PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); Py_DECREF(fast); return NULL; } } else { for (unsigned int j = 0; j < nOptions; j++) delete vm_options[j].optionString; PyErr_Format(PyExc_TypeError, "vmargs arg %d is not a string", i); Py_DECREF(fast); return NULL; } } Py_DECREF(fast); } else if (vmargs != NULL) { PyErr_SetString(PyExc_TypeError, "vmargs is not a string or sequence"); return NULL; } //vm_options[nOptions++].optionString = "-verbose:gc"; //vm_options[nOptions++].optionString = "-Xcheck:jni"; vm_args.nOptions = nOptions; vm_args.ignoreUnrecognized = JNI_FALSE; vm_args.options = vm_options; if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0) { for (unsigned int i = 0; i < nOptions; i++) delete vm_options[i].optionString; PyErr_Format(PyExc_ValueError, "An error occurred while creating Java VM"); return NULL; } env->set_vm(vm, vm_env); for (unsigned int i = 0; i < nOptions; i++) delete vm_options[i].optionString; t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv).tp_alloc(&PY_TYPE(JCCEnv), 0); jccenv->env = env; #ifdef _jcc_lib registerNatives(vm_env); #endif return (PyObject *) jccenv; } }
static void uwsgi_jvm_create(void) { ujvm.vm_args.version = JNI_VERSION_1_2; JNI_GetDefaultJavaVMInitArgs(&ujvm.vm_args); JavaVMOption *options; struct uwsgi_string_list *usl = ujvm.opts; int opt_count = 1; while(usl) { opt_count++; usl = usl->next; } options = uwsgi_calloc(sizeof(JavaVMOption) * opt_count); options[0].optionString = "-Djava.class.path=."; char *old_cp = NULL ; struct uwsgi_string_list *cp = ujvm.classpath; while(cp) { if (old_cp) { options[0].optionString = uwsgi_concat3(old_cp, ":", cp->value); free(old_cp); } else { options[0].optionString = uwsgi_concat3(options[0].optionString, ":", cp->value); } old_cp = options[0].optionString ; cp = cp->next; } usl = ujvm.opts; opt_count = 1; while(usl) { options[opt_count].optionString = usl->value; opt_count++; usl = usl->next; } ujvm.vm_args.options = options; ujvm.vm_args.nOptions = opt_count; JNIEnv *env; if (pthread_key_create(&ujvm.env, NULL)) { uwsgi_error("pthread_key_create()"); exit(1); } if (JNI_CreateJavaVM(&ujvm.vm, (void **) &env, &ujvm.vm_args)) { uwsgi_log("unable to initialize the JVM\n"); exit(1); } pthread_setspecific(ujvm.env, env); char *java_version = NULL; jvmtiEnv *jvmti; if ((*ujvm.vm)->GetEnv(ujvm.vm, (void **)&jvmti, JVMTI_VERSION) == JNI_OK) { (*jvmti)->GetSystemProperty(jvmti, "java.vm.version", &java_version); } if (uwsgi.mywid > 0) { if (java_version) { uwsgi_log("JVM %s initialized at %p (worker: %d pid: %d)\n", java_version, ujvm_env, uwsgi.mywid, (int) uwsgi.mypid); } else { uwsgi_log("JVM initialized at %p (worker: %d pid: %d)\n", ujvm_env, uwsgi.mywid, (int) uwsgi.mypid); } } ujvm.str_class = uwsgi_jvm_class("java/lang/String"); if (!ujvm.str_class) exit(1); ujvm.str_array_class = uwsgi_jvm_class("[Ljava/lang/String;"); if (!ujvm.str_array_class) exit(1); ujvm.int_class = uwsgi_jvm_class("java/lang/Integer"); if (!ujvm.int_class) exit(1); ujvm.bool_class = uwsgi_jvm_class("java/lang/Boolean"); if (!ujvm.bool_class) exit(1); ujvm.long_class = uwsgi_jvm_class("java/lang/Long"); if (!ujvm.long_class) exit(1); ujvm.byte_class = uwsgi_jvm_class("java/lang/Byte"); if (!ujvm.byte_class) exit(1); ujvm.bytearray_class = uwsgi_jvm_class("[B"); if (!ujvm.bytearray_class) exit(1); ujvm.file_class = uwsgi_jvm_class("java/io/File"); if (!ujvm.file_class) exit(1); ujvm.input_stream_class = uwsgi_jvm_class("java/io/InputStream"); if (!ujvm.input_stream_class) exit(1); ujvm.hashmap_class = uwsgi_jvm_class("java/util/HashMap"); if (!ujvm.hashmap_class) exit(1); ujvm.list_class = uwsgi_jvm_class("java/util/ArrayList"); if (!ujvm.list_class) exit(1); ujvm.set_class = uwsgi_jvm_class("java/util/Set"); if (!ujvm.set_class) exit(1); ujvm.iterator_class = uwsgi_jvm_class("java/util/Iterator"); if (!ujvm.iterator_class) exit(1); ujvm.runtime_exception = uwsgi_jvm_class("java/lang/RuntimeException"); if (!ujvm.runtime_exception) exit(1); ujvm.io_exception = uwsgi_jvm_class("java/io/IOException"); if (!ujvm.io_exception) exit(1); jclass uwsgi_class = uwsgi_jvm_class("uwsgi"); if (!uwsgi_class) { exit(1); } /* start filling uwsgi.opt */ jfieldID opt_fid = (*ujvm_env)->GetStaticFieldID(ujvm_env, uwsgi_class, "opt", "Ljava/util/HashMap;"); if (uwsgi_jvm_exception()) { exit(1); } jobject opt_hm = uwsgi_jvm_hashmap(); int j; for (j = 0; j < uwsgi.exported_opts_cnt; j++) { jstring j_opt_key = uwsgi_jvm_str(uwsgi.exported_opts[j]->key, 0); if (uwsgi_jvm_hashmap_has(opt_hm, (jobject) j_opt_key)) { jobject j_opt_value = uwsgi_jvm_hashmap_get(opt_hm, (jobject) j_opt_key); if (uwsgi_jvm_object_is_instance(j_opt_value, ujvm.list_class)) { if (uwsgi.exported_opts[j]->value == NULL) { uwsgi_jvm_list_add(j_opt_value, uwsgi_jvm_bool(JNI_TRUE)); } else { uwsgi_jvm_list_add(j_opt_value, uwsgi_jvm_str(uwsgi.exported_opts[j]->value, 0)); } } else { jobject ll = uwsgi_jvm_list(); uwsgi_jvm_list_add(ll, j_opt_value); if (uwsgi.exported_opts[j]->value == NULL) { uwsgi_jvm_list_add(ll, uwsgi_jvm_bool(JNI_TRUE)); } else { uwsgi_jvm_list_add(ll, uwsgi_jvm_str(uwsgi.exported_opts[j]->value, 0)); } uwsgi_jvm_hashmap_put(opt_hm, j_opt_key, ll); } } else { if (uwsgi.exported_opts[j]->value == NULL) { uwsgi_jvm_hashmap_put(opt_hm, j_opt_key, uwsgi_jvm_bool(JNI_TRUE)); } else { uwsgi_jvm_hashmap_put(opt_hm, j_opt_key, uwsgi_jvm_str(uwsgi.exported_opts[j]->value, 0)); } } } (*ujvm_env)->SetStaticObjectField(ujvm_env, uwsgi_class, opt_fid, opt_hm); (*ujvm_env)->RegisterNatives(ujvm_env, uwsgi_class, uwsgi_jvm_api_methods, sizeof(uwsgi_jvm_api_methods)/sizeof(uwsgi_jvm_api_methods[0])); if (uwsgi_jvm_exception()) { exit(1); } jclass uwsgi_signal_handler_class = uwsgi_jvm_class("uwsgi$SignalHandler"); if (!uwsgi_signal_handler_class) exit(1); ujvm.api_signal_handler_mid = uwsgi_jvm_get_method_id(uwsgi_signal_handler_class, "function", "(I)V"); if (!ujvm.api_signal_handler_mid) exit(1); jclass uwsgi_rpc_function_class = uwsgi_jvm_class("uwsgi$RpcFunction"); if (!uwsgi_rpc_function_class) exit(1); ujvm.api_rpc_function_mid = uwsgi_jvm_get_method_id(uwsgi_rpc_function_class, "function", "([Ljava/lang/String;)Ljava/lang/String;"); if (!ujvm.api_rpc_function_mid) exit(1); ujvm.request_body_class = uwsgi_jvm_class("uwsgi$RequestBody"); if (!ujvm.request_body_class) exit(1); (*ujvm_env)->RegisterNatives(ujvm_env, ujvm.request_body_class, uwsgi_jvm_request_body_methods, sizeof(uwsgi_jvm_request_body_methods)/sizeof(uwsgi_jvm_request_body_methods[0])); if (uwsgi_jvm_exception()) { exit(1); } usl = ujvm.main_classes; while(usl) { jclass c = uwsgi_jvm_class(usl->value); if (!c) { exit(1); } jmethodID mid = uwsgi_jvm_get_static_method_id_quiet(c, "main", "([Ljava/lang/String;)V"); if (mid) { jobject j_args = (*ujvm_env)->NewObjectArray(ujvm_env, 0, ujvm.str_class, NULL); if (uwsgi_jvm_call_static(c, mid, j_args)) { exit(1); } uwsgi_jvm_local_unref(j_args); } else { mid = uwsgi_jvm_get_static_method_id(c, "main", "()V"); if (!mid) { uwsgi_log("unable to find main() method in class \"%s\"\n", usl->value); exit(1); } if (uwsgi_jvm_call_static(c, mid)) { exit(1); } } usl = usl->next; } usl = ujvm.classes; while(usl) { uwsgi_jvm_class(usl->value); usl = usl->next; } // load request_handlers setup functions int i; for(i=0;i<UMAX8;i++) { if (ujvm.request_handlers_setup[i]) { ujvm.request_handlers_setup[i](); } } }
// begin(fix)(2009/11/30) // modified by sekikawa bool CJNIUtil::createJavaVM(char *confFile) { if (m_jvm) { return true; } JavaVMOption *options = NULL; JavaVMInitArgs vm_args; const char *pJavaClassPath = NULL; const char *pJavaLibraryPath = NULL; char javaClassPath[1024]; char javaLibraryPath[1024]; int iOption, nOptions; int nOtherOptions; jint ret; memset(javaClassPath, 0, sizeof(javaClassPath)); memset(javaLibraryPath, 0, sizeof(javaLibraryPath)); Sgv::ConfigFile conf; if (!conf.load(confFile)) { CX3DParser::printLog("Failed to load config file (%s)\n", confFile); return false; } nOptions = 0; pJavaClassPath = conf.getStringValue("java.class.path"); if (pJavaClassPath) { sprintf(javaClassPath, "-Djava.class.path=%s", pJavaClassPath); nOptions++; } pJavaLibraryPath = conf.getStringValue("java.library.path"); if (pJavaLibraryPath) { sprintf(javaLibraryPath, "-Djava.library.path=%s", pJavaLibraryPath); nOptions++; } nOtherOptions = conf.countOtherOptions(); nOptions += nOtherOptions; options = (JavaVMOption *)malloc(sizeof(JavaVMOption) * nOptions); if (!options) { CX3DParser::printLog("Failed to alloc memory for setting JavaVM Options.\n"); return false; } iOption = 0; if (strlen(javaClassPath) > 0) { options[iOption++].optionString = javaClassPath; } if (strlen(javaLibraryPath) > 0) { options[iOption++].optionString = javaLibraryPath; } for (int iOtherOption=0; iOtherOption<nOtherOptions; iOtherOption++) { options[iOption].optionString = (char *)conf.getOtherOption(iOtherOption); iOption++; } CX3DParser::printLog("*** JavaVMOption ***\n"); for (int i=0; i<nOptions; i++) { CX3DParser::printLog("options[%d].optionString = (%s)\n", i, options[i].optionString); } // ----------------------------------------------- // fill in startup structure // ----------------------------------------------- vm_args.version = JNI_VERSION_1_2; JNI_GetDefaultJavaVMInitArgs(&vm_args); vm_args.options = options; vm_args.nOptions = nOptions; // ----------------------------------------------- // ----------------------------------------------- ret = JNI_CreateJavaVM(&m_jvm, (void **)&m_env, &vm_args); if (ret < 0) { CX3DParser::printLog("Failed to create Java VM\n"); return false; } CX3DParser::printLog("Java VM start ok\n"); // ----------------------------------------------- // ----------------------------------------------- free(options); options = NULL; return true; }
/* * MAIN */ int main(int argc, char* argv[]) { int farg; const char* cp; void* env; #if defined(MAIN_MD) MAIN_MD; #endif #if defined(HAVE_LC_MESSAGES) setlocale(LC_MESSAGES, ""); setlocale(LC_CTYPE, ""); #endif #if defined(HAVE_GETTEXT) bindtextdomain(PACKAGE, KAFFE_LOCALEDIR); textdomain(PACKAGE); #endif vmargs.version = JNI_VERSION_1_1; #if defined(KAFFE_PROFILER) profFlag = 0; #endif JNI_GetDefaultJavaVMInitArgs(&vmargs); /* set up libtool/libltdl dlopen emulation */ LTDL_SET_PRELOADED_SYMBOLS(); #if defined(KAFFE_VMDEBUG) cp = getenv("KAFFE_VMDEBUG"); if (cp != 0) dbgSetMaskStr(cp); #endif cp = getenv(BOOTCLASSPATH); vmargs.bootClasspath = cp; cp = getenv(CLASSPATH1); if (cp == 0) { cp = getenv(CLASSPATH2); #if defined(DEFAULT_CLASSPATH) if (cp == 0) { cp = DEFAULT_CLASSPATH; } #endif } vmargs.classpath = (cp == NULL? NULL :strdup(cp)); cp = getenv(LIBRARYPATH1); if (cp == 0) { cp = getenv(LIBRARYPATH2); } vmargs.libraryhome = cp; cp = getenv(KAFFEHOME); if (cp == 0) { #if defined(DEFAULT_KAFFEHOME) cp = DEFAULT_KAFFEHOME; #endif } vmargs.classhome = cp; /* Process program options */ farg = options(argv, argc); argc = argc - farg; #if defined(KAFFE_XPROFILER) if( xProfFlag ) { if( !enableXCallGraph() && !enableXProfiling() ) { fprintf(stderr, "Unable to initialize cross " "language profiling\n"); xProfFlag = 0; } } #endif /* Get the class name to start with */ if (argv[farg] == 0) { usage(); exit(EXIT_FAILURE); } if (strcmp(argv[farg] + strlen(argv[farg]) - strlen(".class"), ".class") == 0) { fprintf(stderr, "Please do not specify the .class extension\n"); exit(EXIT_FAILURE); } /* Initialise */ if (JNI_CreateJavaVM(&global_vm, &env, &vmargs) < 0) { fprintf(stderr, "Cannot create the Java VM\n"); exit(EXIT_FAILURE); } return main2(env, argv, farg, argc); }
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ JNIEnv *env; JavaVM *jvm; jint res; jclass cls; jmethodID mid; jstring jstr; jclass stringClass; jobjectArray args; #ifdef JNI_VERSION_1_2 JavaVMInitArgs vm_args; JavaVMOption options[1]; options[0].optionString = "-Djava.class.path=" USER_CLASSPATH; vm_args.version = 0x00010002; vm_args.options = options; vm_args.nOptions = 1; vm_args.ignoreUnrecognized = JNI_TRUE; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); #else JDK1_1InitArgs vm_args; char classpath[1024]; vm_args.version = 0x00010001; JNI_GetDefaultJavaVMInitArgs(&vm_args); /* Append USER_CLASSPATH to the default system class path */ sprintf(classpath, "%s%c%s", vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH); vm_args.classpath = classpath; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, &env, &vm_args); #endif /* JNI_VERSION_1_2 */ if (res < 0) { fprintf(stderr, "Can't create Java VM\n"); exit(1); } cls = (*env)->FindClass(env, "cat/AccountPanel"); if (cls == NULL) { goto destroy; } mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V"); if (mid == NULL) { goto destroy; } /*jstr = (*env)->NewStringUTF(env, " from C!"); if (jstr == NULL) { goto destroy; } stringClass = (*env)->FindClass(env, "java/lang/String"); args = (*env)->NewObjectArray(env, 1, stringClass, jstr); if (args == NULL) { goto destroy; }*/ (*env)->CallStaticVoidMethod(env, cls, mid, NULL); destroy: if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionDescribe(env); } (*jvm)->DestroyJavaVM(jvm); }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { char *msg = NULL; #ifdef JNI_VERSION_1_2 JavaVMInitArgs vm_args; JavaVMOption options[1]; options[0].optionString = "-Djava.class.path=" USER_CLASSPATH; vm_args.version = 0x00010002; vm_args.options = options; vm_args.nOptions = 1; vm_args.ignoreUnrecognized = JNI_TRUE; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); #else JDK1_1InitArgs vm_args; char classpath[1024]; vm_args.version = 0x00010001; JNI_GetDefaultJavaVMInitArgs(&vm_args); /* Append USER_CLASSPATH to the default system class path */ sprintf(classpath, "%s%c%s", vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH); vm_args.classpath = classpath; /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, &env, &vm_args); #endif /* JNI_VERSION_1_2 */ if (res < 0) { PlaySound( "err.wav", NULL, SND_FILENAME | SND_ASYNC); MessageBox( NULL, "No se pudo crear la maquina virtual.", "Error fatal.", MB_OK| MB_ICONEXCLAMATION) ; return (1); } cls = env->FindClass("system/Cargador"); if (cls != NULL) { mid = env->GetMethodID(cls,"<init>","()V"); if (mid != NULL) { FILE *fichero; fichero = fopen( file, "r" ); if( fichero ){ //tambien funciona mal obj = env->AllocObject( cls ); objg = env->NewGlobalRef(obj); env->CallNonvirtualVoidMethod(objg,cls,mid); /*funciona mal obj = env->NewObject(cls,mid); objg = env->NewGlobalRef(obj); env->CallVoidMethod(cls, mid ); */ }else{ MessageBox( NULL, "Para registrarse ejecute la aplicación\nregistro.exe", "No se encuentra la licencia", MB_OK| MB_ICONEXCLAMATION) ; return (0); } }else{ msg = "No se encontro el metodo\nde inicio."; } }else{ msg = "No se encontro la clase de\ninicio."; } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); } if( msg != NULL ){ jvm->DestroyJavaVM(); // kill jvm //PlaySound( "err.wav", NULL, SND_FILENAME | SND_ASYNC); MessageBox( NULL, msg, "Error fatal", MB_OK| MB_ICONEXCLAMATION ) ; } MSG msga; hInst = hInstance; // Store instance handle in our global variable while (GetMessage (&msga, NULL, 0, 0)) { TranslateMessage (&msga); DispatchMessage (&msga); } return (0); }
/* Initialize the JVM and its environment, loading libraries and all */ bool java_init(arg_data *args, home_data *data) { #ifdef OS_DARWIN dso_handle apph = NULL; char appf[1024]; struct stat sb; #endif /* ifdef OS_DARWIN */ jvm_create_t symb = NULL; JNINativeMethod nativemethods[2]; JavaVMOption *opt = NULL; dso_handle libh = NULL; JavaVMInitArgs arg; char *libf = NULL; jint ret; int x; char loaderclass[] = LOADER; char shutdownmethod[] = "shutdown"; char shutdownparams[] = "(Z)V"; char failedmethod[] = "failed"; char failedparams[] = "(Ljava/lang/String;)V"; char daemonprocid[64]; /* Decide WHAT virtual machine we need to use */ libf = java_library(args, data); if (libf == NULL) { log_error("Cannot locate JVM library file"); return false; } /* Initialize the DSO library */ if (dso_init() != true) { log_error("Cannot initialize the dynamic library loader"); return false; } /* Load the JVM library */ #if !defined(OSD_POSIX) libh = dso_link(libf); if (libh == NULL) { log_error("Cannot dynamically link to %s", libf); log_error("%s", dso_error()); return false; } log_debug("JVM library %s loaded", libf); #endif #ifdef OS_DARWIN /* MacOS/X actually has two libraries, one with the REAL vm, and one for the VM startup. before JVM 1.4.1 The first one (libappshell.dyld) contains CreateVM JVM 1.4.1 through 1.5.* The library name is libjvm_compat.dylib starting with JVM 1.6 on OS X 10.6 the library name is libverify.dylib. */ if (replace(appf, 1024, "$JAVA_HOME/../Libraries/libappshell.dylib", "$JAVA_HOME", data->path) != 0) { log_error("Cannot replace values in loader library"); return false; } if (stat(appf, &sb)) { if (replace(appf, 1024, "$JAVA_HOME/../Libraries/libjvm_compat.dylib", "$JAVA_HOME", data->path) != 0) { log_error("Cannot replace values in loader library"); return false; } } if (stat(appf, &sb)) { if (replace(appf, 1024, "$JAVA_HOME/../Libraries/libverify.dylib", "$JAVA_HOME", data->path) != 0) { log_error("Cannot replace values in loader library"); return false; } } apph = dso_link(appf); if (apph == NULL) { log_error("Cannot load required shell library %s", appf); return false; } log_debug("Shell library %s loaded", appf); #endif /* ifdef OS_DARWIN */ #if defined(OSD_POSIX) /* BS2000 does not allow to call JNI_CreateJavaVM indirectly */ #else symb = (jvm_create_t)dso_symbol(libh, "JNI_CreateJavaVM"); if (symb == NULL) { #ifdef OS_DARWIN symb = (jvm_create_t)dso_symbol(apph, "JNI_CreateJavaVM"); if (symb == NULL) { #endif /* ifdef OS_DARWIN */ log_error("Cannot find JVM library entry point"); return false; #ifdef OS_DARWIN } #endif /* ifdef OS_DARWIN */ } log_debug("JVM library entry point found (0x%08X)", symb); #endif /* Prepare the VM initialization arguments */ /* * Mac OS X Java will load JVM 1.3.1 instead of 1.4.2 if JNI_VERSION_1_2 * is specified. So use JNI_VERSION_1_4 if we can. */ #if defined(JNI_VERSION_1_4) arg.version = JNI_VERSION_1_4; #else arg.version = JNI_VERSION_1_2; #endif #if defined(OSD_POSIX) if (JNI_GetDefaultJavaVMInitArgs(&arg) < 0) { log_error("Cannot init default JVM default args"); return false; } #endif arg.ignoreUnrecognized = FALSE; arg.nOptions = args->onum + 4; /* pid, ppid and abort */ opt = (JavaVMOption *) malloc(arg.nOptions * sizeof(JavaVMOption)); for (x = 0; x < args->onum; x++) { opt[x].optionString = strdup(args->opts[x]); jsvc_xlate_to_ascii(opt[x].optionString); opt[x].extraInfo = NULL; } /* Add our daemon process id */ snprintf(daemonprocid, sizeof(daemonprocid), "-Dcommons.daemon.process.id=%d", (int)getpid()); opt[x].optionString = strdup(daemonprocid); jsvc_xlate_to_ascii(opt[x].optionString); opt[x++].extraInfo = NULL; snprintf(daemonprocid, sizeof(daemonprocid), "-Dcommons.daemon.process.parent=%d", (int)getppid()); opt[x].optionString = strdup(daemonprocid); jsvc_xlate_to_ascii(opt[x].optionString); opt[x++].extraInfo = NULL; snprintf(daemonprocid, sizeof(daemonprocid), "-Dcommons.daemon.version=%s", JSVC_VERSION_STRING); opt[x].optionString = strdup(daemonprocid); jsvc_xlate_to_ascii(opt[x].optionString); opt[x++].extraInfo = NULL; opt[x].optionString = strdup("abort"); jsvc_xlate_to_ascii(opt[x].optionString); opt[x].extraInfo = (void *)java_abort123; arg.options = opt; /* Do some debugging */ if (log_debug_flag == true) { log_debug("+-- DUMPING JAVA VM CREATION ARGUMENTS -----------------"); log_debug("| Version: %#08x", arg.version); log_debug("| Ignore Unrecognized Arguments: %s", arg.ignoreUnrecognized == TRUE ? "True" : "False"); log_debug("| Extra options: %d", args->onum); for (x = 0; x < args->onum; x++) { jsvc_xlate_from_ascii(opt[x].optionString); log_debug("| \"%s\" (0x%08x)", opt[x].optionString, opt[x].extraInfo); jsvc_xlate_to_ascii(opt[x].optionString); } log_debug("+-------------------------------------------------------"); log_debug("| Internal options: %d", arg.nOptions - args->onum); for (; x < arg.nOptions; x++) { jsvc_xlate_from_ascii(opt[x].optionString); log_debug("| \"%s\" (0x%08x)", opt[x].optionString, opt[x].extraInfo); jsvc_xlate_to_ascii(opt[x].optionString); } log_debug("+-------------------------------------------------------"); } /* And finally create the Java VM */ #if defined(OSD_POSIX) ret = JNI_CreateJavaVM(&jvm, &env, &arg); #else ret = (*symb) (&jvm, &env, &arg); #endif if (ret < 0) { log_error("Cannot create Java VM"); return false; } log_debug("Java VM created successfully"); jsvc_xlate_to_ascii(loaderclass); cls = (*env)->FindClass(env, loaderclass); jsvc_xlate_from_ascii(loaderclass); if (cls == NULL) { log_error("Cannot find daemon loader %s", loaderclass); return false; } log_debug("Class %s found", loaderclass); jsvc_xlate_to_ascii(shutdownmethod); nativemethods[0].name = shutdownmethod; jsvc_xlate_to_ascii(shutdownparams); nativemethods[0].signature = shutdownparams; nativemethods[0].fnPtr = (void *)shutdown; jsvc_xlate_to_ascii(failedmethod); nativemethods[1].name = failedmethod; jsvc_xlate_to_ascii(failedparams); nativemethods[1].signature = failedparams; nativemethods[1].fnPtr = (void *)failed; if ((*env)->RegisterNatives(env, cls, nativemethods, 2) != 0) { log_error("Cannot register native methods"); return false; } log_debug("Native methods registered"); return true; }