int main(int argc, char** argv) { (void)argc; (void)argv; VirtualMachine vm; vm.LoadFile("script.as"); vm.Call("void main()"); JavaVM *jvm; /* denotes a Java VM */ JNIEnv *env; /* pointer to native method interface */ JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */ JavaVMOption* options = new JavaVMOption[1]; options[0].optionString = "-Djava.class.path=/usr/lib/java"; vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 1; vm_args.options = options; vm_args.ignoreUnrecognized = false; /* load and initialize a Java VM, return a JNI interface * pointer in env */ JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); delete options; /* invoke the Main.test method using the JNI */ jclass cls = env->FindClass("Main"); jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V"); env->CallStaticVoidMethod(cls, mid, 100); /* We are done. */ jvm->DestroyJavaVM(); std::cout << "Hello World! (C++)" << std::endl; }
int main(int cArgs, char *argv[]) { int optionCount; int firstOptionOrdinal; int argCount; int firstArgOrdinal; GetCounts(cArgs, argv, optionCount, firstOptionOrdinal, argCount, firstArgOrdinal); JavaVMOption* options = GetJavaOptions(argv, optionCount, firstOptionOrdinal); JNIEnv *env; JavaVM *jvm; int failureCode = 0; if ((failureCode = CreateJVM(env, jvm, options, optionCount)) != ErrSuccess) { fflush(stdout); return failureCode; } if ((failureCode = CallMainMethodOfEntryClass(env, argv, firstArgOrdinal, argCount)) != ErrSuccess) { fflush(stdout); return failureCode; } // Check for errors. if (env->ExceptionOccurred()) { env->ExceptionDescribe(); } // Finally, destroy the JavaVM jvm->DestroyJavaVM(); return 0; }
int main( int argc, char *argv[] ) { JavaVMInitArgs vm_args; JavaVMOption options[ 1 ]; JavaVM *vm; JNIEnv *env; options[ 0 ].optionString = "-Djava.class.path=."; vm_args.options = options; vm_args.nOptions = 1; vm_args.version = JNI_VERSION_1_2; int res = JNI_CreateJavaVM( &vm, (void **)&env, &vm_args ); if( res < 0 ) { cerr << "Failed to create VM (" << res << ")" << endl; return -1; } jclass cls = env->FindClass( CLASS_NAME ); // Now try to call main jmethodID mainMethodID = env->GetStaticMethodID( cls, "main", "([Ljava/lang/String;)V" ); jclass classString = env->FindClass( "java.lang.String" ); jobjectArray argsToMain = env->NewObjectArray(0, classString, NULL); env->CallStaticVoidMethod( cls, mainMethodID, argsToMain ); vm->DestroyJavaVM( ); return 0; }
int mainprogram(char *game) { FILE *f; char **paramlines; int l_paramlines=0; char prmfile[512]; sprintf_s(prmfile, 512, "../%s/%s.prm", game, game); if (fopen_s(&f, prmfile, "r") !=0) { MessageBox(NULL, TEXT("Unable to load parameter file. Please reinstall the program."), TEXT("Error"), MB_OK); return 0; } else { char line[MAX_LINE_LENGTH]; while (fgets(line, MAX_LINE_LENGTH, f)!=NULL) l_paramlines++; paramlines=new char *[l_paramlines]; fseek(f, 0, SEEK_SET); int i=0; while (fgets(line, MAX_LINE_LENGTH, f)!=NULL) { int len=strlen(line); for (int j=len-1; j>=0; j--) { if (line[j]!='\n' && line[j]!='\r') break; line[j]=0; } paramlines[i]=new char[len+1]; strcpy_s(paramlines[i], len+1, line); i++; } } if (l_paramlines<1) { MessageBox(NULL, TEXT("Empty parameter file. Please reinstall the program."), TEXT("Error"), MB_OK); return 0; } JavaVM *jvm; JNIEnv *env; LoadLibrary(TEXT("jvm.dll")); JavaVMInitArgs vm_args; vm_args.version=JNI_VERSION_1_6; vm_args.nOptions=l_paramlines-1; vm_args.options=new JavaVMOption[l_paramlines-1]; for (int i=0; i<l_paramlines-1; i++) vm_args.options[i].optionString=paramlines[i]; vm_args.ignoreUnrecognized=false; jint result=JNI_CreateJavaVM(&jvm, reinterpret_cast<void **>(&env), &vm_args); if (result!=JNI_OK) return 0; jclass cls=env->FindClass(paramlines[l_paramlines-1]); if (cls!=NULL) { jmethodID mid=env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); jobjectArray args=env->NewObjectArray(1, env->FindClass("java/lang/String"), NULL); env->SetObjectArrayElement(args,0,env->NewStringUTF(game)); env->CallStaticVoidMethod(cls, mid, args); } jvm->DestroyJavaVM(); return 0; }
void jserver_destroy() { JavaVM* jvm = get_jvm(); if (jvm != NULL) { /* Destroy the Java VM. */ jvm->DestroyJavaVM(); } }
int main(int argc, char* argv[]) { JavaVM *jvm; JNIEnv *env; // NB: This program requires loci_tools.jar in the same directory. string classpath = "-Djava.class.path"; const int numJars = 1; string jars[numJars] = { "loci_tools.jar" }; for (int i=0; i<numJars; i++) { classpath += i == 0 ? "=" : PATHSEP; classpath += jars[i]; } cout << "Classpath = " << classpath << endl; // get the default initialization arguments and set the class path JavaVMInitArgs vm_args; JNI_GetDefaultJavaVMInitArgs(&vm_args); const int numOptions = 1; JavaVMOption options[numOptions]; options[0].optionString = (char*) classpath.c_str(); //options[1].optionString = "-verbose:jni"; vm_args.version = JNI_VERSION_1_4; // VM version 1.4 vm_args.options = options; vm_args.nOptions = numOptions; // load and initialize a Java VM, return a JNI interface pointer in env if (JNI_CreateJavaVM(&jvm, (void**) &env, &vm_args)) { cout << "Failed to create the JVM" << endl; exit(1); } // invoke the ImageInfo.main(String[]) method using the JNI jclass imageInfoClass = env->FindClass("loci/formats/tools/ImageInfo"); cout << "Got ImageInfo class: " << imageInfoClass << endl; jmethodID mid = env->GetStaticMethodID(imageInfoClass, "main", "([Ljava/lang/String;)V"); cout << "Got main method: " << mid << endl; jclass stringClass = env->FindClass("java/lang/String"); cout << "Got String class: " << stringClass << endl; jobjectArray args = env->NewObjectArray(argc - 1, stringClass, 0); for (int i=1; i<argc; i++) { jstring arg = env->NewStringUTF(argv[i]); env->SetObjectArrayElement(args, i - 1, arg); } cout << "Got object array: " << args << endl; env->CallStaticVoidMethod(imageInfoClass, mid, args); jvm->DestroyJavaVM(); }
int main(int ac, const char** av) { JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_2; vmArgs.nOptions = 1; vmArgs.ignoreUnrecognized = JNI_TRUE; JavaVMOption options[1]; vmArgs.options = options; options[0].optionString = const_cast<char*>("-Xbootclasspath:[bootJar]"); JavaVM* vm; void* env; JNI_CreateJavaVM(&vm, &env, &vmArgs); JNIEnv* e = static_cast<JNIEnv*>(env); char mainClass[256]; getMainClass(mainClass, sizeof(mainClass)); jclass c = e->FindClass(mainClass); if (not e->ExceptionCheck()) { jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); if (not e->ExceptionCheck()) { jclass stringClass = e->FindClass("java/lang/String"); if (not e->ExceptionCheck()) { jobjectArray a = e->NewObjectArray(ac - 1, stringClass, 0); if (not e->ExceptionCheck()) { for (int i = 1; i < ac; ++i) { e->SetObjectArrayElement(a, i - 1, e->NewStringUTF(av[i])); } e->CallStaticVoidMethod(c, m, a); } else fprintf(stderr, "Couldn't create array\n"); } else fprintf(stderr, "java.lang.String not found\n"); } else fprintf(stderr, "main method not found\n"); } else fprintf(stderr, "Main class not found\n"); int exitCode = 0; if (e->ExceptionCheck()) { exitCode = -1; e->ExceptionDescribe(); e->ExceptionClear(); } vm->DestroyJavaVM(); return exitCode; }
int createServiceProxy(int id) { JavaVM *jvm; /* representa uma VM Java */ JNIEnv *env; /* ponteiro para a interface de metodos nativos */ jvm = bftsmartdiversity::jvm; env = bftsmartdiversity::env; /* invoke the Main.test method using the JNI */ jclass cls = env->FindClass("bftsmart/diversity/ClientWrapper"); if (cls == NULL) { std::cout << "ERRO no FindClass diversity" << std::endl; jvm->DestroyJavaVM(); return 0x8100; } jint arg = (jint) id; jmethodID constru = env->GetMethodID(cls, "<init>", "(I)V"); if (constru == NULL) { std::cout << "ERRO ao construir wrapper getmid" << std::endl; jvm->DestroyJavaVM(); return 0x8200; } bftsmartdiversity::serviceProxy = env->NewObject(cls, constru, arg); if (bftsmartdiversity::serviceProxy == NULL) { std::cout << "ERRO ao construir wrapper int. srvprox" << std::endl; jvm->DestroyJavaVM(); return 0x8201; } bftsmartdiversity::invokeOrderedMethod = env->GetMethodID(cls, "invokeOrdered", "([B)[B"); bftsmartdiversity::invokeUnorderedMethod = env->GetMethodID(cls, "invokeUnordered", "([B)[B"); if (bftsmartdiversity::invokeOrderedMethod == NULL || bftsmartdiversity::invokeUnorderedMethod == NULL) { std::cout << "ERRO ao obter execute(un) ordered " << std::endl; jvm->DestroyJavaVM(); return 0x8107; } return 0x0; }
int main(int argc, char **argv) { JavaVM* pJVM = 0; JNIEnv* env = create_vm(&pJVM); jint ver = env->GetVersion(); printf("version is : %d\n", ver); initJavaReference(env); // check for exceptions checkException(env); // destroy pJVM->DestroyJavaVM(); pJVM = 0; }
int main(int args, const char * argv[]) { char optionString[] = "-Djava.class.path=/Users/nerdwizard/Documents/XDU/Salt/SingleDocker/out/production/SingleDocker/"; JavaVM * jvm; /* denotes a Java VM */ JNIEnv * env; /* pointer to native method interface */ JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */ JavaVMOption * options = new JavaVMOption[1]; size_t optionStringSize = strlen(optionString) + 1; options[0].optionString = new char[optionStringSize]; copy(optionString, optionString + optionStringSize, options[0].optionString); vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 1; vm_args.options = options; vm_args.ignoreUnrecognized = (jboolean) false; /* load and initialize a Java VM, return a JNI interface * pointer in env */ JNI_CreateJavaVM(&jvm, (void **) &env, &vm_args); delete options; auto className = "org/bedlab/ros/docks/Execute"; if (env == nullptr) { cerr << "WTF?!" << endl; return -1; } jclass cls = env->FindClass(className); if (cls == nullptr) { printJVMException(env); cerr << className << ": Class Not Found" << endl; return -1; } auto methodName = "execute"; jmethodID mid = env->GetStaticMethodID(cls, methodName, "(Ljava/lang/String) Ljava/lang/String"); if (mid == nullptr) { printJVMException(env); cerr << methodName << ": MethodNot Found" << endl; return -1; } string path = string(getcwd(NULL, 0)) + string(argv[1]); cout << "Working on: " << path << endl; jstring jpath = env->NewString((const jchar *) path.c_str(), (jsize) path.length()); jstring ret = (jstring) env->CallStaticObjectMethod(cls, mid, jpath); cout << ">> " << ret << endl; /* We are done. */ jvm->DestroyJavaVM(); return 0; }
int invokeOrdered(BFT_BYTE command[], int tamanho, BFT_BYTE saida[]) { JavaVM *jvm; /* representa uma VM Java */ JNIEnv *env; /* ponteiro para a interface de metodos nativos */ jvm = bftsmartdiversity::jvm; env = bftsmartdiversity::env; /* apenas para fins de debug printf("tamanho: %d\n",tamanho); for (int i=0;i<tamanho;i++) { printf("%x ",command[i]); } printf("\n"); fim do debug*/ jbyteArray arrayJava = env->NewByteArray(tamanho); env->SetByteArrayRegion(arrayJava, 0, tamanho, (jbyte*) command); jbyteArray result = (jbyteArray) (env->CallObjectMethod(bftsmartdiversity::serviceProxy, bftsmartdiversity::invokeOrderedMethod, arrayJava)); if (result == NULL) { std::cout << "erro o chamar invoke ordered" << std::endl; jvm->DestroyJavaVM(); return 0x8109; } jint saidaT = env->GetArrayLength(result); env->GetByteArrayRegion(result, 0, saidaT, (jbyte*) saida); /* apenas para fins de debug printf("tamanho: %d\n",saidaT); for (int i=0;i<saidaT;i++) { printf("%x ",saida[i]); } printf("\n"); fim do debug */ return (int) saidaT; }
int invokeUnordered(BFT_BYTE command[], int tamanho, BFT_BYTE saida[]) { JavaVM *jvm; /* representa uma VM Java */ JNIEnv *env; /* ponteiro para a interface de metodos nativos */ jvm = bftsmartdiversity::jvm; env = bftsmartdiversity::env; jbyteArray arrayJava = env->NewByteArray(tamanho); env->SetByteArrayRegion(arrayJava, 0, tamanho, (jbyte*) command); jbyteArray result = (jbyteArray) (env->CallObjectMethod(bftsmartdiversity::serviceProxy, bftsmartdiversity::invokeUnorderedMethod, arrayJava)); if (result == NULL) { std::cout << "erro o chamar invoke unordered" << std::endl; jvm->DestroyJavaVM(); return 0x8109; } jint saidaT = env->GetArrayLength(result); env->GetByteArrayRegion(result, 0, saidaT, (jbyte*) saida); return (int) saidaT; }
int main(int argc, char** argv) { JavaVMInitArgs args; args.version = JNI_VERSION_1_1; args.nOptions = 1; args.options = new JavaVMOption[1]; args.options->optionString = (char*)"/home/benland100/Desktop/sjvm/javatest/"; JavaVM *vm; JNIEnv *env; JNI_CreateJavaVM(&vm,(void**)&env,(void*)&args); delete [] args.options; //jclass system = env->FindClass("java/lang/System"); //jclass printstream = env->FindClass("java/io/PrintStream"); //jfieldID outID = env->GetStaticFieldID(system,"out","Ljava/io/PrintStream;"); //jobject out = env->GetStaticObjectField(system,outID); //cout << (int)out << '\n'; //jclass mainclass = env->FindClass("smart/Client"); //jmethodID main = env->GetStaticMethodID(mainclass,"main","([Ljava/lang/String;)V"); //env->CallStaticVoidMethod(mainclass,main,env->NewObjectArray(0,env->FindClass("java/lang/String"),0)); //jobject obj = env->AllocObject(exception);//env->NewObject(exception,einit); //env->CallVoidMethod(obj,einit); //jclass test = env->FindClass("fields/subclass"); jclass mainclass = env->FindClass("javatest"); jmethodID main = env->GetStaticMethodID(mainclass,"main","([Ljava/lang/String;)V"); try { env->CallStaticVoidMethod(mainclass,main); if (env->ExceptionOccurred() == 0) { cout << "Executing Success\n"; } else { cout << "Damn, exceptions...\n"; } } catch ( ... ) { } env->DeleteLocalRef(mainclass); vm->DestroyJavaVM(); return 0; }
int main(int argc, char** argv) { //Creating VM And ENV Variables JavaVM *vm; JNIEnv *env; JavaVMInitArgs vm_args; JavaVMOption* options = new JavaVMOption[1]; //VM Arguments options[0].optionString = (char *)"-Djava.class.path=.:jars/netcdfAll-4.5.jar"; vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 1; vm_args.ignoreUnrecognized = 1; vm_args.options=options; // Construct a VM jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args); //Delete Options delete options; ////////////////////////////////////////////////////////////////////////////////////////////////// //array of file names string fileName[total]; fileName[0]="20130101_0300.gz"; fileName[1]="20130101_0700.gz"; fileName[2]="20130101_1100.gz"; fileName[3]="20130101_0000.gz"; fileName[4]="20130101_0400.gz"; fileName[5]="20130101_0800.gz"; fileName[6]="20130101_1200.gz"; fileName[7]="20130101_0100.gz"; fileName[8]="20130101_0500.gz"; fileName[9]="20130101_0900.gz"; fileName[10]="20130101_0200.gz"; fileName[11]="20130101_0600.gz"; fileName[12]="20130101_1000.gz"; //for(int i=0;i<total;i++) // fileName[i]="20130101_0000.gz"; clock_t tStart = clock(); //Parallel Execution of for loop to get the size for each file for ( int i = 0; i < total; i++) WeatherData::getSize(vm,env,"latitude",fileName[i],dataDir,i); //Parallel Execution of for loop to get the attributes for ( int i = 0; i < total; i++) { WeatherData::getFloatData(vm,env,"windSpeed",fileName[i],dataDir,capacity[i]); WeatherData::getFloatData(vm,env,"windDir",fileName[i],dataDir,capacity[i]); } //Get Station Ids for ( int i = 0; i < total; i++) { WeatherData::getStringData(vm,env,"stationId",fileName[i],dataDir,capacity[i]); WeatherData::deleteFile(vm,env,fileName[i],dataDir); } WeatherData::calcBins1(windSpeeds,windDirs,stationIds,stationIds[7000]); //print result in matrix for(int i = 0; i < 16; i++) { for(int j = 0; j < 6; j++) { printf("%d\t",result[i][j]); } printf("\n"); } //Print Time Taken For Execution printf("\n\nTime taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC); // Shutdown the VM. vm->DestroyJavaVM(); }
int main(int ac, const char** av) { JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_2; vmArgs.nOptions = 1; vmArgs.ignoreUnrecognized = JNI_TRUE; const char* class_ = 0; const char* jar = 0; int argc = 0; const char** argv = 0; const char* classpath = "."; for (int i = 1; i < ac; ++i) { if (strcmp(av[i], "-cp") == 0 or strcmp(av[i], "-classpath") == 0) { if (i + 1 == ac) usageAndExit(av[0]); classpath = av[++i]; } else if (strcmp(av[i], "-jar") == 0) { if (i + 1 == ac) usageAndExit(av[0]); jar = av[++i]; } else if (strncmp(av[i], "-X", 2) == 0 or strncmp(av[i], "-D", 2) == 0) { ++ vmArgs.nOptions; } else if (strcmp(av[i], "-client") == 0 or strcmp(av[i], "-server") == 0) { // ignore } else { if (jar == 0) { class_ = av[i++]; } if (i < ac) { argc = ac - i; argv = av + i; i = ac; } } } if (jar) { classpath = jar; class_ = mainClass(jar); if (class_ == 0) { fprintf(stderr, "Main-Class manifest header not found in %s\n", jar); exit(-1); } } #ifdef BOOT_LIBRARY ++ vmArgs.nOptions; #endif #ifdef BOOT_IMAGE vmArgs.nOptions += 2; #endif #ifdef BOOT_BUILTINS ++ vmArgs.nOptions; #endif RUNTIME_ARRAY(JavaVMOption, options, vmArgs.nOptions); vmArgs.options = RUNTIME_ARRAY_BODY(options); unsigned optionIndex = 0; #ifdef BOOT_IMAGE vmArgs.options[optionIndex++].optionString = const_cast<char*>("-Davian.bootimage=bootimageBin"); vmArgs.options[optionIndex++].optionString = const_cast<char*>("-Davian.codeimage=codeimageBin"); #endif #ifdef BOOT_LIBRARY vmArgs.options[optionIndex++].optionString = const_cast<char*>("-Davian.bootstrap=" BOOT_LIBRARY); #endif #ifdef BOOT_BUILTINS vmArgs.options[optionIndex++].optionString = const_cast<char*>("-Davian.builtins=" BOOT_BUILTINS); #endif #define CLASSPATH_PROPERTY "-Djava.class.path=" unsigned classpathSize = strlen(classpath); unsigned classpathPropertyBufferSize = sizeof(CLASSPATH_PROPERTY) + classpathSize; RUNTIME_ARRAY(char, classpathPropertyBuffer, classpathPropertyBufferSize); memcpy(RUNTIME_ARRAY_BODY(classpathPropertyBuffer), CLASSPATH_PROPERTY, sizeof(CLASSPATH_PROPERTY) - 1); memcpy(RUNTIME_ARRAY_BODY(classpathPropertyBuffer) + sizeof(CLASSPATH_PROPERTY) - 1, classpath, classpathSize + 1); vmArgs.options[optionIndex++].optionString = RUNTIME_ARRAY_BODY(classpathPropertyBuffer); for (int i = 1; i < ac; ++i) { if (strncmp(av[i], "-X", 2) == 0 or strncmp(av[i], "-D", 2) == 0) { vmArgs.options[optionIndex++].optionString = const_cast<char*>(av[i]); } } if (class_ == 0) { usageAndExit(av[0]); } JavaVM* vm; void* env; JNI_CreateJavaVM(&vm, &env, &vmArgs); JNIEnv* e = static_cast<JNIEnv*>(env); jclass c = 0; if (not e->ExceptionCheck()) { c = e->FindClass(class_); } if (jar) { free(const_cast<char*>(class_)); } if (not e->ExceptionCheck()) { jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); if (not e->ExceptionCheck()) { jclass stringClass = e->FindClass("java/lang/String"); if (not e->ExceptionCheck()) { jobjectArray a = e->NewObjectArray(argc, stringClass, 0); if (not e->ExceptionCheck()) { for (int i = 0; i < argc; ++i) { e->SetObjectArrayElement(a, i, e->NewStringUTF(argv[i])); } e->CallStaticVoidMethod(c, m, a); } } } } int exitCode = 0; if (e->ExceptionCheck()) { exitCode = -1; e->ExceptionDescribe(); } vm->DestroyJavaVM(); return exitCode; }
bool startJVM(TCHAR* basedir, TCHAR* appFolder, TCHAR* jar, int argCount, LPTSTR *szArgList) { TCHAR jvmPath[LAUNCHER_MAXPATH+1] = {0}; JavaVMInitArgs jvmArgs; JavaVMOption options[MAX_OPTIONS]; JVM_CREATE createProc; JNIEnv* env; JavaVM* jvm = NULL; char jarASCII[LAUNCHER_MAXPATH] = {0}; char classpath[LAUNCHER_MAXPATH*2] = {0}; char mainclassASCII[LAUNCHER_MAXPATH] = {0}, appClasspath[LAUNCHER_MAXPATH] = {0}; size_t outlen = 0; jclass cls; jmethodID mid; TCHAR argname[MAX_OPTION_NAME + 1] = {0}; TCHAR argvalue[LAUNCHER_MAXPATH] = {0}, mainclass[LAUNCHER_MAXPATH] = {0}; CHAR argvalueASCII[LAUNCHER_MAXPATH] = {0}; HMODULE msvcrtdll; bool runtimeBundled; TCHAR tmpPath[LAUNCHER_MAXPATH] = {0}; TCHAR appid[LAUNCHER_MAXPATH] = {0}; memset(&options, 0, sizeof(JavaVMOption)*MAX_OPTIONS); memset(&jvmArgs, 0, sizeof(JavaVMInitArgs)); makeFullFileName(basedir, _T("\\runtime"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR)); runtimeBundled = fileExists(tmpPath); if (runtimeBundled) { if (!getJvmPath(basedir, jvmPath, LAUNCHER_MAXPATH)) { showError(_T("jvm.dll is not found in bundled runtime."), jvmPath); return false; } //make sure msvcr100 is loaded (or we may fail if copy of it is not installed into system) makeFullFileName(basedir, _T("runtime\\jre\\bin\\msvcr100.dll"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR)); msvcrtdll = ::LoadLibrary(tmpPath); } else { if (!getSystemJvmPath(jvmPath, LAUNCHER_MAXPATH)) { showError(_T("No bundled runtime and can not find system JRE."), jvmPath); return false; } //make sure msvcr100 is loaded (or we may fail if copy of it is not installed into system) makeFullFileName(basedir, _T("\\bin\\msvcr100.dll"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR)); msvcrtdll = ::LoadLibrary(tmpPath); } // Dynamically load the JVM HMODULE jvmLibHandle = LoadLibrary(jvmPath); if (jvmLibHandle == NULL) { DWORD dwErr = GetLastError(); showError(_T("Error loading jvm.dll"), jvmPath); return false; } //convert argument to ASCII string as this is what CreateJVM needs wcstombs_s(&outlen, jarASCII, LAUNCHER_MAXPATH, jar, (size_t) wcslen(jar) + 1); strcpy_s(classpath, LAUNCHER_MAXPATH*2, "-Djava.class.path="); strcat_s(classpath, LAUNCHER_MAXPATH, jarASCII); if (getConfigValue(basedir, CONFIG_CLASSPATH_KEY, argvalue, LAUNCHER_MAXPATH)) { size_t inLen = (size_t) wcslen(argvalue); //convert argument to ASCII string as this is what CreateJVM needs wcstombs_s(&outlen, argvalueASCII, sizeof(argvalueASCII), argvalue, inLen + 1); //compress spaces and replaces them with ; { char *in = argvalueASCII; char *out = argvalueASCII; bool needSemicolon = false; while (*in != 0) { if (*in == ' ') { if (needSemicolon) { *out = ';'; out++; needSemicolon = false; } } else { needSemicolon = true; *out = *in; out++; } in++; } *out = 0; } if (strlen(argvalueASCII) > 0) { strcat_s(classpath, LAUNCHER_MAXPATH, ";"); strcat_s(classpath, LAUNCHER_MAXPATH, argvalueASCII); } } // Set up the VM init args jvmArgs.version = JNI_VERSION_1_2; options[0].optionString = _strdup(classpath); int cnt = 1; if (isDebug) { options[cnt].optionString = _strdup("vfprintf"); options[cnt].extraInfo = vfprintfHook; cnt++; } //Note: should not try to quote the path. Spaces are fine here _stprintf_s(argvalue, _T("-Djava.library.path=%s"), appFolder); wcstombs_s(&outlen, argvalueASCII, sizeof(argvalueASCII), argvalue, wcslen(argvalue) + 1); options[cnt].optionString = _strdup(argvalueASCII); cnt++; //add app specific JVM parameters int idx = 1; int found = 0; do { _stprintf_s(argname, MAX_OPTION_NAME, _T("jvmarg.%d"), idx); found = getConfigValue(basedir, argname, argvalue, LAUNCHER_MAXPATH); if (found) { TCHAR* option = replaceStr(argvalue, _T("$APPDIR"), basedir); char* jvmOption = convertToDupedChar(option); if (jvmOption != NULL) { options[cnt].optionString = jvmOption; cnt++; } idx++; } } while (found && idx < MAX_OPTIONS); cnt = addUserOptions(basedir, options, cnt); jvmArgs.version = 0x00010002; jvmArgs.options = options; jvmArgs.nOptions = cnt; jvmArgs.ignoreUnrecognized = JNI_TRUE; // Create the JVM // NB: need to use ASCII string as UNICODE is not supported createProc = (JVM_CREATE) GetProcAddress(jvmLibHandle, "JNI_CreateJavaVM"); if (createProc == NULL) { showError(_T("Failed to locate JNI_CreateJavaVM"), jvmPath); return false; } if ((*createProc)(&jvm, &env, &jvmArgs) < 0) { showError(_T("Failed to create JVM"), jvmPath); return false; } if (!getConfigValue(basedir, CONFIG_MAINCLASS_KEY, mainclass, LAUNCHER_MAXPATH)) { showError(_T("Package error"), _T("No main class specified. Nothing to launch")); return false; } else { size_t inLen = (size_t) wcslen(mainclass); //convert argument to ASCII string as this is what CreateJVM needs wcstombs_s(&outlen, mainclassASCII, sizeof(mainclassASCII), mainclass, inLen + 1); } cls = env->FindClass(mainclassASCII); if (cls != NULL) { mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); if (mid != NULL) { jclass stringClass = env->FindClass("java/lang/String"); //prepare app arguments if any. Skip value at index 0 - this is path to executable ... //NOTE: // - what if user run in non-English/UTF-8 locale? do we need to convert args? // - extend to pass jvm args and debug args (allow them in front, use marker option to separate them?) int startArgIndex = countNumberOfSystemArguments(argCount, szArgList); jobjectArray args = env->NewObjectArray(argCount - startArgIndex, stringClass, NULL); for(int i=startArgIndex; i<argCount; i++) { size_t inLen = (size_t) wcslen(szArgList[i]); env->SetObjectArrayElement(args, i-startArgIndex, env->NewString((jchar*)szArgList[i], inLen)); } env->CallStaticVoidMethod(cls, mid, args); } else { showError(_T("no main method in the main class!"), mainclass); return false; } } else { showError(_T("no main class."), mainclass); return false; } if (env->ExceptionOccurred()) { showError(_T("Failed due to exception from main class."), mainclass); env->ExceptionDescribe(); } // If application main() exits quickly but application is run on some other thread // (e.g. Swing app performs invokeLater() in main and exits) // then if we return execution to tWinMain it will exit. // This will cause process to exit and application will not actually run. // // To avoid this we are trying to detach jvm from current thread (java.exe does the same) // Because we are doing this on the main JVM thread (i.e. one that was used to create JVM) // this call will spawn "Destroy Java VM" java thread that will shut JVM once there are // no non-daemon threads running, and then return control here. // I.e. this will happen when EDT and other app thread will exit. if (jvm->DetachCurrentThread() != 0) { showError(_T("Detach failed."), NULL); } jvm->DestroyJavaVM(); return true; }
int main(void) { JavaVMOption options[3]; JNIEnv *env; JavaVM *jvm; JavaVMInitArgs vm_args; long status; jclass cls; jmethodID mid; jfieldID fid; jobject obj; options[0].optionString = "-Djava.compiler = NONE"; options[1].optionString = "-Djava.class.path=.;D:/Universal_Tank/apache-jena-2.12.0/lib/commons-codec-1.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/httpclient-4.2.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/httpclient-cache-4.2.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/httpcore-4.2.5.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jackson-annotations-2.3.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jackson-core-2.3.3.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jackson-databind-2.3.3.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jcl-over-slf4j-1.7.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jena-arq-2.12.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jena-core-2.12.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jena-iri-1.1.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jena-sdb-1.5.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jena-tdb-1.1.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/jsonld-java-0.5.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/log4j-1.2.17.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/slf4j-api-1.7.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/slf4j-log4j12-1.7.6.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/xercesImpl-2.11.0.jar;D:/Universal_Tank/apache-jena-2.12.0/lib/xml-apis-1.4.01.jar;"; options[2].optionString = "-verbose:NONE"; memset(&vm_args, 0, sizeof(vm_args)); vm_args.version = JNI_VERSION_1_4; vm_args.nOptions = 3; vm_args.options = options; vm_args.ignoreUnrecognized = JNI_TRUE; // 启动虚拟机 status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (status != JNI_ERR) { // 先获得class对象 cls = env->FindClass("Sample2"); if (cls != 0) { // 获取方法ID, 通过方法名和签名, 调用静态方法 mid = env->GetStaticMethodID(cls, "sayHello", "(Ljava/lang/String;)Ljava/lang/String;"); if (mid != 0) { const char* name = "World33"; jstring arg = env->NewStringUTF(name); jstring result = (jstring)env->CallStaticObjectMethod(cls, mid, arg); const char* str = env->GetStringUTFChars(result, false); printf("Result of sayHello: %s\n", str); env->ReleaseStringUTFChars(result, 0); //const char* name = "World22"; //jstring arg = env->NewStringUTF(name); //jstring result = (jstring)env->CallStaticObjectMethod(cls, mid, arg); ////long result = (jlong)env->CallStaticObjectMethod(cls, mid, arg); ////somthing wrong with the following three lines //const char* str = env->GetStringUTFChars(result, 0);printf("here"); ////printf("Result of sayHello: %s\n",str); ////env->ReleaseStringUTFChars(result, 0); } /*** 新建一个对象 ***/ // 调用默认构造函数 //obj = env->AllocObjdect(cls); // 调用指定的构造函数, 构造函数的名字叫做<init> mid = env->GetMethodID(cls, "<init>", "()V"); obj = env->NewObject(cls, mid); if (obj == 0) { printf("Create object failed!\n"); } /*** 新建一个对象 ***/ // 获取属性ID, 通过属性名和签名 fid = env->GetFieldID(cls, "name", "Ljava/lang/String;"); if (fid != 0) { const char* name = "icejoywoo"; jstring arg = env->NewStringUTF(name); env->SetObjectField(obj, fid, arg); // 修改属性 } // 调用成员方法 mid = env->GetMethodID(cls, "sayHello", "()Ljava/lang/String;"); if (mid != 0) { jstring result = (jstring)env->CallObjectMethod(obj, mid); printf("here"); const char* str = env->GetStringUTFChars(result, false); printf("Result of sayHello: %s\n", str); env->ReleaseStringUTFChars(result, 0); } } jvm->DestroyJavaVM(); return 0; } else { printf("JVM Created failed!\n"); return -1; } }
KoFilter::ConversionStatus MpxjImport::doImport( QByteArray inFile, QByteArray outFile ) { QString normalizedInFile; QString normalizedOutFile; // Need to convert to "\" on Windows normalizedInFile = QDir::toNativeSeparators(inFile); normalizedOutFile = QDir::toNativeSeparators(outFile); kDebug(planMpxjDbg()) << normalizedInFile << normalizedOutFile; #if 1 QString cp = qgetenv( "PLAN_CLASSPATH" ); QString x = QDir::toNativeSeparators(PLANCONVERT_JAR_FILE); if ( ! x.isEmpty() ) { if ( ! cp.isEmpty() ) { cp += CLASSPATH_SEPARATOR; } cp += x; } QString exe = "java"; QStringList args; args << "-cp"; args << cp; args << "plan.PlanConvert"; args << normalizedInFile << normalizedOutFile; int res = KProcess::execute( exe, args ); kDebug(planMpxjDbg())<<res; return res == 0 ? KoFilter::OK : KoFilter::InternalError; #else JavaVM *jvm = 0; /* denotes a Java VM */ JNIEnv *env = 0; /* pointer to native method interface */ JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */ JavaVMOption* options = new JavaVMOption[1]; QByteArray cp = qgetenv( "PLAN_CLASSPATH" ); if ( ! cp.isEmpty() ) { cp = QByteArray( "-Djava.class.path=" ) + cp; } QByteArray x = PLANCONVERT_JAR_FILE; if ( ! x.isEmpty() ) { if ( ! cp.isEmpty() ) { cp += CLASSPATH_SEPARATOR; } cp += x; } options[0].optionString = cp.data(); kDebug(planMpxjDbg())<<"env:"<<cp; vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 1; vm_args.options = options; vm_args.ignoreUnrecognized = false; /* load and initialize a Java VM, return a JNI interface pointer in env */ JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if ( ! env ) { kDebug(planMpxjDbg())<<"Failed to create jvm environment"; // TODO: proper message, and restore cursor (or enhance filter manager error handling) KMessageBox::error( 0, "Failed to create JavaVM, check your installation" ); return KoFilter::UserCancelled; } delete options; jclass cls = env->FindClass("plan/PlanConvert"); if ( cls == 0 ) { kDebug(planMpxjDbg())<<"Failed to find class"; return KoFilter::InternalError; } kDebug(planMpxjDbg())<<"Found class"; jstring in = env->NewStringUTF( normalizedInFile ); jstring out = env->NewStringUTF( normalizedOutFile ); jobjectArray args = env->NewObjectArray( 2, env->FindClass("java/lang/String"), in ); // env->setObjectArrayElement( args, 0, in ); env->SetObjectArrayElement( args, 1, out ); if (args == 0) { kDebug(planMpxjDbg())<<"Out of memory"; return KoFilter::OutOfMemory; } jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V" ); if ( mid == 0 ) { kDebug(planMpxjDbg())<<"Failed to find main method"; return KoFilter::InternalError; } env->CallStaticVoidMethod( cls, mid, args ); if ( env->ExceptionCheck() ) { kError()<<"Exception:"; env->ExceptionDescribe(); return KoFilter::InternalError; } /* We are done. */ jvm->DestroyJavaVM(); if ( ! QFile::exists( normalizedOutFile ) ) { kDebug(planMpxjDbg())<<"No output file created:"<<outFile; return KoFilter::StorageCreationError; } return KoFilter::OK; #endif }
/* * Parse arguments. Most of it just gets passed through to the VM. The * JNI spec defines a handful of standard arguments. */ int main(int argc, char* const argv[]) { printf("ZHK test printf\n"); JavaVM* vm = NULL; JNIEnv* env = NULL; JavaVMInitArgs initArgs; JavaVMOption* options = NULL; char* slashClass = NULL; int optionCount, curOpt, i, argIdx; int needExtra = JNI_FALSE; int result = 1; setvbuf(stdout, NULL, _IONBF, 0); /* ignore argv[0] */ argv++; argc--; /* * If we're adding any additional stuff, e.g. function hook specifiers, * add them to the count here. * * We're over-allocating, because this includes the options to the VM * plus the options to the program. */ optionCount = argc; options = (JavaVMOption*) malloc(sizeof(JavaVMOption) * optionCount); memset(options, 0, sizeof(JavaVMOption) * optionCount); /* * Copy options over. Everything up to the name of the class starts * with a '-' (the function hook stuff is strictly internal). * * [Do we need to catch & handle "-jar" here?] */ for (curOpt = argIdx = 0; argIdx < argc; argIdx++) { if (argv[argIdx][0] != '-' && !needExtra) break; options[curOpt++].optionString = strdup(argv[argIdx]); /* some options require an additional arg */ needExtra = JNI_FALSE; if (strcmp(argv[argIdx], "-classpath") == 0 || strcmp(argv[argIdx], "-cp") == 0) /* others? */ { needExtra = JNI_TRUE; } } if (needExtra) { fprintf(stderr, "Dalvik VM requires value after last option flag\n"); goto bail; } /* insert additional internal options here */ assert(curOpt <= optionCount); initArgs.version = JNI_VERSION_1_4; initArgs.options = options; initArgs.nOptions = curOpt; initArgs.ignoreUnrecognized = JNI_FALSE; //printf("nOptions = %d\n", initArgs.nOptions); blockSigpipe(); /* * Start VM. The current thread becomes the main thread of the VM. */ jint ret_JNI_CreateJavaVM; ret_JNI_CreateJavaVM = JNI_CreateJavaVM(&vm, &env, &initArgs); //printf("ZHK in Main.cpp:215 ret_JNI_CreateJavaVM = %d\n" ,ret_JNI_CreateJavaVM); if (ret_JNI_CreateJavaVM < 0) { printf("ZHK in Main.cpp:217 Dalvik VM init failed! (check log file)\n"); fprintf(stderr, "Dalvik VM init failed! (check log file)\n"); goto bail; } /* * Make sure they provided a class name. We do this after VM init * so that things like "-Xrunjdwp:help" have the opportunity to emit * a usage statement. */ if (argIdx == argc) { printf("ZHK in Main.cpp:228 Dalvik VM requires a class name\n"); fprintf(stderr, "Dalvik VM requires a class name\n"); goto bail; } /* * We want to call main() with a String array with our arguments in it. * Create an array and populate it. Note argv[0] is not included. */ jobjectArray strArray; strArray = createStringArray(env, &argv[argIdx+1], argc-argIdx-1); if (strArray == NULL) goto bail; /* * Find [class].main(String[]). */ jclass startClass; jmethodID startMeth; char* cp; /* convert "com.android.Blah" to "com/android/Blah" */ slashClass = strdup(argv[argIdx]); for (cp = slashClass; *cp != '\0'; cp++) if (*cp == '.') *cp = '/'; startClass = env->FindClass(slashClass); if (startClass == NULL) { printf("ZHK in Main.cpp:257 Dalvik VM unable to locate class '%s'\n", slashClass); fprintf(stderr, "Dalvik VM unable to locate class '%s'\n", slashClass); goto bail; } startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { printf("ZHK in Main.cpp:265 Dalvik VM unable to find static main(String[]) in '%s'\n", slashClass); fprintf(stderr, "Dalvik VM unable to find static main(String[]) in '%s'\n", slashClass); goto bail; } /* * Make sure the method is public. JNI doesn't prevent us from calling * a private method, so we have to check it explicitly. */ if (!methodIsPublic(env, startClass, startMeth)) goto bail; /* * Invoke main(). */ env->CallStaticVoidMethod(startClass, startMeth, strArray); if (!env->ExceptionCheck()) result = 0; bail: /*printf("Shutting down Dalvik VM\n");*/ if (vm != NULL) { /* * This allows join() and isAlive() on the main thread to work * correctly, and also provides uncaught exception handling. */ if (vm->DetachCurrentThread() != JNI_OK) { fprintf(stderr, "Warning: unable to detach main thread\n"); result = 1; } if (vm->DestroyJavaVM() != 0) fprintf(stderr, "Warning: Dalvik VM did not shut down cleanly\n"); /*printf("\nDalvik VM has exited\n");*/ } for (i = 0; i < optionCount; i++) free((char*) options[i].optionString); free(options); free(slashClass); /*printf("--- VM is down, process exiting\n");*/ return result; }
int main(int argc, char* const argv[]) { JavaVM* vm = NULL; JNIEnv* env = NULL; JavaVMInitArgs initArgs; JavaVMOption* options = NULL; char* slashClass = NULL; int optionCount, curOpt, i, argIdx; int needExtra = JNI_FALSE; int result = 1; setvbuf(stdout, NULL, _IONBF, 0); /* ignore argv[0] */ argv++; argc--; optionCount = argc; options = (JavaVMOption*) malloc(sizeof(JavaVMOption) * optionCount); memset(options, 0, sizeof(JavaVMOption) * optionCount); for (curOpt = argIdx = 0; argIdx < argc; argIdx++) { if (argv[argIdx][0] != '-' && !needExtra) break; options[curOpt++].optionString = strdup(argv[argIdx]); needExtra = JNI_FALSE; if (strcmp(argv[argIdx], "-classpath") == 0 || strcmp(argv[argIdx], "-cp") == 0) /* others? */ { needExtra = JNI_TRUE; } } if (needExtra) { fprintf(stderr, "Dalvik VM requires value after last option flag\n"); goto bail; } assert(curOpt <= optionCount); initArgs.version = JNI_VERSION_1_4; initArgs.options = options; initArgs.nOptions = curOpt; initArgs.ignoreUnrecognized = JNI_FALSE; //printf("nOptions = %d\n", initArgs.nOptions); blockSigpipe(); if (JNI_CreateJavaVM(&vm, &env, &initArgs) < 0) { fprintf(stderr, "Dalvik VM init failed (check log file)\n"); goto bail; } if (argIdx == argc) { fprintf(stderr, "Dalvik VM requires a class name\n"); goto bail; } jobjectArray strArray; strArray = createStringArray(env, &argv[argIdx+1], argc-argIdx-1); if (strArray == NULL) goto bail; jclass startClass; jmethodID startMeth; char* cp; slashClass = strdup(argv[argIdx]); for (cp = slashClass; *cp != '\0'; cp++) if (*cp == '.') *cp = '/'; startClass = env->FindClass(slashClass); if (startClass == NULL) { fprintf(stderr, "Dalvik VM unable to locate class '%s'\n", slashClass); goto bail; } startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { fprintf(stderr, "Dalvik VM unable to find static main(String[]) in '%s'\n", slashClass); goto bail; } if (!methodIsPublic(env, startClass, startMeth)) goto bail; env->CallStaticVoidMethod(startClass, startMeth, strArray); if (!env->ExceptionCheck()) result = 0; bail: /*printf("Shutting down Dalvik VM\n");*/ if (vm != NULL) { if (vm->DetachCurrentThread() != JNI_OK) { fprintf(stderr, "Warning: unable to detach main thread\n"); result = 1; } if (vm->DestroyJavaVM() != 0) fprintf(stderr, "Warning: Dalvik VM did not shut down cleanly\n"); /*printf("\nDalvik VM has exited\n");*/ } for (i = 0; i < optionCount; i++) free((char*) options[i].optionString); free(options); free(slashClass); /*printf("--- VM is down, process exiting\n");*/ return result; }
void * start_java(void *start_args) { try { struct start_args *args = (struct start_args *)start_args; std::string path = ExecuteCommand("/usr/libexec/java_home -v 1.8"); path.erase(std::remove(path.begin(), path.end(), '\n'), path.end()); std::cout << "Found java \"" << path << "\"" << std::endl; std::string libPath = path + "/jre/lib/server/libjvm.dylib"; std::cout << "Use library \"" << libPath << "\"" << std::endl; void* lib_handle = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_LAZY); if (!lib_handle) { throw std::runtime_error("Failed to open library"); } JNICreateJavaVM createJavaJVM = (JNICreateJavaVM)dlsym(lib_handle, "JNI_CreateJavaVM"); if (!createJavaJVM) { dlclose(lib_handle); throw std::runtime_error("Function JNI_CreateJavaVM not found"); } int res; JavaVM *jvm; JNIEnv *env; res = createJavaJVM(&jvm, &env, &args->vm_args); if (res < 0) { dlclose(lib_handle); throw std::runtime_error("Failed to create jvm"); } /* load the launch class */ jclass main_class; jmethodID main_method_id; main_class = env->FindClass(args->launch_class); if (main_class == NULL) { jvm->DestroyJavaVM(); dlclose(lib_handle); throw std::runtime_error("Main class not found"); } /* get main method */ main_method_id = env->GetStaticMethodID(main_class, "main", "([Ljava/lang/String;)V"); if (main_method_id == NULL) { jvm->DestroyJavaVM(); dlclose(lib_handle); throw std::runtime_error("Method main not found"); } /* make the initial argument */ jobject empty_args = env->NewObjectArray(0, env->FindClass("java/lang/String"), NULL); /* call the method */ env->CallStaticVoidMethod(main_class, main_method_id, empty_args); /* Don't forget to destroy the JVM at the end */ jvm->DestroyJavaVM(); dlclose(lib_handle); return (0); } catch (const std::runtime_error& e) { ShowAlert("Did you install Java JDK 8 or later?", e); exit(-1); } }
int main(){ JavaVM * jvm; JNIEnv * env; JavaVMOption * options = new JavaVMOption[1]; options[0].optionString = const_cast< char* >( "-Djava.class.path=." ); JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_6; vmArgs.nOptions = 1; vmArgs.options = options; vmArgs.ignoreUnrecognized = false; jint rc = JNI_CreateJavaVM( & jvm, ( void** )( & env ), & vmArgs ); if( rc != JNI_OK ){ std::cerr << "errorCode: " << rc << std::endl; return 1; } { jclass cls = env->FindClass( "Main" ); if( cls == nullptr ){ std::cerr << "Could not find class 'Main'" << std::endl; return 2; } { /* * static void */ jmethodID methodId = env->GetStaticMethodID( cls, "function", "()V" ); if( methodId == nullptr ){ std::cerr << "Could not find method 'void function()'" << std::endl; return 3; } env->CallStaticVoidMethod( cls, methodId ); } { /* * static with parameters and return value */ jmethodID methodId = env->GetStaticMethodID( cls, "function2", "(I)I" ); if( methodId == nullptr ){ std::cerr << "Could not find method 'int function2(int)'" << std::endl; return 4; } jint result = env->CallStaticIntMethod( cls, methodId, ( jint )( 5 ) ); assert( ( int )( result ) == 10 ); } { /* * method */ jmethodID methodId = env->GetMethodID( cls, "<init>", "()V" ); if( methodId == nullptr ){ std::cerr << "Could not find method '<init>'" << std::endl; return 5; } jobject object = env->NewObject( cls, methodId ); if( object == nullptr ){ std::cerr << "Could not construct an object" << std::endl; return 6; } methodId = env->GetMethodID( cls, "getId", "()I" ); if( methodId == nullptr ){ std::cerr << "Could not find method 'getId'" << std::endl; return 7; } jint result = env->CallIntMethod( object, methodId ); assert( ( int )( result ) == 14 ); } } jvm->DestroyJavaVM(); delete options; }
void* launchVM(void* params) { std::string execDir = getExecutableDir(); std::ifstream configFile; configFile.open((execDir + std::string("/config.json")).c_str()); printf("config file: %s\n", (execDir + std::string("/config.json")).c_str()); picojson::value json; configFile >> json; std::string err = picojson::get_last_error(); if(!err.empty()) { printf("Couldn't parse json: %s\n", err.c_str()); } std::string jarFile = execDir + std::string("/") + json.get<picojson::object>()["jar"].to_str(); std::string main = json.get<picojson::object>()["mainClass"].to_str(); std::string classPath = std::string("-Djava.class.path=") + jarFile; picojson::array vmArgs = json.get<picojson::object>()["vmArgs"].get<picojson::array>(); printf("jar: %s\n", jarFile.c_str()); printf("mainClass: %s\n", main.c_str()); JavaVMOption* options = (JavaVMOption*)malloc(sizeof(JavaVMOption) * (1 + vmArgs.size())); options[0].optionString = (char*)classPath.c_str(); for(unsigned i = 0; i < vmArgs.size(); i++) { options[i+1].optionString = (char*)vmArgs[i].to_str().c_str(); printf("vmArg %d: %s\n", i, options[i+1].optionString); } JavaVMInitArgs args; args.version = JNI_VERSION_1_6; args.nOptions = 1 + (int)vmArgs.size(); args.options = options; args.ignoreUnrecognized = JNI_FALSE; JavaVM* jvm = 0; JNIEnv* env = 0; #ifndef WINDOWS #ifdef MACOSX std::string jre = execDir + std::string("/jre/lib/server/libjvm.dylib"); #elif defined(__LP64__) std::string jre = execDir + std::string("/jre/lib/amd64/server/libjvm.so"); #else std::string jre = execDir + std::string("/jre/lib/i386/server/libjvm.so"); #endif printf("jre: %s\n", jre.c_str()); void* handle = dlopen(jre.c_str(), RTLD_LAZY); if(handle == NULL) { fprintf(stderr, "%s\n", dlerror()); exit(EXIT_FAILURE); } PtrCreateJavaVM ptrCreateJavaVM = (PtrCreateJavaVM)dlsym(handle, "JNI_CreateJavaVM"); if(ptrCreateJavaVM == NULL) { fprintf(stderr, "%s\n", dlerror()); exit(EXIT_FAILURE); } #else HINSTANCE hinstLib = LoadLibrary(TEXT("jre\\bin\\server\\jvm.dll")); PtrCreateJavaVM ptrCreateJavaVM = (PtrCreateJavaVM)GetProcAddress(hinstLib,"JNI_CreateJavaVM"); #endif if(!changeWorkingDir(execDir)) { printf("Couldn't change working directory to: %s\n", execDir.c_str()); } jint res = ptrCreateJavaVM(&jvm, (void**)&env, &args); if(res < 0) { fprintf(stderr, "Failed to create Java VM\n"); exit(EXIT_FAILURE); } jobjectArray appArgs = env->NewObjectArray(g_argc, env->FindClass("java/lang/String"), NULL); for(int i = 0; i < g_argc; i++) { jstring arg = env->NewStringUTF(g_argv[i]); env->SetObjectArrayElement(appArgs, i, arg); } jclass mainClass = env->FindClass(main.c_str()); jmethodID mainMethod = env->GetStaticMethodID(mainClass, "main", "([Ljava/lang/String;)V"); if(mainMethod == 0) { fprintf(stderr, "Failed to aquire main() method of class: %s:\n", main.c_str()); exit(EXIT_FAILURE); } env->CallStaticVoidMethod(mainClass, mainMethod, appArgs); jvm->DestroyJavaVM(); return 0; }
extern "C" EXPORT int avianMain(const char* bootLibrary, int ac, const char** av) { JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_2; vmArgs.nOptions = 3; vmArgs.ignoreUnrecognized = JNI_TRUE; JavaVMOption options[vmArgs.nOptions]; vmArgs.options = options; options[0].optionString = (char*) "-Davian.bootimage=bootimageBin"; options[1].optionString = (char*) "-Davian.codeimage=codeimageBin"; options[2].optionString = (char*) "-Xbootclasspath:[bootJar]:[resourcesJar]"; char* buffer; if (bootLibrary) { const char* const property = "-Davian.bootstrap="; const unsigned propertySize = strlen(property); const unsigned bootLibrarySize = strlen(bootLibrary); buffer = static_cast<char*>(malloc(propertySize + bootLibrarySize + 1)); memcpy(buffer, property, propertySize); memcpy(buffer + propertySize, bootLibrary, bootLibrarySize); buffer[propertySize + bootLibrarySize] = 0; vmArgs.options[vmArgs.nOptions++].optionString = buffer; } else { buffer = 0; } JavaVM* vm; void* env; JNI_CreateJavaVM(&vm, &env, &vmArgs); JNIEnv* e = static_cast<JNIEnv*>(env); jclass c = e->FindClass(MAIN_CLASS); if (not e->ExceptionCheck()) { jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); if (not e->ExceptionCheck()) { jclass stringClass = e->FindClass("java/lang/String"); if (not e->ExceptionCheck()) { jobjectArray a = e->NewObjectArray(ac-1, stringClass, 0); if (not e->ExceptionCheck()) { for (int i = 1; i < ac; ++i) { e->SetObjectArrayElement(a, i-1, e->NewStringUTF(av[i])); } e->CallStaticVoidMethod(c, m, a); } } } } int exitCode = 0; if (e->ExceptionCheck()) { exitCode = -1; e->ExceptionDescribe(); } vm->DestroyJavaVM(); if (buffer) { free(buffer); } return exitCode; }
bool finalize() { jint res = jvm->DestroyJavaVM(); //return ( ! env->ExceptionOccurred() ); //Note, this will always fail according to DestroyJavaVM specification return res >= 0; }
/* * Main program to invoke Java runtime using JNI invocation API. Supports * setting of VM arguments through standard command line options. */ void main(int argc, char *argv[]) { bool isJava2 = false; JRESettings set; void *handle; JDK1_1InitArgs vmargs; JavaVM *jvm; JNIEnv *env; // char *s, *name; jclass cls; jmethodID mid; jarray args; int i; /* First scan arguments for help and debug options */ for (i = 1; i < argc; i++) { char *arg = argv[i]; if (*arg++ != '-') { break; } if (strcmp(arg, "?") == 0 || strcmp(arg, "h") == 0 || strcmp(arg, "help") == 0) { PrintUsage(); exit(1); } #ifdef JRE_DEBUG if (strcmp(arg, "d") == 0) { debug = JNI_TRUE; } #endif } /* Get runtime settings */ #ifdef VERSION if (JRE_GetSettings(&set, VERSION) != 0) { #else if (JRE_GetCurrentSettings(&set) != 0) { #endif if (JRE_GetDefaultSettings(&set) != 0) { // fprintf(stderr, "Could not locate Java runtime\n"); MessageBox(NULL,"Could not locate Java runtime","",MB_OK); exit(1); } } short majorVers = 0; short minorVers = 0; if(set.majorVersion){ majorVers = atoi(set.majorVersion); } if(set.minorVersion){ minorVers = atoi(set.minorVersion); } isJava2 = ((majorVers > 1) || (minorVers > 1)); #ifdef JRE_DEBUG if (debug) { char *ver = JRE_MakeVersion(set.majorVersion, set.minorVersion, set.microVersion); fprintf(stderr, "Runtime Settings:\n"); fprintf(stderr, " javaHome = %s\n", set.javaHome != 0 ? set.javaHome : "<not set>"); fprintf(stderr, " runtimeLib = %s\n", set.runtimeLib != 0 ? set.runtimeLib : "<not set>"); fprintf(stderr, " version = %s\n", ver != 0 ? ver : "<not set>"); fprintf(stderr, " compiler = %s\n\n", set.compiler != 0 ? set.compiler : "<not set>"); } #endif /* Load runtime library */ // char testNetscapeJVMPATH[1024]; // strcpy(testNetscapeJVMPATH,"C:\\Program Files\\Netscape\\Communicator\\Program\\jrt3240.dll"); // handle = JRE_LoadLibrary(testNetscapeJVMPATH); handle = JRE_LoadLibrary(set.runtimeLib); if (handle == 0) { //winerror.h DWORD err = GetLastError(); // fprintf(stderr, "Could not load runtime library: %s error %u\n",set.runtimeLib,err); char messageStr[1024]; sprintf(messageStr,"Could not load runtime library: %s error %u",set.runtimeLib,err); MessageBox(NULL,messageStr,"",MB_OK); exit(1); } /* Parse command line options */ --argc; argv++; if (ParseOptions(&argc, &argv, &vmargs) != 0) { PrintUsage(); exit(1); } /* Get name of class */ if (*argv == 0) { PrintUsage(); exit(1); } /* name = (char *)_strdup(*argv++); for (s = name; *s != '\0'; s++) { if (*s == '.') *s = '/'; } --argc; */ /* * The following is used to specify that we require at least * JNI version 1.1. Currently, this field is not checked but * will be starting with JDK/JRE 1.2. The value returned after * calling JNI_GetDefaultJavaVMInitArgs() is the actual JNI version * supported, and is always higher that the requested version. */ bool errorCreateVM = true; if(isJava2){ char *newPath = (char *)JRE_Malloc(strlen("-Djava.class.path=")+strlen(addClassPath)+strlen(set.classPath)+1);// for symbol ; strcpy(newPath,"-Djava.class.path="); strcat(newPath,addClassPath); strcat(newPath,set.classPath); // char *newLibPath = (char *)JRE_Malloc(strlen((char *)nativeLibPath)+strlen("-Djava.library.path=")+1); JavaVMInitArgs vm_args; JavaVMOption options[1]; options[0].optionString = newPath; /* user classes */ // options[1].optionString = newLibPath; /* set native library path */ // options[2].optionString = "-Djava.compiler=NONE"; /* disable JIT */ // options[3].optionString = "-verbose:jni"; /* print JNI-related messages */ vm_args.version = JNI_VERSION_1_2; vm_args.options = options; vm_args.nOptions = 1; vm_args.ignoreUnrecognized = JNI_FALSE; errorCreateVM = (JRE_CreateJavaVM((HINSTANCE)handle, &jvm, &env, &vm_args) != 0); free(newPath); // free(newLibPath); }else{ /* Add pre-defined system properties */ if (set.javaHome != 0) { char *def = (char *)JRE_Malloc(strlen(set.javaHome) + 16); sprintf(def, "java.home=%s", set.javaHome); AddProperty(def); } if (set.compiler != 0) { char *def = (char *)JRE_Malloc(strlen(set.compiler) + 16); sprintf(def, "java.compiler=%s", set.compiler); AddProperty(def); } vmargs.version = 0x00010001; char newPath[1024]; strcpy(newPath,".;"); strcat(newPath,addClassPath); strcat(newPath,set.classPath); if (JRE_GetDefaultJavaVMInitArgs(handle, &vmargs) != 0) { // fprintf(stderr, "Could not initialize Java VM\n"); MessageBox(NULL,"Could not initialize Java VM","",MB_OK); exit(1); } vmargs.classpath = newPath; #ifdef JRE_DEBUG if (debug) { fprintf(stderr, "CLASSPATH is %s\n\n", vmargs.classpath); } #endif /* Set user-defined system properties for Java VM */ if (props != 0) { if (numProps == maxProps) { char **tmp = (char **)JRE_Malloc((numProps + 1) * sizeof(char **)); memcpy(tmp, props, numProps * sizeof(char **)); free(props); props = tmp; } props[numProps] = 0; vmargs.properties = props; } /* Load and initialize Java VM */ errorCreateVM = (JRE_CreateJavaVM(handle, &jvm, &env, &vmargs) != 0); } if (errorCreateVM) { // fprintf(stderr, "Could not create Java VM\n"); MessageBox(NULL,"Could not create Java VM","",MB_OK); exit(1); } /* Free properties */ if (props != 0) { free(props); } /* Find class */ cls = env->FindClass(mainWabaClassName); if (cls == 0) { // fprintf(stderr, "Class not found: %s\n", *--argv); char messageStr[1024]; sprintf(messageStr,"Class not found: %s", *--argv); MessageBox(NULL,messageStr,"",MB_OK); exit(1); } /* Find main method of class */ mid = env->GetStaticMethodID( cls, "main", "([Ljava/lang/String;)V"); if (mid == 0) { // fprintf(stderr, "In class %s: public static void main(String args[]) is not defined\n",mainWabaClassName); char messageStr[1024]; sprintf(messageStr,"In class %s: public static void main(String args[]) is not defined\n",mainWabaClassName); MessageBox(NULL,messageStr,"",MB_OK); exit(1); } /* Invoke main method */ args = NewStringArray(env, argv, argc); if (args == 0) { JRE_FatalError(env, "Couldn't build argument list for main\n"); } env->CallStaticVoidMethod(cls, mid, args); if (env->ExceptionOccurred()) { env->ExceptionDescribe(); } /* Wait until we are the only user thread remaining then unload VM */ jvm->DestroyJavaVM(); /* Unload the runtime */ JRE_UnloadLibrary(handle); } /* * Parses command line VM options. Returns 0 if successful otherwise * returns -1 if an invalid option was encountered. */ jint ParseOptions(int *argcp, char ***argvp, JDK1_1InitArgs *vmargs) { char *arg, **argv = *argvp; while ((arg = *argv++) != 0 && *arg++ == '-') { if (strcmp(arg, "classpath") == 0) { if (*argv == 0) { // fprintf(stderr, "No class path given for %s option\n", arg); char messageStr[1024]; sprintf(messageStr,"No class path given for %s option", arg); MessageBox(NULL,messageStr,"",MB_OK); return -1; } vmargs->classpath = *argv++; } else if (strcmp(arg, "cp") == 0) { char *cp = vmargs->classpath; if (*argv == 0) { // fprintf(stderr, "No class path given for %s option\n", arg); char messageStr[1024]; sprintf(messageStr,"No class path given for %s option", arg); MessageBox(NULL,messageStr,"",MB_OK); return -1; } vmargs->classpath = (char *)malloc(strlen(*argv) + strlen(cp) + 2); if (vmargs->classpath == 0) { perror("malloc"); exit(1); } sprintf(vmargs->classpath, "%s%c%s", *argv++, PATH_SEPARATOR, cp); } else if (strncmp(arg, "D", 1) == 0) { AddProperty(arg + 1); } else if (strncmp(arg, "ss", 2) == 0) { jint n = atoml(arg + 2); if (n >= 1000) { vmargs->nativeStackSize = n; } } else if (strncmp(arg, "oss", 3) == 0) { jint n = atoml(arg + 3); if (n >= 1000) { vmargs->javaStackSize = n; } } else if (strncmp(arg, "ms", 2) == 0) { jint n = atoml(arg + 2); if (n >= 1000) { vmargs->minHeapSize = n; } } else if (strncmp(arg, "mx", 2) == 0) { jint n = atoml(arg + 2); if (n >= 1000) { vmargs->maxHeapSize = n; } } else if (strcmp(arg, "noasyncgc") == 0) { vmargs->disableAsyncGC = JNI_TRUE; } else if (strcmp(arg, "noclassgc") == 0) { vmargs->enableClassGC = JNI_FALSE; } else if (strcmp(arg, "verify") == 0) { vmargs->verifyMode = 2; } else if (strcmp(arg, "verifyremote") == 0) { vmargs->verifyMode = 1; } else if (strcmp(arg, "noverify") == 0) { vmargs->verifyMode = 0; } else if (strcmp(arg, "nojit") == 0) { /** * Set the value of java.compiler equal to the empty * string. At the jit library loading step nothing will * loaded. */ AddProperty("java.compiler="); } else if (strcmp(arg, "v") == 0 || strcmp(arg, "verbose") == 0) { vmargs->verbose = JNI_TRUE; #ifdef JRE_DEBUG } else if (strcmp(arg, "d") == 0) { debug = JNI_TRUE; #endif } else if (strcmp(arg, "verbosegc") == 0) { vmargs->enableVerboseGC = JNI_TRUE; } else if (strcmp(arg, "?") == 0 || strcmp(arg, "h") == 0 || strcmp(arg, "help") == 0) { return -1; } else { // fprintf(stderr, "Illegal option: -%s\n", arg); char messageStr[1024]; sprintf(messageStr,"Illegal option: -%s", arg); MessageBox(NULL,messageStr,"",MB_OK); return -1; } } *argcp -= --argv - *argvp; *argvp = argv; return 0; }