Exemplo n.º 1
0
JNIEXPORT jint JNICALL Java_com_apple_dnssd_AppleDNSSD_InitLibrary( JNIEnv *pEnv, jclass cls,
						jint callerVersion)
{
	/* Ensure that caller & interface versions match. */
	if ( callerVersion != kInterfaceVersion)
		return kDNSServiceErr_Incompatible;

#if AUTO_CALLBACKS
	{
		jsize	numVMs;
	
		if ( 0 != JNI_GetCreatedJavaVMs( &gJavaVM, 1, &numVMs))
			return kDNSServiceErr_BadState;
	}
#endif

	// Set AppleDNSSD.hasAutoCallbacks
	{
#if AUTO_CALLBACKS
		jboolean	hasAutoC = JNI_TRUE;
#else
		jboolean	hasAutoC = JNI_FALSE;
#endif
		jfieldID	hasAutoCField = (*pEnv)->GetStaticFieldID( pEnv, cls, "hasAutoCallbacks", "Z");
		(*pEnv)->SetStaticBooleanField( pEnv, cls, hasAutoCField, hasAutoC);
	}

	return kDNSServiceErr_NoError;
}
Exemplo n.º 2
0
void initJVM()
{
   if (_pVMJvm != NULL)
      return;

   JNIEnv* pVMEnv = NULL;
#ifdef _WIN32
   HMODULE handle = LoadLibraryA(_jrePath.c_str());
#else
   void *handle = dlopen(_jrePath.c_str(), RTLD_NOW);
#endif
   if (handle == NULL)
      throw std::runtime_error("initJVM: unable to load libjvm.");

   JNI_GetCreatedJavaVMs_t JNI_GetCreatedJavaVMs = (JNI_GetCreatedJavaVMs_t) LoadSym(handle, "JNI_GetCreatedJavaVMs");
   if (JNI_GetCreatedJavaVMs == NULL)
      JNI_GetCreatedJavaVMs = (JNI_GetCreatedJavaVMs_t) LoadSym(handle, "JNI_GetCreatedJavaVMs_Impl");
   if (JNI_GetCreatedJavaVMs == NULL)
      throw std::runtime_error("initJVM: unable to find method JNI_GetCreatedJavaVMs.");

   // try to get an already created JVM
   jsize nbVMs = 0;
   JNI_GetCreatedJavaVMs(&_pVMJvm, 1, &nbVMs);
   if (nbVMs == 0)
   {
      // Else : create a new JVM
      setClassPath();
      jint nbOptions = (jint) _options.size();
      JavaVMOption *aOptions = new JavaVMOption[nbOptions];
      for (jint i = 0; i < nbOptions; ++i)
         aOptions[i].optionString = (char*) _options[i].c_str();

      JavaVMInitArgs oVMArgs;
      memset(&oVMArgs, 0, sizeof(oVMArgs));
      oVMArgs.version = JNI_VERSION_1_6;
      oVMArgs.nOptions = nbOptions;
      oVMArgs.options = aOptions;

      JNI_CreateJavaVM_t JNI_CreateJavaVM = (JNI_CreateJavaVM_t) LoadSym(handle, "JNI_CreateJavaVM");
      if (JNI_CreateJavaVM == NULL)
         JNI_CreateJavaVM = (JNI_CreateJavaVM_t) LoadSym(handle, "JNI_CreateJavaVM_Impl");
      if (JNI_CreateJavaVM == NULL)
         throw std::runtime_error("initJVM: unable to find method JNI_CreateJavaVM.");

      jint result = JNI_CreateJavaVM(&_pVMJvm, (void**) &pVMEnv, (void*) &oVMArgs);
      if (result != 0)
      {
         std::ostringstream oss;
         oss << "initJVM: can't create new JVM (" << result << ").";
         throw std::runtime_error(oss.str());
      }

      delete[] aOptions;
   }
}
short initJVM()
{
  jint result;

  if ((_tlp_jenv != 0) && (_tlv_jenv_set)) {
    return TestJOI_OK;
  }

  if (gp_jvm == NULL)
  {
    jsize jvm_count = 0;
    // Is there an existing JVM?
    result = JNI_GetCreatedJavaVMs (&gp_jvm, 1, &jvm_count);
    if (result != JNI_OK)
      return TestJOI_ERROR_CHECK_JVM;
      
    if (jvm_count == 0)
    {
      test_createJVM();
      return 0;
    }
  }

  // We found a JVM, can we use it?
  result = gp_jvm->GetEnv((void**) &_tlp_jenv, JNI_VERSION_1_6);
  switch (result)
  {
    case JNI_OK:
      break;
    
    case JNI_EDETACHED:
      printf("initJVM: Detached, Try 2 attach\n");
      result = gp_jvm->AttachCurrentThread((void**) &_tlp_jenv, NULL);   
      if (result != JNI_OK)
	{
	  printf("initJVM: Error in attaching\n");
	  return TestJOI_ERROR_ATTACH_JVM;
	}
      
      break;
       
    case JNI_EVERSION:
      return TestJOI_ERROR_JVM_VERSION;
      break;
      
    default:
      return TestJOI_ERROR_ATTACH_JVM;
      break;
  }

  _tlv_jenv_set = true;

  return TestJOI_OK;
}
Exemplo n.º 4
0
NITFPROT(int) _GetJNIEnv(JavaVM** vm, JNIEnv** env)
{
    jsize num = 0;
    jint status = JNI_GetCreatedJavaVMs(vm, 1, &num);
    status = (**vm)->GetEnv(*vm, (void**)env, JNI_VERSION_1_4);
    
    if (env == NULL && status == JNI_EDETACHED)
    {
        //attach the current thread
        status = (**vm)->AttachCurrentThread(*vm, (void**)env, NULL);
        return 1;
    }
    return 0;
}
Exemplo n.º 5
0
void sysOutPrint(const char* cstr, ...)
{
	if (!g_vmBuf)
	{
		jsize numVMs;
		if (JNI_GetCreatedJavaVMs(&g_vmBuf, 1, &numVMs))
			return;
	}
	JNIEnv* env;
	jint threadState = g_vmBuf->GetEnv((void**)&env, JNI_VERSION_1_2);
	if (threadState == JNI_EDETACHED)
		g_vmBuf->AttachCurrentThread((void**)&env, NULL);
	jthrowable oldExcept = env->ExceptionOccurred();
	if (oldExcept)
		env->ExceptionClear();
    va_list args;
    va_start(args, cstr);
    char buf[1024];
    //vsprintf(buf, cstr, args);

#ifdef WIN32
	_invalid_parameter_handler oldHandler, newHandler;
	newHandler = myInvalidParameterHandler;
	oldHandler = _set_invalid_parameter_handler(newHandler);
	int num = vsprintf_s(buf, sizeof(buf)-1 , cstr, args);
	if ( num > sizeof( buf ) || num < 0 )
	{
		strcpy_s( buf, sizeof( buf ), "ERROR: sysOutPrint buffer overrun, slog crashs here.\r\n" ); 
	}
	_set_invalid_parameter_handler(oldHandler);
#else
	//vsprintf(buf, cstr, args);
	int num = vsnprintf(buf, sizeof(buf), cstr, args);
#endif

    va_end(args);
	jstring jstr = env->NewStringUTF(buf);
	static jclass cls = (jclass) env->NewGlobalRef(env->FindClass("java/lang/System"));
	static jfieldID outField = env->GetStaticFieldID(cls, "out", "Ljava/io/PrintStream;");
	static jmethodID printMeth = env->GetMethodID(env->FindClass("java/io/PrintStream"),
		"print", "(Ljava/lang/String;)V");
	jobject outObj = env->GetStaticObjectField(cls, outField);
	env->CallVoidMethod(outObj, printMeth, jstr);
	env->DeleteLocalRef(jstr);
	if (oldExcept)
		env->Throw(oldExcept);
	if (threadState == JNI_EDETACHED)
		g_vmBuf->DetachCurrentThread();
}
Exemplo n.º 6
0
// This is the harder trick:  Pull the current state out of mid-air.
static unpacker* get_unpacker() {
  //fprintf(stderr, "get_unpacker()\n");
  JavaVM* vm = null;
  JNI_GetCreatedJavaVMs(&vm, 1, null);
  void* envRaw = null;
  vm->GetEnv(&envRaw, JNI_VERSION_1_1);
  JNIEnv* env = (JNIEnv*) envRaw;
  //fprintf(stderr, "get_unpacker() env=%p\n", env);
  if (env == null)
    return null;
  jobject pObj = env->CallStaticObjectMethod(NIclazz, currentInstMID);
  //fprintf(stderr, "get_unpacker() pObj=%p\n", pObj);
  if (pObj == null)
    return null;
  // Got pObj and env; now do it the easy way.
  return get_unpacker(env, pObj);
}
Exemplo n.º 7
0
vector<JavaVM *> JNIKit::listJvms() {
	vector<JavaVM *> vms;

	// Make call to JNI to acquire the list of VMs..
	JavaVM *temp[64];
	jint count;
	jint result = JNI_GetCreatedJavaVMs(temp, 64, &count);

	// Did it fail?
	if (result != JNI_OK)
		throw JNIError("could not obtain jvm list");

	// And put them neatly in a vec.
	for (int i = 0; i < count; i++) {
		vms.push_back(temp[i]);
	}

	return vms;
}
static JavaVM* PV_GetCurrentVM(void)
{
    JavaVM*		vmArray[2];
    jsize		count;
    jint		result;

    count = 0;
    result = JNI_GetCreatedJavaVMs(vmArray, 2, &count);	// ask for 2
    if ((result == 0) && (count >= 1))						// error if not just 1
	{
	    if (count > 1)
		{
		    DEBUG_STR("WARNING:  JNI_GetCreatedJavaVMs() returned >1 VMs\n");
		}
	    return vmArray[0];
	}
    DEBUG_STR("JNI_GetCreatedJavaVMs() returned error\n");
    return NULL;
}
Exemplo n.º 9
0
JavaVM *aitk_resolve_local_jvm()
{
    JavaVM *gVm = NULL;

    int n;
    JavaVM* jvms[1];

    if ((JNI_GetCreatedJavaVMs(jvms, 1, &n) != JNI_OK) || (n == 0))
    {
        ddi_log_printf("Failed to resolve any Java VM !\n");
    }
    else 
    {
        gVm = jvms[0];
        ddi_log_printf("Local VM: %x\n", gVm); 
    }

    return gVm;
}
Exemplo n.º 10
0
long postMessage( char* pSrc, char* pData, int nDataLen, int MsgType, int Priority )
{
	JNIEnv* env;

	//we sould have a lock here, for mutiple thread

	if (!vmBuf)
	{
		if (JNI_GetCreatedJavaVMs(&vmBuf, 1, &numVMs))
		{
			return -1;
		}
	}

	jint threadState = vmBuf->GetEnv((void**)&env, JNI_VERSION_1_2);
	if (threadState == JNI_EDETACHED)
	{
		vmBuf->AttachCurrentThread((void**)&env, NULL);
	}

	if ( !msgMgrClass )
	{
		msgMgrClass = (jclass) env->NewGlobalRef(env->FindClass("sage/msg/MsgManager"));
		if (msgMgrClass)
			postMsgMeth = env->GetStaticMethodID(msgMgrClass, "postMessage", "(Lsage/msg/SageMsg;)V");
		msgClass = (jclass) env->NewGlobalRef(env->FindClass("sage/msg/SageMsg"));
		if (msgClass)
			msgConstructor = env->GetMethodID(msgClass, "<init>", "(ILjava/lang/Object;Ljava/lang/Object;I)V");
	}

	int dataLen = nDataLen;
	jbyteArray javaData = env->NewByteArray(dataLen);
	env->SetByteArrayRegion(javaData, 0, dataLen, (const jbyte*)pData);
	jobject msgObj = env->NewObject( msgClass, msgConstructor, MsgType, env->NewStringUTF(pSrc), 
										javaData, Priority );
	env->CallStaticVoidMethod( msgMgrClass, postMsgMeth, msgObj );
	msg_id++;

	if ( threadState == JNI_EDETACHED )
		vmBuf->DetachCurrentThread();

	return 0;
}
Exemplo n.º 11
0
	int helper::get_jvmenv(JNIEnv* &jnienv, JavaVM* &javavm)
	{
		jint size = 1; //?
		jint vmCount;
		int ret = JNI_GetCreatedJavaVMs(&javavm, size, &vmCount);

		if (ret<0){
			std::cout << "Cannot get a created jvm" << std::endl;
			return ret;
		}

		ret = javavm->AttachCurrentThread((void **)&jnienv, NULL);

		if (ret<0){
			std::cout << "Cannot attach to jvm" << std::endl;
			return ret;
		}

		return ret;
	}
Exemplo n.º 12
0
void PlugletEngine::StartJVM() {
    JNIEnv *env = NULL;
    jint res;
    jsize jvmCount;
    JNI_GetCreatedJavaVMs(&jvm, 1, &jvmCount);
    if (jvmCount) {
        PR_LOG(PlugletLog::log, PR_LOG_DEBUG,
               ("PlugletEngine::StartJVM we got already started JVM\n"));
        return;
    }
    char classpath[1024]="";
    char debug[256]="";
    char runjdwp[256]="";
    sprintf(debug, "-Xdebug");
    sprintf(runjdwp, 
            "-Xrunjdwp:transport=dt_shmem,address=jdbconn,server=y,suspend=y");
    JavaVMInitArgs vm_args;
    JavaVMOption options[4];
    char * classpathEnv = PR_GetEnv("CLASSPATH");
    if (classpathEnv != NULL) {
        sprintf(classpath, "-Djava.class.path=%s",classpathEnv);
        PR_LOG(PlugletLog::log, PR_LOG_DEBUG,
               ("PlugletEngine::StartJVM about to create JVM classpath=%s\n",classpath));
    }
    options[0].optionString = classpath;
    options[1].optionString = debug;
    options[2].optionString = runjdwp;
    options[3].optionString=""; //-Djava.compiler=NONE";
    vm_args.version = JNI_VERSION_1_4;
    vm_args.options = options;
    vm_args.nOptions = 1; // EDBURNS: Change to 3 for debugging, 1 for non-debuging
    vm_args.ignoreUnrecognized = JNI_FALSE;
    /* Create the Java VM */
    PR_LOG(PlugletLog::log, PR_LOG_DEBUG,
           ("PlugletEngine::StartJVM about to start JVM with options %s %s %s\n",
            options[0].optionString, options[1].optionString, 
            options[2].optionString));
    res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    PR_LOG(PlugletLog::log, PR_LOG_DEBUG,
           ("PlugletEngine::StartJVM after CreateJavaVM res = %d\n",res));
}
JavaVMSingleton::JavaVMSingleton(const char* classPath, const char* javaLibPath)
{
  JavaVM *jvms;
  jsize nVMs;
  if ( JNI_GetCreatedJavaVMs(&jvms, 1, &nVMs) == 0 )
  {
    if (nVMs == 1)
    {
      JavaVM *jvm = jvms;
      JNIEnv *env;
      if( jvm->AttachCurrentThread((void **)&env, NULL) == 0)
      {
        init(jvm, env);
        return;
      }
      else
        throw VMOpenException();
    }
  }

  init(classPath, javaLibPath);
}
// static
void *TimedEventQueue::ThreadWrapper(void *me) {

#ifdef ANDROID_SIMULATOR
    // The simulator runs everything as one process, so any
    // Binder calls happen on this thread instead of a thread
    // in another process. We therefore need to make sure that
    // this thread can do calls into interpreted code.
    // On the device this is not an issue because the remote
    // thread will already be set up correctly for this.
    JavaVM *vm;
    int numvms;
    JNI_GetCreatedJavaVMs(&vm, 1, &numvms);
    JNIEnv *env;
    vm->AttachCurrentThread(&env, NULL);
#endif

    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_FOREGROUND);
    static_cast<TimedEventQueue *>(me)->threadEntry();

#ifdef ANDROID_SIMULATOR
    vm->DetachCurrentThread();
#endif
    return NULL;
}
Exemplo n.º 15
0
/** get java environment for the current thread or 0 if something goes wrong. */
static JNIEnv *getJNIEnv() {
    JNIEnv *env;
    jsize l;
    jint res = 0;
    
    if (!jvm) { /* we're hoping that the JVM pointer won't change :P we fetch it just once */
        res = JNI_GetCreatedJavaVMs(&jvm, 1, &l);
        if (res != 0) {
	  fprintf(stderr, "JNI_GetCreatedJavaVMs failed! (%d)\n", (int)res); return 0;
        }
        if (l<1) {
	  /* fprintf(stderr, "JNI_GetCreatedJavaVMs said there's no JVM running!\n"); */ return 0;
        }
	if (!jvm)
	  error("Unable to get JVM handle");
    }
    res = (*jvm)->AttachCurrentThread(jvm, (void**) &env, 0);
    if (res!=0) {
        fprintf(stderr, "AttachCurrentThread failed! (%d)\n", (int)res); return 0;
    }
    /* if (eenv!=env)
        fprintf(stderr, "Warning! eenv=%x, but env=%x - different environments encountered!\n", eenv, env); */
    return env;
}
Exemplo n.º 16
0
/*
 * The function handling notify callbacks. It casts the pApplication paramter
 * back to a NotifyEncapsulation structure and retrieves the Notify object and
 * the application data from it.
 *
 * @param hSession The session, this callback is comming from.
 * @param event The type of event that occurred.
 * @param pApplication The application data as passed in upon OpenSession. In
                       this wrapper we always pass in a NotifyEncapsulation
                       object, which holds necessary information for delegating
                       the callback to the Java VM.
 * @return
 */
CK_RV notifyCallback(
    CK_SESSION_HANDLE hSession,     /* the session's handle */
    CK_NOTIFICATION   event,
    CK_VOID_PTR       pApplication  /* passed to C_OpenSession */
)
{
    NotifyEncapsulation *notifyEncapsulation;
    JavaVM *jvm;
    JNIEnv *env;
    jsize actualNumberVMs;
    jint returnValue;
    jlong jSessionHandle;
    jlong jEvent;
    jclass ckNotifyClass;
    jmethodID jmethod;
    jthrowable pkcs11Exception;
    jclass pkcs11ExceptionClass;
    jlong errorCode;
    CK_RV rv = CKR_OK;
    int wasAttached = 1;

    if (pApplication == NULL) { return rv ; } /* This should not occur in this wrapper. */

    notifyEncapsulation = (NotifyEncapsulation *) pApplication;

    /* Get the currently running Java VM */
    returnValue = JNI_GetCreatedJavaVMs(&jvm, (jsize) 1, &actualNumberVMs);
    if ((returnValue != 0) || (actualNumberVMs <= 0)) { return rv ; } /* there is no VM running */

    /* Determine, if current thread is already attached */
    returnValue = (*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_2);
    if (returnValue == JNI_EDETACHED) {
        /* thread detached, so attach it */
        wasAttached = 0;
        returnValue = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL);
    } else if (returnValue == JNI_EVERSION) {
        /* this version of JNI is not supported, so just try to attach */
        /* we assume it was attached to ensure that this thread is not detached
         * afterwards even though it should not
         */
        wasAttached = 1;
        returnValue = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL);
    } else {
        /* attached */
        wasAttached = 1;
    }

    jSessionHandle = ckULongToJLong(hSession);
    jEvent = ckULongToJLong(event);

    ckNotifyClass = (*env)->FindClass(env, CLASS_NOTIFY);
    if (ckNotifyClass == NULL) { return rv; }
    jmethod = (*env)->GetMethodID(env, ckNotifyClass, "CK_NOTIFY", "(JJLjava/lang/Object;)V");
    if (jmethod == NULL) { return rv; }

    (*env)->CallVoidMethod(env, notifyEncapsulation->jNotifyObject, jmethod,
                         jSessionHandle, jEvent, notifyEncapsulation->jApplicationData);

    /* check, if callback threw an exception */
    pkcs11Exception = (*env)->ExceptionOccurred(env);

    if (pkcs11Exception != NULL) {
        /* TBD: clear the pending exception with ExceptionClear? */
        /* The was an exception thrown, now we get the error-code from it */
        pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
        if (pkcs11ExceptionClass == NULL) { return rv; }

        jmethod = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
        if (jmethod == NULL) { return rv; }

        errorCode = (*env)->CallLongMethod(env, pkcs11Exception, jmethod);
        rv = jLongToCKULong(errorCode);
    }

    /* if we attached this thread to the VM just for callback, we detach it now */
    if (wasAttached) {
        returnValue = (*jvm)->DetachCurrentThread(jvm);
    }

    return rv ;
}
Exemplo n.º 17
0
/**
 * getJNIEnv: A helper function to get the JNIEnv* for the given thread.
 * If no JVM exists, then one will be created. JVM command line arguments
 * are obtained from the LIBHDFS_OPTS environment variable.
 *
 * @param: None.
 * @return The JNIEnv* corresponding to the thread.
 */
JNIEnv* getJNIEnv(void)
{

    const jsize vmBufLength = 1;
    JavaVM* vmBuf[vmBufLength]; 
    JNIEnv *env;
    jint rv = 0; 
    jint noVMs = 0;

    // Only the first thread should create the JVM. The other trheads should
    // just use the JVM created by the first thread.
    LOCK_JVM_MUTEX();

    rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), vmBufLength, &noVMs);
    if (rv != 0) {
        fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv);
        UNLOCK_JVM_MUTEX();
        return NULL;
    }

    if (noVMs == 0) {
        //Get the environment variables for initializing the JVM
        char *hadoopClassPath = getenv("CLASSPATH");
        if (hadoopClassPath == NULL) {
            fprintf(stderr, "Environment variable CLASSPATH not set!\n");
            UNLOCK_JVM_MUTEX();
            return NULL;
        } 
        char *hadoopClassPathVMArg = "-Djava.class.path=";
        size_t optHadoopClassPathLen = strlen(hadoopClassPath) + 
          strlen(hadoopClassPathVMArg) + 1;
        char *optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen);
        snprintf(optHadoopClassPath, optHadoopClassPathLen,
                "%s%s", hadoopClassPathVMArg, hadoopClassPath);

        int noArgs = 1;
        //determine how many arguments were passed as LIBHDFS_OPTS env var
        char *hadoopJvmArgs = getenv("LIBHDFS_OPTS");
        char jvmArgDelims[] = " ";
        if (hadoopJvmArgs != NULL)  {
                char *result = NULL;
                result = strtok( hadoopJvmArgs, jvmArgDelims );
                while ( result != NULL ) {
                        noArgs++;
        		result = strtok( NULL, jvmArgDelims);
           	}
        }
        JavaVMOption options[noArgs];
        options[0].optionString = optHadoopClassPath;
		//fill in any specified arguments
	if (hadoopJvmArgs != NULL)  {
            char *result = NULL;
            result = strtok( hadoopJvmArgs, jvmArgDelims );	
            int argNum = 1;
            for (;argNum < noArgs ; argNum++) {
                options[argNum].optionString = result; //optHadoopArg;
            }
        }

        //Create the VM
        JavaVMInitArgs vm_args;
        JavaVM *vm;
        vm_args.version = JNI_VERSION_1_2;
        vm_args.options = options;
        vm_args.nOptions = noArgs; 
        vm_args.ignoreUnrecognized = 1;

        rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args);
        if (rv != 0) {
            fprintf(stderr, "Call to JNI_CreateJavaVM failed "
                    "with error: %d\n", rv);
            UNLOCK_JVM_MUTEX();
            return NULL;
        }

        free(optHadoopClassPath);
    }
    else {
        //Attach this thread to the VM
        JavaVM* vm = vmBuf[0];
        rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0);
        if (rv != 0) {
            fprintf(stderr, "Call to AttachCurrentThread "
                    "failed with error: %d\n", rv);
            UNLOCK_JVM_MUTEX();
            return NULL;
        }
    }
    UNLOCK_JVM_MUTEX();

    return env;
}
Exemplo n.º 18
0
SEXP init_java(SEXP classpath) {
	JavaVMInitArgs initArgs;
	initArgs.version = JNI_VERSION_1_4;

	JavaVMOption options[2];
	std::string classpath_optstr = "-Djava.class.path=";
	classpath_optstr += CHAR(STRING_ELT(classpath,0));

	// these lines require explicit casts to cast away const-ness. I'm trusting
	// Java won't be modifying the options strings.  
	options[0].optionString = (char*)classpath_optstr.c_str();
	options[1].optionString = (char*)"-Djava.version=1.5";
  
    	initArgs.options=options;
    	initArgs.nOptions = 2;

	//jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs);
	// See if there's a pre-existing VM, and use it if so. Only the first VM returned
	// is used.
	
	jsize numvms;
	JavaVM *existing_vm;
	JNI_GetCreatedJavaVMs(&existing_vm, 1, &numvms);

	if(numvms > 0)
		existing_vm->AttachCurrentThread((void**)&env, NULL);
	else
		JNI_CreateJavaVM(&jvm, (void**)&env, (void*)&initArgs);

	add_class("RDirectBufferData", "edu/stanford/math/plex/RDirectBufferData");
	add_method("RDirectBufferData", "<init>", "(ILjava/nio/ByteBuffer;)V");
	
	add_class("RipsStream", "edu/stanford/math/plex/RipsStream");
	add_method("RipsStream", "<init>", "(DDILedu/stanford/math/plex/PointData;)V");
	
	add_class("Persistence","edu/stanford/math/plex/Persistence");
	add_method("Persistence", "<init>", "()V");
	add_method("Persistence","computeIntervals", "(Ledu/stanford/math/plex/SimplexStream;)[Ledu/stanford/math/plex/PersistenceInterval$Float;");

	add_class("PersistenceInterval.Float","edu/stanford/math/plex/PersistenceInterval$Float");
	add_method("PersistenceInterval.Float", "<init>", "()V");
	add_method("PersistenceInterval.Float", "2<init>", "(IDD)V");

	add_class("LazyWitnessStream", "edu/stanford/math/plex/LazyWitnessStream");
	add_method("LazyWitnessStream", "<init>", "(DIDI[ILedu/stanford/math/plex/PointData;)V");

	add_class("WitnessStream", "edu/stanford/math/plex/WitnessStream");
	
	add_method("WitnessStream", "<s>makeRandomLandmarks", "(Ledu/stanford/math/plex/PointData;I)[I");
	add_method("WitnessStream", "<s>estimateRmax", "(Ledu/stanford/math/plex/PointData;[I)D");

	add_class("Plex", "edu/stanford/math/plex/Plex");
	add_method("Plex", "<s>FilterInfinite", 
		"([Ledu/stanford/math/plex/PersistenceInterval;)Ledu/stanford/math/plex/Plex$BettiNumbers;");

	add_class("Plex.BettiNumbers", "edu/stanford/math/plex/Plex$BettiNumbers");
	add_method("Plex.BettiNumbers", "toString", "()Ljava/lang/String;");

	add_class("ExplicitStream", "edu/stanford/math/plex/ExplicitStream");
	add_method("ExplicitStream", "<init>", "()V");
	add_method("ExplicitStream", "open", "()V");
	add_method("ExplicitStream", "close", "()V");
	add_method("ExplicitStream", "add", "([ID)V");
	add_method("ExplicitStream", "remove", "([I)V");

	add_class("EuclideanArrayData", "edu/stanford/math/plex/EuclideanArrayData");
	add_method("EuclideanArrayData", "<init>", "([DI)V");	
	add_method("EuclideanArrayData", "2<init>", "(II)V");	

	p = env->NewObject(cl["Persistence"], fn["Persistence.<init>"]);

	return(R_NilValue);
}
Exemplo n.º 19
0
/**
 * getJNIEnv: A helper function to get the JNIEnv* for the given thread.
 * If no JVM exists, then one will be created. JVM command line arguments
 * are obtained from the LIBHDFS_OPTS environment variable.
 *
 * @param: None.
 * @return The JNIEnv* corresponding to the thread.
 */
JNIEnv* getJNIEnv(void)
{

    const jsize vmBufLength = 1;
    JavaVM* vmBuf[vmBufLength]; 
    JNIEnv *env;
    jint rv = 0; 
    jint noVMs = 0;

    // Only the first thread should create the JVM. The other trheads should
    // just use the JVM created by the first thread.
    LOCK_JVM_MUTEX();

    rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), vmBufLength, &noVMs);
    if (rv != 0) {
        fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv);
        UNLOCK_JVM_MUTEX();
        return NULL;
    }

    if (noVMs == 0) {
        //Get the environment variables for initializing the JVM
        char *hadoopClassPath = getenv("CLASSPATH");
        if (hadoopClassPath == NULL) {
            fprintf(stderr, "Environment variable CLASSPATH not set!\n");
            UNLOCK_JVM_MUTEX();
            return NULL;
        } 
        char *hadoopClassPathVMArg = "-Djava.class.path=";
        size_t optHadoopClassPathLen = strlen(hadoopClassPath) + 
          strlen(hadoopClassPathVMArg) + 1;
        char *optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen);
        snprintf(optHadoopClassPath, optHadoopClassPathLen,
                "%s%s", hadoopClassPathVMArg, hadoopClassPath);

        // Determine the # of LIBHDFS_OPTS args
        int noArgs = 1;
        char *hadoopJvmArgs = getenv("LIBHDFS_OPTS");
        char jvmArgDelims[] = " ";
        char *str, *token, *savePtr;
        if (hadoopJvmArgs != NULL)  {
          hadoopJvmArgs = strdup(hadoopJvmArgs);
          for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
            token = strtok_r(str, jvmArgDelims, &savePtr);
            if (NULL == token) {
              break;
            }
          }
          free(hadoopJvmArgs);
        }

        // Now that we know the # args, populate the options array
        JavaVMOption options[noArgs];
        options[0].optionString = optHadoopClassPath;
        hadoopJvmArgs = getenv("LIBHDFS_OPTS");
	if (hadoopJvmArgs != NULL)  {
          hadoopJvmArgs = strdup(hadoopJvmArgs);
          for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
            token = strtok_r(str, jvmArgDelims, &savePtr);
            if (NULL == token) {
              break;
            }
            options[noArgs].optionString = token;
          }
        }

        //Create the VM
        JavaVMInitArgs vm_args;
        JavaVM *vm;
        vm_args.version = JNI_VERSION_1_2;
        vm_args.options = options;
        vm_args.nOptions = noArgs; 
        vm_args.ignoreUnrecognized = 1;

        rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args);

        if (hadoopJvmArgs != NULL)  {
          free(hadoopJvmArgs);
        }
        free(optHadoopClassPath);

        if (rv != 0) {
            fprintf(stderr, "Call to JNI_CreateJavaVM failed "
                    "with error: %d\n", rv);
            UNLOCK_JVM_MUTEX();
            return NULL;
        }
    }
    else {
        //Attach this thread to the VM
        JavaVM* vm = vmBuf[0];
        rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0);
        if (rv != 0) {
            fprintf(stderr, "Call to AttachCurrentThread "
                    "failed with error: %d\n", rv);
            UNLOCK_JVM_MUTEX();
            return NULL;
        }
    }
    UNLOCK_JVM_MUTEX();

    return env;
}
Exemplo n.º 20
0
void JVM_Init(void)
{
	int				i;
	jint            nVMs = 0;		// number of VM's active
	JavaVMInitArgs  vm_args;

	growList_t      growOptions;
	JavaVMOption   *option;
	JavaVMOption   *options;

	char            classPath[MAX_QPATH];
	char            policyPath[MAX_OSPATH];

	Com_InitGrowList(&growOptions, 5);

	Com_Printf("------- JVM_Init() -------\n");

	jvm_javaLib = Cvar_Get("jvm_javaLib", DEFAULT_JAVA_LIB, CVAR_ARCHIVE | CVAR_LATCH);
	jvm_useJITCompiler = Cvar_Get("jvm_useJITCompiler", "1", CVAR_INIT);
	jvm_useJAR = Cvar_Get("jvm_useJAR", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_remoteDebugging = Cvar_Get("jvm_remoteDebugging", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_profiling = Cvar_Get("jvm_profiling", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_verboseJNI = Cvar_Get("jvm_verboseJNI", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_verboseClass = Cvar_Get("jvm_verboseClass", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_verboseGC = Cvar_Get("jvm_verboseGC", "0", CVAR_ARCHIVE | CVAR_LATCH);
	jvm_policyFile = Cvar_Get("jvm_policyFile", "", CVAR_ARCHIVE | CVAR_LATCH);

	option = AllocOption(&growOptions);

	if(!jvm_useJITCompiler->integer)
	{
		Com_Printf("Disabling Java JIT support\n");
		option->optionString = "-Djava.compiler=NONE";
	}
	else
	{
		option->optionString = "-Djava.compiler=YES";
	}

	// TODO support sv_pure
	if(jvm_useJAR->integer)
	{
		Com_sprintf(classPath, sizeof(classPath), "-Djava.class.path=%s",
					FS_BuildOSPath(Cvar_VariableString("fs_basepath"), Cvar_VariableString("fs_game"), "game.jar"));
	}
	else
	{
		Com_sprintf(classPath, sizeof(classPath), "-Djava.class.path=%s",
					FS_BuildOSPath(Cvar_VariableString("fs_basepath"), Cvar_VariableString("fs_game"), "classes"));
	}

	option = AllocOption(&growOptions);
	option->optionString = classPath;

	Com_Printf("Set main class path to '%s'\n", classPath);

	if(jvm_remoteDebugging->integer)
	{
		Com_Printf("Enabling remote debugging\n");

		option = AllocOption(&growOptions);
		option->optionString = "-Xdebug";

		option = AllocOption(&growOptions);
		option->optionString = "-Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=y";
	}

	if(jvm_verboseJNI->integer)
	{
		Com_Printf("Enabling verbose JNI prints\n");

		option = AllocOption(&growOptions);
		option->optionString = "-verbose:jni";
	}

	if(jvm_verboseClass->integer)
	{
		Com_Printf("Enabling displaying information about each class loaded.\n");

		option = AllocOption(&growOptions);
		option->optionString = "-verbose:class";
	}

	if(jvm_verboseGC->integer)
	{
		Com_Printf("Enabling reports on each garbage collection event.\n");

		option = AllocOption(&growOptions);
		option->optionString = "-verbose:gc";
	}

#if 1
	{
		Com_Printf("Enabling security manager\n");

		option = AllocOption(&growOptions);
		option->optionString = "-Djava.security.manager";
	}
#endif

	if(Q_stricmp(jvm_policyFile->string, "") != 0)
	{
		Com_sprintf(policyPath, sizeof(policyPath), "-Djava.security.policy=file:%s", FS_BuildOSPath(Cvar_VariableString("fs_basepath"), Cvar_VariableString("fs_game"), jvm_policyFile->string));

		option = AllocOption(&growOptions);
		option->optionString = policyPath;

		Com_Printf("Enabling '%s'\n", policyPath);
	}



	// convert growlist to array
	options = Com_Allocate(growOptions.currentElements * sizeof(JavaVMOption));
	for(i = 0; i < growOptions.currentElements; i++)
	{
		options[i] = *(JavaVMOption*) Com_GrowListElement(&growOptions, i);
	}

	vm_args.version = JNI_VERSION_1_4;
	vm_args.options = options;
	vm_args.nOptions = growOptions.currentElements;
	vm_args.ignoreUnrecognized = JNI_TRUE;

#if defined(USE_JAVA_DLOPEN)
	if(!JVM_JNI_Init())
	{
		Com_Error(ERR_FATAL, "JNI initialization failed");
	}
#endif

	Com_Printf("Searching for existing Java VM's ...");

	// look for an existing VM
#if defined(USE_JAVA_DLOPEN)
	if(QJNI_GetCreatedJavaVMs(&javaVM, 1, &nVMs) != JNI_OK)
#else
	if(JNI_GetCreatedJavaVMs(&javaVM, 1, &nVMs) != JNI_OK)
#endif
	{
		Com_Error(ERR_FATAL, "Search for existing VM's failed");
	}

	Com_Printf("found %i\n", nVMs);

#if 1
	if(nVMs > 0)
	{
		Com_Printf("Attaching to existing Java VM...");

		if((*javaVM)->AttachCurrentThread(javaVM, (void **)&javaEnv, NULL))
		{
			Com_Error(ERR_FATAL, "Couldn't attach to existing VM");
		}

		javaVMIsOurs = qfalse;
		//javaVM = jvm;

		Com_Printf("done\n");
	}
	else
#endif
	{
		int res;

		Com_Printf("Creating new Java VM...");

		// Create the Java VM
#if defined(USE_JAVA_DLOPEN)
		res = QJNI_CreateJavaVM(&javaVM, (void **)&javaEnv, &vm_args);
#else
		res = JNI_CreateJavaVM(&javaVM, (void **)&javaEnv, &vm_args);
#endif
		if(res != JNI_OK )
		{
			Com_Error(ERR_FATAL, "Can't create Java VM, JNI returned %i", res);
		}

		//javaVM = jvm;

		Com_Printf("done\n");
	}

	if(!javaVM)
	{
		Com_Error(ERR_FATAL, "JVM_Init failed");
	}

	// finally register the needed core modules
	Misc_javaRegister();
	Engine_javaRegister();
	CVar_javaRegister();
	UserCommand_javaRegister();


	// clean up allocated objects
	for(i = 0; i < growOptions.currentElements; i++)
	{
		option = Com_GrowListElement(&growOptions, i);
		Com_Dealloc(option);
	}
	Com_DestroyGrowList(&growOptions);

	Com_Dealloc(options);
}
Exemplo n.º 21
0
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");

}
Exemplo n.º 22
0
/*
 * This method will initialize the JVM. If there is already an active JVM
 * running, it will just attach to it. If there isn't an active JVM, it will
 * create and start a new one
 */
void Runtime::initializeJVM() throw( HLA::RTIinternalError )
{
	logger->debug( "Initialize the JVM" );

	///////////////////////////////////////////
	// 1. get the classpath and library path //
	///////////////////////////////////////////
	pair<string,string> paths = this->generatePaths();
	logger->debug( "Using Classpath   : %s", paths.first.c_str() );
	logger->debug( "Using Library Path: %s", paths.second.c_str() );

	/////////////////////////////////////////////
	// 2. check to see if a JVM already exists //
	/////////////////////////////////////////////
	// other jvm options - remember to increment the option array size
	// if you are going to add more
	string stackSize( "-Xss8m" );
	string mode = getMode();
	string compiler = getCompiler();
	string hlaVersion = getHlaVersion();
	string architecture = getArch();
	
	// before we can create or connect to the JVM, we need to specify its environment
	JavaVMInitArgs vmargs;
	JavaVMOption options[7];
	options[0].optionString = const_cast<char*>(paths.first.c_str());
	options[1].optionString = const_cast<char*>(paths.second.c_str());
	options[2].optionString = const_cast<char*>(mode.c_str());         // build mode
	options[3].optionString = const_cast<char*>(compiler.c_str());     // compiler version
	options[4].optionString = const_cast<char*>(hlaVersion.c_str());   // hla interface version
	options[5].optionString = const_cast<char*>(architecture.c_str()); // architecture
	options[6].optionString = const_cast<char*>(stackSize.c_str());
	vmargs.nOptions = 7;
	vmargs.version = JNI_VERSION_1_6;
	vmargs.options = options;
	vmargs.ignoreUnrecognized = JNI_TRUE;

	// Before we create the JVM, we will check to see if one already exists or
	// not. If there is an existing one, we will just attach to it rather than
	// creating a separate one.
	jint result;
	jsize jvmCount = 0;
	result = JNI_GetCreatedJavaVMs( &jvm, 1, &jvmCount );
	if( this->jvm != NULL && jvmCount > 0 && result == JNI_OK )
	{
		///////////////////////////////////////////////////////////////
		// JVM already exists, just attach to the existing reference //
		///////////////////////////////////////////////////////////////
		logger->debug( "[check] JVM already exists, attaching to it" );
		result = jvm->AttachCurrentThread( (void**)&jvmenv, &vmargs );
		// check the result
		if( result < 0 )
		{
			logger->fatal( "*** JVM already existed, but we failed to attach ***" );
			logger->fatal( "    result=%d", result );
			throw HLA::RTIinternalError( "*** JVM already existed, but we failed to attach ***" );
		}

		// we're all attached just fine, so let's get out of here
		this->attached = true;
		return;
	}

	//////////////////////////////////
	// 3. create a new JVM instance //
	//////////////////////////////////
	// JVM doesn't exist yet, create a new one to work with
	logger->debug( "[check] JVM doesn't exist, creating a new one" );
	result = JNI_CreateJavaVM( &jvm, (void**)&jvmenv, &vmargs );

	if( result < 0 )
	{
		logger->fatal( "*** Couldn't create a new JVM! *** result=%d", result );
		throw HLA::RTIinternalError( "*** Couldn't create a new JVM! ***" );
	}

	logger->info( "New JVM has been created" );
}
Exemplo n.º 23
0
/*
 * is the function that gets called by PKCS#11 to unlock a mutex and calls the Java
 * UnlockMutex function
 *
 * @param env - used to call JNI funktions to get the Java classes, objects, methods and fields
 * @param pMutex - the mutex to unlock
 * @return - should return CKR_OK if the mutex was not unlocked already
 */
CK_RV callJUnlockMutex(CK_VOID_PTR pMutex)
{
    JavaVM *jvm;
    JNIEnv *env;
    jsize actualNumberVMs;
    jint returnValue;
    jthrowable pkcs11Exception;
    jclass pkcs11ExceptionClass;
    jlong errorCode;
    CK_RV rv = CKR_OK;
    int wasAttached = 1;
    jclass jUnlockMutexClass;
    jclass jInitArgsClass;
    jmethodID methodID;
    jfieldID fieldID;
    jobject jUnlockMutex;
    jobject jMutex;


    /* Get the currently running Java VM */
    returnValue = JNI_GetCreatedJavaVMs(&jvm, (jsize) 1, &actualNumberVMs);
    if ((returnValue != 0) || (actualNumberVMs <= 0)) { return rv ; } /* there is no VM running */

    /* Determine, if current thread is already attached */
    returnValue = (*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_2);
    if (returnValue == JNI_EDETACHED) {
        /* thread detached, so attach it */
        wasAttached = 0;
        returnValue = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL);
    } else if (returnValue == JNI_EVERSION) {
        /* this version of JNI is not supported, so just try to attach */
        /* we assume it was attached to ensure that this thread is not detached
         * afterwards even though it should not
         */
        wasAttached = 1;
        returnValue = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL);
    } else {
        /* attached */
        wasAttached = 1;
    }


    jUnlockMutexClass = (*env)->FindClass(env, CLASS_UNLOCKMUTEX);
    jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);

    /* convert the CK-type mutex to a Java mutex */
    jMutex = ckVoidPtrToJObject(pMutex);

    /* get the UnlockMutex object out of the jInitArgs object */
    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
    assert(fieldID != 0);
    jUnlockMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
    assert(jUnlockMutex != 0);

    /* call the CK_UNLOCKMUTEX method of the UnLockMutex object */
    methodID = (*env)->GetMethodID(env, jUnlockMutexClass, "CK_UNLOCKMUTEX", "(Ljava/lang/Object;)V");
    assert(methodID != 0);
    (*env)->CallVoidMethod(env, jUnlockMutex, methodID, jMutex);


    /* check, if callback threw an exception */
    pkcs11Exception = (*env)->ExceptionOccurred(env);

    if (pkcs11Exception != NULL) {
        /* The was an exception thrown, now we get the error-code from it */
        pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
        methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
        assert(methodID != 0);
        errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
        rv = jLongToCKULong(errorCode);
    }

    /* if we attached this thread to the VM just for callback, we detach it now */
    if (wasAttached) {
        returnValue = (*jvm)->DetachCurrentThread(jvm);
    }

    return rv ;
}
Exemplo n.º 24
0
int OGRMDBJavaEnv::Init()
{
    if (jvm_static == NULL)
    {
        JavaVM* vmBuf[1];
        jsize nVMs;

        /* Are we already called from Java ? */
        if (JNI_GetCreatedJavaVMs(vmBuf, 1, &nVMs) == JNI_OK && nVMs == 1)
        {
            jvm = vmBuf[0];
            if (jvm->GetEnv((void **)&env, JNI_VERSION_1_2) == JNI_OK)
            {
                bCalledFromJava = TRUE;
            }
            else
            {
                jvm = NULL;
                env = NULL;
            }
        }
        else
        {
            JavaVMInitArgs args;
            JavaVMOption options[1];
            args.version = JNI_VERSION_1_2;
            const char* pszClassPath = CPLGetConfigOption("CLASSPATH", NULL);
            CPLString osClassPathOption;
            if (pszClassPath)
            {
                args.nOptions = 1;
                osClassPathOption.Printf("-Djava.class.path=%s", pszClassPath);
                options[0].optionString = (char*) osClassPathOption.c_str();
                args.options = options;
            }
            else
                args.nOptions = 0;
            args.ignoreUnrecognized = JNI_FALSE;

            int ret = JNI_CreateJavaVM(&jvm, (void **)&env, &args);
            if (ret != 0 || jvm == NULL || env == NULL)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "JNI_CreateJavaVM failed (%d)", ret);
                return FALSE;
            }

            jvm_static = jvm;
            env_static = env;
        }
    }
    else
    {
        jvm = jvm_static;
        env = env_static;
    }

    CHECK(byteArray_class, env->FindClass("[B"));
    CHECK(file_class, env->FindClass("java/io/File"));
    CHECK(file_constructor, env->GetMethodID(file_class, "<init>", "(Ljava/lang/String;)V"));
    CHECK(database_class, env->FindClass("com/healthmarketscience/jackcess/Database"));

    CHECK(database_open, env->GetStaticMethodID(database_class, "open", "(Ljava/io/File;Z)Lcom/healthmarketscience/jackcess/Database;"));
    CHECK(database_close, env->GetMethodID(database_class, "close", "()V"));
    CHECK(database_getTableNames, env->GetMethodID(database_class, "getTableNames", "()Ljava/util/Set;"));
    CHECK(database_getTable, env->GetMethodID(database_class, "getTable", "(Ljava/lang/String;)Lcom/healthmarketscience/jackcess/Table;"));

    CHECK(table_class, env->FindClass("com/healthmarketscience/jackcess/Table"));
    CHECK(table_getColumns, env->GetMethodID(table_class, "getColumns", "()Ljava/util/List;"));
    CHECK(table_iterator, env->GetMethodID(table_class, "iterator", "()Ljava/util/Iterator;"));
    CHECK(table_getRowCount, env->GetMethodID(table_class, "getRowCount", "()I"));

    CHECK(column_class, env->FindClass("com/healthmarketscience/jackcess/Column"));
    CHECK(column_getName, env->GetMethodID(column_class, "getName", "()Ljava/lang/String;"));
    CHECK(column_getType, env->GetMethodID(column_class, "getType", "()Lcom/healthmarketscience/jackcess/DataType;"));
    CHECK(column_getLength, env->GetMethodID(column_class, "getLength", "()S"));
    CHECK(column_isVariableLength, env->GetMethodID(column_class, "isVariableLength", "()Z"));

    CHECK(datatype_class, env->FindClass("com/healthmarketscience/jackcess/DataType"));
    CHECK(datatype_getValue, env->GetMethodID(datatype_class, "getValue", "()B"));

    CHECK(list_class, env->FindClass("java/util/List"));
    CHECK(list_iterator, env->GetMethodID(list_class, "iterator", "()Ljava/util/Iterator;"));

    CHECK(set_class, env->FindClass("java/util/Set"));
    CHECK(set_iterator, env->GetMethodID(set_class, "iterator", "()Ljava/util/Iterator;"));

    CHECK(map_class, env->FindClass("java/util/Map"));
    CHECK(map_get, env->GetMethodID(map_class, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"));

    CHECK(iterator_class,  env->FindClass("java/util/Iterator"));
    CHECK(iterator_hasNext, env->GetMethodID(iterator_class, "hasNext", "()Z"));
    CHECK(iterator_next, env->GetMethodID(iterator_class, "next", "()Ljava/lang/Object;"));

    CHECK(object_class,  env->FindClass("java/lang/Object"));
    CHECK(object_toString, env->GetMethodID(object_class, "toString", "()Ljava/lang/String;"));
    CHECK(object_getClass, env->GetMethodID(object_class, "getClass", "()Ljava/lang/Class;"));

    CHECK(boolean_class,  env->FindClass("java/lang/Boolean"));
    CHECK(boolean_booleanValue, env->GetMethodID(boolean_class, "booleanValue", "()Z"));

    CHECK(byte_class,  env->FindClass("java/lang/Byte"));
    CHECK(byte_byteValue, env->GetMethodID(byte_class, "byteValue", "()B"));

    CHECK(short_class,  env->FindClass("java/lang/Short"));
    CHECK(short_shortValue, env->GetMethodID(short_class, "shortValue", "()S"));

    CHECK(integer_class,  env->FindClass("java/lang/Integer"));
    CHECK(integer_intValue, env->GetMethodID(integer_class, "intValue", "()I"));

    CHECK(float_class,  env->FindClass("java/lang/Float"));
    CHECK(float_floatValue, env->GetMethodID(float_class, "floatValue", "()F"));

    CHECK(double_class,  env->FindClass("java/lang/Double"));
    CHECK(double_doubleValue, env->GetMethodID(integer_class, "doubleValue", "()D"));

    return TRUE;
}
JOI_RetCode JavaObjectInterface::initJVM()
{
  jint result;
  if (jvm_ == NULL)
  {
    jsize jvm_count = 0;
    // Is there an existing JVM already created?
    result = JNI_GetCreatedJavaVMs (&jvm_, 1, &jvm_count);
    if (result != JNI_OK)
    {
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_CHECK_JVM));
      return JOI_ERROR_CHECK_JVM;      
    }
    if (jvm_count == 0)
    {
      // No - create a new one.
      result = createJVM();
      if (result != JNI_OK)
      {
         GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_CHECK_JVM));
         return JOI_ERROR_CREATE_JVM;
      }
        
      needToDetach_ = false;
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Created a new JVM.");
    }
    char *jniHandleCapacityStr =  getenv("TRAF_JNIHANDLE_CAPACITY");
    if (jniHandleCapacityStr != NULL)
       jniHandleCapacity_ = atoi(jniHandleCapacityStr);
    if (jniHandleCapacity_ == 0)
        jniHandleCapacity_ = TRAF_DEFAULT_JNIHANDLE_CAPACITY;
  }
  if (jenv_  == NULL)
  {
  // We found a JVM, can we use it?
  result = jvm_->GetEnv((void**) &jenv_, JNI_VERSION_1_6);
  switch (result)
  {
    case JNI_OK:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attached to an existing JVM.");
      break;
    
    case JNI_EDETACHED:
      result = jvm_->AttachCurrentThread((void**) &jenv_, NULL);   
      if (result != JNI_OK)
        return JOI_ERROR_ATTACH_JVM;
      
      needToDetach_ = true;
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attached to an existing JVM from another thread.");
      break;
       
    case JNI_EVERSION:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attaching to a JVM of the wrong version.");
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_JVM_VERSION));
      return JOI_ERROR_JVM_VERSION;
      break;
      
    default:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Unknown error Attaching to an existing JVM.");
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_ATTACH_JVM));
      return JOI_ERROR_ATTACH_JVM;
      break;
  }
  }
  jclass lJavaClass;
  if (gThrowableClass == NULL)
  {
     lJavaClass = jenv_->FindClass("java/lang/Throwable");
     if (lJavaClass != NULL)
     {
        gThrowableClass  = (jclass)jenv_->NewGlobalRef(lJavaClass);
        jenv_->DeleteLocalRef(lJavaClass);
        gGetStackTraceMethodID  = jenv_->GetMethodID(gThrowableClass,
                      "getStackTrace",
                      "()[Ljava/lang/StackTraceElement;");
        gThrowableToStringMethodID = jenv_->GetMethodID(gThrowableClass,
                      "toString",
                      "()Ljava/lang/String;");
     }
  }
  if (gStackTraceClass == NULL)
  {
     lJavaClass =  (jclass)jenv_->FindClass("java/lang/StackTraceElement");
     if (lJavaClass != NULL)
     {
        gStackTraceClass = (jclass)jenv_->NewGlobalRef(lJavaClass);
        jenv_->DeleteLocalRef(lJavaClass);
        gStackFrameToStringMethodID  = jenv_->GetMethodID(gStackTraceClass,
                      "toString",
                      "()Ljava/lang/String;");
     }
  }                  
  return JOI_OK;
}
    static JNIEnv *getNewEnv() {
        
        JNIEnv *env; /* pointer to native method interface */
        JavaVM * jvmBuf[1];
        jsize nVMs;
        char *debugJ4CppEnv = NULL;
        char *classPathEnv = NULL;
        char *jvmOptionsEnv = NULL;
#if defined(_WIN32) || defined(_WIN64)
        errno_t errno_val;
        size_t requiredSize;
        errno_val =  getenv_s( &requiredSize, NULL, 0, "DEBUG_J4CPP");
        if(requiredSize > 0) {
            debugJ4CppEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, debugJ4CppEnv, requiredSize, "DEBUG_J4CPP");
        }
        errno_val =  getenv_s( &requiredSize, NULL, 0, "CLASSPATH");
        if(requiredSize > 0) {
            classPathEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, classPathEnv, requiredSize, "CLASSPATH");
        }
        errno_val =  getenv_s( &requiredSize, NULL, 0, "JVM_OPTIONS");
        if(requiredSize > 0) {
            jvmOptionsEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, jvmOptionsEnv, requiredSize, "JVM_OPTIONS");
        }
#else 
        debugJ4CppEnv = getenv("DEBUG_J4CPP");
        classPathEnv = getenv("CLASSPATH");
        jvmOptionsEnv = getenv("JVM_OPTIONS");
#endif
        debug_j4cpp = debug_j4cpp || (debugJ4CppEnv != NULL && debugJ4CppEnv[0] != 0);
        std::string str;
        str += "%CLASSPATH_PREFIX%";
        if (classPathEnv != NULL) {
            std::string classPathEnvStr(classPathEnv);
            if (debug_j4cpp) std::cout << "classPathEnv=" << classPathEnvStr << std::endl;
            str += "%PATH_SEPERATOR%";
            str += classPathEnvStr;
        }
        if (debug_j4cpp) std::cout << "str=" << str << std::endl;
#if defined(_WIN32) || defined(_WIN64)
        _putenv_s("CLASSPATH", str.c_str());
#else
        setenv("CLASSPATH", str.c_str(), 1);
#endif
        std::string optsString;
        optsString += "-Djava.class.path=";
        optsString += str;
        if (jvmOptionsEnv != NULL) {
            std::string jvmOptionsEnvStr(jvmOptionsEnv);
            if (debug_j4cpp) std::cout << "jvmOptionsEnvStr=" << jvmOptionsEnvStr << std::endl;
            optsString += " ";
            optsString += jvmOptionsEnvStr;
        }
        if (debug_j4cpp) std::cout << "optsString=" << optsString << std::endl;
        jint v = JNI_GetCreatedJavaVMs(jvmBuf, 1, &nVMs);
        if (nVMs > 0) {
            jvm = jvmBuf[0];
            jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
            return env;
        }
        JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
        JavaVMOption* options = new JavaVMOption[1];
        options[0].optionString = (char *) optsString.c_str();
        vm_args.version = JNI_VERSION_1_6;
        vm_args.nOptions = NULL != options[0].optionString ? 1 : 0;
        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)),
                ((void *) (&vm_args)));
        delete options;
#if defined(_WIN32) || defined(_WIN64)
        if(debugJ4CppEnv != NULL) {
            free(debugJ4CppEnv);
            debugJ4CppEnv = NULL;
        }
        if(classPathEnv != NULL) {
            free(classPathEnv);
            classPathEnv = NULL;
        }
        if(jvmOptionsEnv != NULL) {
            free(jvmOptionsEnv);
            jvmOptionsEnv = NULL;
        }
#endif
        registerNativeMethods(env);
//        static JNINativeMethod methods[1];
//        jclass loaderclass = env->FindClass("java/lang/ClassLoader");
//        std::cout << "loaderclass = " << loaderclass << std::endl;
//        jmethodID mid = env->GetStaticMethodID(loaderclass,"getSystemClassLoader","()Ljava/lang/ClassLoader;");
//        std::cout << "mid = " << mid << std::endl;
//        jobject loader = env->CallStaticObjectMethod(loaderclass,mid);
//        std::cout << "loader = " << loader << std::endl;
//        jclass rn_clss = env->FindClass("NativeRunnable");
//        std::cout << "rn_clss = " << rn_clss << std::endl;
//        if(NULL != rn_clss) {
//            methods[0].name = (char *) "run";
//            methods[0].signature = (char *) "()V";
//            methods[0].fnPtr = (void *) Java_NativeRunnable_run;
//            jint rn_ret = env->RegisterNatives(rn_clss,methods,1);
//            std::cout << "rn_ret = " << rn_ret << std::endl;
//        }
        return env;
    }