Exemple #1
0
/*
* Class:     eu_vandertil_jerasure_jni_Cauchy
* Method:    cauchy_xy_coding_matrix
* Signature: (III[I[I)[I
*/
JNIEXPORT jintArray JNICALL Java_eu_vandertil_jerasure_jni_Cauchy_cauchy_1xy_1coding_1matrix
	(JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jx, jintArray jy)
{
	bool outOfMemory = false;
	jintArray result = NULL;

	jint *x = env->GetIntArrayElements(jx, NULL);
	jint *y = env->GetIntArrayElements(jy, NULL);

	if(x != NULL && y != NULL) {
		int* matrix = cauchy_xy_coding_matrix(k,m,w, (int*)x, (int*)y);

		if(matrix != NULL) {
			result = env->NewIntArray(k*m);
			if(result != NULL) {
				env->SetIntArrayRegion(result, 0, k*m, (jint*)matrix);
			} else {
				outOfMemory = true;
			}

		} else {
			outOfMemory = true;
		}

		free(matrix);
	} else {
		outOfMemory = true;
	}

	if(outOfMemory) {
		throwOutOfMemoryError(env, "");
	}

	env->ReleaseIntArrayElements(jx, x, NULL);
	env->ReleaseIntArrayElements(jy, y, NULL);

	return result;
}
JNIEXPORT jshortArray JNICALL Java_com_purplefrog_speexjni_SpeexDecoder_decode
  (JNIEnv *env, jclass cls, jint slot, jbyteArray input_frame_)
{
    if (throwIfBadSlot(env, slot))
	return;

    struct Slot * gob = slots.slots[slot];

    int frame_length = (*env)->GetArrayLength(env, input_frame_);

    int frame_size;
    speex_decoder_ctl(gob->state, SPEEX_GET_FRAME_SIZE, &frame_size);

    //

    char* input_frame = (*env)->GetByteArrayElements(env, input_frame_, 0);
    
    speex_bits_read_from(&gob->bits, input_frame, frame_length);

    (*env)->ReleaseByteArrayElements(env, input_frame_, input_frame, 0);

    //

    jshortArray rval;
    rval = (*env)->NewShortArray(env, frame_size);
    if (rval==0) {
	throwOutOfMemoryError(env, "failed to allocate speex output frame");
	return;
    }

    short* output_frame = (*env)->GetShortArrayElements(env, rval, 0);

    speex_decode_int(gob->state, &gob->bits, output_frame);

    (*env)->ReleaseShortArrayElements(env, rval, output_frame, 0);

    return rval;
}
Exemple #3
0
// Throws a runtime exception back to the Java VM appropriate for the type of
// error and frees the NEOERR that is passed in.
// TODO: throw more specific exceptions for errors like NERR_IO and NERR_NOMEM
int jNeoErr(JNIEnv *env, NEOERR *err) {
  STRING str;

  string_init(&str);
  if (nerr_match(err, NERR_PARSE)) {
    nerr_error_string(err, &str);
    throwRuntimeException(env, str.buf);
  } else if (nerr_match(err, NERR_IO)) {
    nerr_error_string(err, &str);
    throwIOException(env, str.buf);
  } else if (nerr_match(err, NERR_NOMEM)) {
    nerr_error_string(err, &str);
    throwOutOfMemoryError(env, str.buf);
  } else {
    nerr_error_traceback(err, &str);
    throwRuntimeException(env, str.buf);
  }

  nerr_ignore(&err);  // free err, otherwise it would leak
  string_clear(&str);

  return 0;
}
Exemple #4
0
/*
 * converts a jobjectArray with Java Attributes to a CK_ATTRIBUTE array. The allocated memory
 * has to be freed after use!
 *
 * @param env - used to call JNI funktions to get the array informtaion
 * @param jArray - the Java Attribute array (template) to convert
 * @param ckpArray - the reference, where the pointer to the new CK_ATTRIBUTE array will be
 *                   stored
 * @param ckpLength - the reference, where the array length will be stored
 */
void jAttributeArrayToCKAttributeArray(JNIEnv *env, jobjectArray jArray, CK_ATTRIBUTE_PTR *ckpArray, CK_ULONG_PTR ckpLength)
{
    CK_ULONG i;
    jlong jLength;
    jobject jAttribute;

    TRACE0("\nDEBUG: jAttributeArrayToCKAttributeArray");
    if (jArray == NULL) {
        *ckpArray = NULL_PTR;
        *ckpLength = 0L;
        return;
    }
    jLength = (*env)->GetArrayLength(env, jArray);
    *ckpLength = jLongToCKULong(jLength);
    *ckpArray = (CK_ATTRIBUTE_PTR) malloc(*ckpLength * sizeof(CK_ATTRIBUTE));
    if (*ckpArray == NULL) {
        throwOutOfMemoryError(env, 0);
        return;
    }
    TRACE1(", converting %d attributes", jLength);
    for (i=0; i<(*ckpLength); i++) {
        TRACE1(", getting %d. attribute", i);
        jAttribute = (*env)->GetObjectArrayElement(env, jArray, i);
        if ((*env)->ExceptionCheck(env)) {
            freeCKAttributeArray(*ckpArray, i);
            return;
        }
        TRACE1(", jAttribute = %d", jAttribute);
        TRACE1(", converting %d. attribute", i);
        (*ckpArray)[i] = jAttributeToCKAttribute(env, jAttribute);
        if ((*env)->ExceptionCheck(env)) {
            freeCKAttributeArray(*ckpArray, i);
            return;
        }
    }
    TRACE0("FINISHED\n");
}
EncodedJSValue JSC_HOST_CALL IntlDateTimeFormatPrototypeGetterFormat(ExecState* state)
{
    // 12.3.3 Intl.DateTimeFormat.prototype.format (ECMA-402 2.0)
    // 1. Let dtf be this DateTimeFormat object.
    IntlDateTimeFormat* dtf = jsDynamicCast<IntlDateTimeFormat*>(state->thisValue());

    // FIXME: Workaround to provide compatibility with ECMA-402 1.0 call/apply patterns.
    // https://bugs.webkit.org/show_bug.cgi?id=153679
    if (!dtf)
        dtf = jsDynamicCast<IntlDateTimeFormat*>(state->thisValue().get(state, state->vm().propertyNames->intlSubstituteValuePrivateName));

    // 2. ReturnIfAbrupt(dtf).
    if (!dtf)
        return JSValue::encode(throwTypeError(state, ASCIILiteral("Intl.DateTimeFormat.prototype.format called on value that's not an object initialized as a DateTimeFormat")));

    JSBoundFunction* boundFormat = dtf->boundFormat();
    // 3. If the [[boundFormat]] internal slot of this DateTimeFormat object is undefined,
    if (!boundFormat) {
        VM& vm = state->vm();
        JSGlobalObject* globalObject = dtf->globalObject();
        // a. Let F be a new built-in function object as defined in 12.3.4.
        // b. The value of F’s length property is 1. (Note: F’s length property was 0 in ECMA-402 1.0)
        JSFunction* targetObject = JSFunction::create(vm, globalObject, 1, ASCIILiteral("format"), IntlDateTimeFormatFuncFormatDateTime, NoIntrinsic);
        JSArray* boundArgs = JSArray::tryCreateUninitialized(vm, globalObject->arrayStructureForIndexingTypeDuringAllocation(ArrayWithUndecided), 0);
        if (!boundArgs)
            return JSValue::encode(throwOutOfMemoryError(state));

        // c. Let bf be BoundFunctionCreate(F, «this value»).
        boundFormat = JSBoundFunction::create(vm, state, globalObject, targetObject, dtf, boundArgs, 1, ASCIILiteral("format"));
        if (vm.exception())
            return JSValue::encode(JSValue());
        // d. Set dtf.[[boundFormat]] to bf.
        dtf->setBoundFormat(vm, boundFormat);
    }
    // 4. Return dtf.[[boundFormat]].
    return JSValue::encode(boundFormat);
}
Exemple #6
0
/*
 * converts a jstring to a CK_CHAR array. The allocated memory has to be freed after use!
 *
 * @param env - used to call JNI funktions to get the array informtaion
 * @param jArray - the Java array to convert
 * @param ckpArray - the reference, where the pointer to the new CK_CHAR array will be stored
 * @param ckpLength - the reference, where the array length will be stored
 */
void jStringToCKUTF8CharArray(JNIEnv *env, const jstring jArray, CK_UTF8CHAR_PTR *ckpArray, CK_ULONG_PTR ckpLength)
{
    const char* pCharArray;
    jboolean isCopy;

    if(jArray == NULL) {
        *ckpArray = NULL_PTR;
        *ckpLength = 0L;
        return;
    }

    pCharArray = (*env)->GetStringUTFChars(env, jArray, &isCopy);
    if (pCharArray == NULL) { return; }

    *ckpLength = strlen(pCharArray);
    *ckpArray = (CK_UTF8CHAR_PTR) malloc((*ckpLength + 1) * sizeof(CK_UTF8CHAR));
    if (*ckpArray == NULL) {
        (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
        throwOutOfMemoryError(env, 0);
        return;
    }
    strcpy((char*)*ckpArray, pCharArray);
    (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
}
Exemple #7
0
/*
 * Class:     sun_security_pkcs11_wrapper_PKCS11
 * Method:    C_SignFinal
 * Signature: (J)[B
 * Parametermapping:                    *PKCS11*
 * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
 * @return  jbyteArray jSignature       CK_BYTE_PTR pSignature
 *                                      CK_ULONG_PTR pulSignatureLen
 */
JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignFinal
    (JNIEnv *env, jobject obj, jlong jSessionHandle, jint jExpectedLength)
{
    CK_SESSION_HANDLE ckSessionHandle;
    jbyteArray jSignature = NULL;
    CK_RV rv;
    CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
    CK_BYTE_PTR bufP = BUF;
    CK_ULONG ckSignatureLength = MAX_STACK_BUFFER_LEN;

    CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
    if (ckpFunctions == NULL) { return NULL; }

    ckSessionHandle = jLongToCKULong(jSessionHandle);

    if ((jExpectedLength > 0) && ((CK_ULONG)jExpectedLength < ckSignatureLength)) {
        ckSignatureLength = jExpectedLength;
    }

    rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
    if (rv == CKR_BUFFER_TOO_SMALL) {
        bufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
        if (bufP == NULL) {
            throwOutOfMemoryError(env, 0);
            return NULL;
        }
        rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
    }
    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
        jSignature = ckByteArrayToJByteArray(env, bufP, ckSignatureLength);
    }

    if (bufP != BUF) { free(bufP); }

    return jSignature;
}
Exemple #8
0
JNIEXPORT jintArray JNICALL Java_sun_security_smartcardio_PCSC_SCardGetStatusChange
    (JNIEnv *env, jclass thisClass, jlong jContext, jlong jTimeout,
    jintArray jCurrentState, jobjectArray jReaderNames)
{
    SCARDCONTEXT context = (SCARDCONTEXT)jContext;
    LONG rv;
    int readers = (*env)->GetArrayLength(env, jReaderNames);
    SCARD_READERSTATE *readerState;
    int i;
    jintArray jEventState = NULL;
    int *currentState = NULL;
    const char *readerName;

    readerState = calloc(readers, sizeof(SCARD_READERSTATE));
    if (readerState == NULL && readers > 0) {
        throwOutOfMemoryError(env, NULL);
        return NULL;
    }

    currentState = (*env)->GetIntArrayElements(env, jCurrentState, NULL);
    if (currentState == NULL) {
        free(readerState);
        return NULL;
    }

    for (i = 0; i < readers; i++) {
        readerState[i].szReader = NULL;
    }

    for (i = 0; i < readers; i++) {
        jobject jReaderName = (*env)->GetObjectArrayElement(env, jReaderNames, i);
        if ((*env)->ExceptionCheck(env)) {
            goto cleanup;
        }
        readerName = (*env)->GetStringUTFChars(env, jReaderName, NULL);
        if (readerName == NULL) {
            goto cleanup;
        }
        readerState[i].szReader = strdup(readerName);
        (*env)->ReleaseStringUTFChars(env, jReaderName, readerName);
        if (readerState[i].szReader == NULL) {
            throwOutOfMemoryError(env, NULL);
            goto cleanup;
        }
        readerState[i].pvUserData = NULL;
        readerState[i].dwCurrentState = currentState[i];
        readerState[i].dwEventState = SCARD_STATE_UNAWARE;
        readerState[i].cbAtr = 0;
        (*env)->DeleteLocalRef(env, jReaderName);
    }

    if (readers > 0) {
        rv = CALL_SCardGetStatusChange(context, (DWORD)jTimeout, readerState, readers);
        if (handleRV(env, rv)) {
            goto cleanup;
        }
    }

    jEventState = (*env)->NewIntArray(env, readers);
    if (jEventState == NULL) {
        goto cleanup;
    }
    for (i = 0; i < readers; i++) {
        jint eventStateTmp;
        dprintf3("-reader status %s: 0x%X, 0x%X\n", readerState[i].szReader,
            readerState[i].dwCurrentState, readerState[i].dwEventState);
        eventStateTmp = (jint)readerState[i].dwEventState;
        (*env)->SetIntArrayRegion(env, jEventState, i, 1, &eventStateTmp);
        if ((*env)->ExceptionCheck(env)) {
            jEventState = NULL;
            goto cleanup;
        }
    }
cleanup:
    (*env)->ReleaseIntArrayElements(env, jCurrentState, currentState, JNI_ABORT);
    for (i = 0; i < readers; i++) {
        free((char *)readerState[i].szReader);
    }
    free(readerState);
    return jEventState;
}
static jobject android_os_Exec_createSubProcess(JNIEnv *env, jobject clazz,
    jstring cmd, jobjectArray args, jobjectArray envVars,
    jintArray processIdArray)
{
    const jchar* str = cmd ? env->GetStringCritical(cmd, 0) : 0;
    String8 cmd_8;
    if (str) {
        cmd_8.set(str, env->GetStringLength(cmd));
        env->ReleaseStringCritical(cmd, str);
    }

    jsize size = args ? env->GetArrayLength(args) : 0;
    char **argv = NULL;
    String8 tmp_8;
    if (size > 0) {
        argv = (char **)malloc((size+1)*sizeof(char *));
        if (!argv) {
            throwOutOfMemoryError(env, "Couldn't allocate argv array");
            return NULL;
        }
        for (int i = 0; i < size; ++i) {
            jstring arg = reinterpret_cast<jstring>(env->GetObjectArrayElement(args, i));
            str = env->GetStringCritical(arg, 0);
            if (!str) {
                throwOutOfMemoryError(env, "Couldn't get argument from array");
                return NULL;
            }
            tmp_8.set(str, env->GetStringLength(arg));
            env->ReleaseStringCritical(arg, str);
            argv[i] = strdup(tmp_8.string());
        }
        argv[size] = NULL;
    }

    size = envVars ? env->GetArrayLength(envVars) : 0;
    char **envp = NULL;
    if (size > 0) {
        envp = (char **)malloc((size+1)*sizeof(char *));
        if (!envp) {
            throwOutOfMemoryError(env, "Couldn't allocate envp array");
            return NULL;
        }
        for (int i = 0; i < size; ++i) {
            jstring var = reinterpret_cast<jstring>(env->GetObjectArrayElement(envVars, i));
            str = env->GetStringCritical(var, 0);
            if (!str) {
                throwOutOfMemoryError(env, "Couldn't get env var from array");
                return NULL;
            }
            tmp_8.set(str, env->GetStringLength(var));
            env->ReleaseStringCritical(var, str);
            envp[i] = strdup(tmp_8.string());
        }
        envp[size] = NULL;
    }

    int procId;
    int ptm = create_subprocess(cmd_8.string(), argv, envp, &procId);

    if (argv) {
        for (char **tmp = argv; *tmp; ++tmp) {
            free(*tmp);
        }
        free(argv);
    }
    if (envp) {
        for (char **tmp = envp; *tmp; ++tmp) {
            free(*tmp);
        }
        free(envp);
    }

    if (processIdArray) {
        int procIdLen = env->GetArrayLength(processIdArray);
        if (procIdLen > 0) {
            jboolean isCopy;

            int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
            if (pProcId) {
                *pProcId = procId;
                env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
            }
        }
    }

    jobject result = env->NewObject(class_fileDescriptor, method_fileDescriptor_init);

    if (!result) {
        LOGE("Couldn't create a FileDescriptor.");
    }
    else {
        env->SetIntField(result, field_fileDescriptor_descriptor, ptm);
    }

    return result;
}
Exemple #10
0
/*
 * Class:     sun_security_pkcs11_wrapper_PKCS11
 * Method:    C_GetAttributeValue
 * Signature: (JJ[Lsun/security/pkcs11/wrapper/CK_ATTRIBUTE;)[Lsun/security/pkcs11/wrapper/CK_ATTRIBUTE;
 * Parametermapping:                    *PKCS11*
 * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
 * @param   jlong jObjectHandle         CK_OBJECT_HANDLE hObject
 * @param   jobjectArray jTemplate      CK_ATTRIBUTE_PTR pTemplate
 *                                      CK_ULONG ulCount
 */
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1GetAttributeValue
    (JNIEnv *env, jobject obj, jlong jSessionHandle, jlong jObjectHandle, jobjectArray jTemplate)
{
    CK_SESSION_HANDLE ckSessionHandle;
    CK_OBJECT_HANDLE ckObjectHandle;
    CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
    CK_ULONG ckAttributesLength;
    CK_ULONG ckBufferLength;
    CK_ULONG i;
    jobject jAttribute;
    CK_RV rv;

    CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
    if (ckpFunctions == NULL) { return; }

    TRACE0("DEBUG: C_GetAttributeValue");
    TRACE1(", hSession=%u", jSessionHandle);
    TRACE1(", hObject=%u", jObjectHandle);
    TRACE1(", pTemplate=%p", jTemplate);
    TRACE0(" ... ");

    ckSessionHandle = jLongToCKULong(jSessionHandle);
    ckObjectHandle = jLongToCKULong(jObjectHandle);
    TRACE1("jAttributeArrayToCKAttributeArray now with jTemplate = %d", jTemplate);
    jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
    if ((*env)->ExceptionCheck(env)) { return; }

    TRACE2("DEBUG: jAttributeArrayToCKAttributeArray finished with ckpAttribute = %d, Length = %d\n", ckpAttributes, ckAttributesLength);

    /* first set all pValue to NULL, to get the needed buffer length */
    for(i = 0; i < ckAttributesLength; i++) {
        if (ckpAttributes[i].pValue != NULL_PTR) {
            free(ckpAttributes[i].pValue);
            ckpAttributes[i].pValue = NULL_PTR;
        }
    }

    rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
        free(ckpAttributes);
        return ;
    }

    /* now, the ulValueLength field of each attribute should hold the exact buffer length needed
     * allocate the needed buffers accordingly
     */
    for (i = 0; i < ckAttributesLength; i++) {
        ckBufferLength = sizeof(CK_BYTE) * ckpAttributes[i].ulValueLen;
        ckpAttributes[i].pValue = (void *) malloc(ckBufferLength);
        if (ckpAttributes[i].pValue == NULL) {
            freeCKAttributeArray(ckpAttributes, i);
            throwOutOfMemoryError(env, 0);
            return;
        }
        ckpAttributes[i].ulValueLen = ckBufferLength;
    }

    /* now get the attributes with all values */
    rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);

    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
        /* copy back the values to the Java attributes */
        for (i = 0; i < ckAttributesLength; i++) {
            jAttribute = ckAttributePtrToJAttribute(env, &(ckpAttributes[i]));
            if (jAttribute == NULL) {
                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
                return;
            }
            (*env)->SetObjectArrayElement(env, jTemplate, i, jAttribute);
            if ((*env)->ExceptionCheck(env)) {
                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
                return;
            }
        }
    }
    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
    TRACE0("FINISHED\n");
}
/**
 * Everything that is allocated here will be freed at deleteContext when the class is unloaded.
 */
JNIEXPORT jobject JNICALL Java_org_apache_activemq_artemis_jlibaio_LibaioContext_newContext(JNIEnv* env, jobject thisObject, jint queueSize) {
    io_context_t libaioContext;
    int i = 0;

    #ifdef DEBUG
        fprintf (stdout, "Initializing context\n");
    #endif

    int res = io_queue_init(queueSize, &libaioContext);
    if (res) {
        // Error, so need to release whatever was done before
        free(libaioContext);

        throwRuntimeExceptionErrorNo(env, "Cannot initialize queue:", res);
        return NULL;
    }

    struct iocb ** iocb = (struct iocb **)malloc((sizeof(struct iocb *) * (size_t)queueSize));
    if (iocb == NULL) {
       throwOutOfMemoryError(env);
       return NULL;
    }

    for (i = 0; i < queueSize; i++) {
       iocb[i] = (struct iocb *)malloc(sizeof(struct iocb));
       if (iocb[i] == NULL) {
           // it's unlikely this would happen at this point
           // for that reason I'm not cleaning up individual IOCBs here
           // we could increase support here with a cleanup of any previously allocated iocb
           // But I'm afraid of adding not needed complexity here
           throwOutOfMemoryError(env);
           return NULL;
       }
    }

    struct io_control * theControl = (struct io_control *) malloc(sizeof(struct io_control));
    if (theControl == NULL) {
        throwOutOfMemoryError(env);
        return NULL;
    }

    res = pthread_mutex_init(&(theControl->iocbLock), 0);
    if (res) {
        free(theControl);
        free(libaioContext);
        throwRuntimeExceptionErrorNo(env, "Can't initialize mutext:", res);
        return NULL;
    }

    res = pthread_mutex_init(&(theControl->pollLock), 0);
    if (res) {
        free(theControl);
        free(libaioContext);
        throwRuntimeExceptionErrorNo(env, "Can't initialize mutext:", res);
        return NULL;
    }

    struct io_event * events = (struct io_event *)malloc(sizeof(struct io_event) * (size_t)queueSize);

    theControl->ioContext = libaioContext;
    theControl->events = events;
    theControl->iocb = iocb;
    theControl->queueSize = queueSize;
    theControl->iocbPut = 0;
    theControl->iocbGet = 0;
    theControl->used = 0;
    theControl->thisObject = (*env)->NewGlobalRef(env, thisObject);

    return (*env)->NewDirectByteBuffer(env, theControl, sizeof(struct io_control));
}
Exemple #12
0
JSValue RegExpObject::matchGlobal(ExecState* exec, JSGlobalObject* globalObject, JSString* string)
{
    RegExp* regExp = this->regExp();

    ASSERT(regExp->global());

    VM* vm = &globalObject->vm();

    setLastIndex(exec, 0);
    if (exec->hadException())
        return jsUndefined();

    String s = string->value(exec);
    RegExpConstructor* regExpConstructor = globalObject->regExpConstructor();
    MatchResult result = regExpConstructor->performMatch(*vm, regExp, string, s, 0);

    // return array of matches
    MarkedArgumentBuffer list;
    // We defend ourselves from crazy.
    const size_t maximumReasonableMatchSize = 1000000000;

    if (regExp->unicode()) {
        unsigned stringLength = s.length();
        while (result) {
            if (list.size() > maximumReasonableMatchSize) {
                throwOutOfMemoryError(exec);
                return jsUndefined();
            }

            size_t end = result.end;
            size_t length = end - result.start;
            list.append(jsSubstring(exec, s, result.start, length));
            if (!length)
                end = advanceStringUnicode(s, stringLength, end);
            result = regExpConstructor->performMatch(*vm, regExp, string, s, end);
        }
    } else {
        while (result) {
            if (list.size() > maximumReasonableMatchSize) {
                throwOutOfMemoryError(exec);
                return jsUndefined();
            }

            size_t end = result.end;
            size_t length = end - result.start;
            list.append(jsSubstring(exec, s, result.start, length));
            if (!length)
                ++end;
            result = regExpConstructor->performMatch(*vm, regExp, string, s, end);
        }
    }

    if (list.isEmpty()) {
        // if there are no matches at all, it's important to return
        // Null instead of an empty array, because this matches
        // other browsers and because Null is a false value.
        return jsNull();
    }

    return constructArray(exec, static_cast<ArrayAllocationProfile*>(0), list);
}
Exemple #13
0
JNIEXPORT jintArray JNICALL Java_de_tesis_dynaware_javafx_graphics_importers_fbx_JFbxLib_getMeshFaces(JNIEnv *env, jobject obj, jint attributeIndex) {

	// Check FBX file has been opened.
	if (!isOpen()) { throwFileClosedException(env); }

	// Check attribute index bounds for safety.
	if (!checkAttributeBounds(attributeIndex)) { throwArrayOutOfBoundsException(env); }

	// Check attribute type for safety.
	if (!isValidType(attributeIndex, FbxNodeAttribute::EType::eMesh)) { return NULL; }

	FbxMesh* mesh = (FbxMesh*)currentNode->GetNodeAttributeByIndex(attributeIndex);

	bool byPolygonVertex = false;
	bool index           = false;
	bool indexToDirect   = false;
	bool direct          = false;

	FbxLayerElementUV *firstLayer = mesh->GetElementUV(0);
	if (firstLayer!=NULL) {
		byPolygonVertex = firstLayer->GetMappingMode()==FbxLayerElement::EMappingMode::eByPolygonVertex;
		index           = firstLayer->GetReferenceMode()==FbxLayerElement::EReferenceMode::eIndex;
		indexToDirect   = firstLayer->GetReferenceMode()==FbxLayerElement::EReferenceMode::eIndexToDirect;
		direct          = firstLayer->GetReferenceMode()==FbxLayerElement::EReferenceMode::eDirect;
	}

	const int polygonCount = mesh->GetPolygonCount();

	jintArray faces = env->NewIntArray(6*polygonCount);

	// Check memory could be allocated.
	if (faces == NULL) { throwOutOfMemoryError(env); }

	for (int i=0; i<polygonCount; i++) {
		jint face[6];

		// Assume we are working with a triangle mesh.
		face[0] = mesh->GetPolygonVertex(i,0);
		face[2] = mesh->GetPolygonVertex(i,1);
		face[4] = mesh->GetPolygonVertex(i,2);

		if (byPolygonVertex && (index || indexToDirect)) {
			face[1] = mesh->GetTextureUVIndex(i, 0);
			face[3] = mesh->GetTextureUVIndex(i, 1);
			face[5] = mesh->GetTextureUVIndex(i, 2);
		}
		else if (direct) {
			face[1] = 3*i;
			face[3] = 3*i+1;
			face[5] = 3*i+2;
		}
		else {
			face[1] = 0;
			face[3] = 0;
			face[5] = 0;
		}

		env->SetIntArrayRegion(faces, 6*i, 6, face);
	}

	return faces;
}
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    } else {

        sprintf (dumbPath, "%s/artemisJLHandler_XXXXXX", P_tmpdir);
        dumbWriteHandler = mkstemp (dumbPath);

        #ifdef DEBUG
           fprintf (stdout, "Creating temp file %s for dumb writes\n", dumbPath);
           fflush(stdout);
        #endif

        if (dumbWriteHandler < 0) {
           fprintf (stderr, "couldn't create stop file handler %s\n", dumbPath);
           return JNI_ERR;
        }

        //
        // Accordingly to previous experiences we must hold Global Refs on Classes
        // And
        //
        // Accordingly to IBM recommendations here:
        // We don't need to hold a global reference on methods:
        // http://www.ibm.com/developerworks/java/library/j-jni/index.html#notc
        // Which actually caused core dumps

        jclass localRuntimeExceptionClass = (*env)->FindClass(env, "java/lang/RuntimeException");
        if (localRuntimeExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        runtimeExceptionClass = (jclass) (*env)->NewGlobalRef(env, localRuntimeExceptionClass);
        if (runtimeExceptionClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env);
            return JNI_ERR;
        }

        jclass localIoExceptionClass = (*env)->FindClass(env, "java/io/IOException");
        if (localIoExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        ioExceptionClass = (jclass) (*env)->NewGlobalRef(env, localIoExceptionClass);
        if (ioExceptionClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env);
            return JNI_ERR;
        }

        submitClass = (*env)->FindClass(env, "org/apache/activemq/artemis/jlibaio/SubmitInfo");
        if (submitClass == NULL) {
           return JNI_ERR;
        }

        submitClass = (jclass)(*env)->NewGlobalRef(env, (jobject)submitClass);

        errorMethod = (*env)->GetMethodID(env, submitClass, "onError", "(ILjava/lang/String;)V");
        if (errorMethod == NULL) {
           return JNI_ERR;
        }

        doneMethod = (*env)->GetMethodID(env, submitClass, "done", "()V");
        if (doneMethod == NULL) {
           return JNI_ERR;
        }

        libaioContextClass = (*env)->FindClass(env, "org/apache/activemq/artemis/jlibaio/LibaioContext");
        if (libaioContextClass == NULL) {
           return JNI_ERR;
        }
        libaioContextClass = (jclass)(*env)->NewGlobalRef(env, (jobject)libaioContextClass);

        libaioContextDone = (*env)->GetMethodID(env, libaioContextClass, "done", "(Lorg/apache/activemq/artemis/jlibaio/SubmitInfo;)V");
        if (libaioContextDone == NULL) {
           return JNI_ERR;
        }

        return JNI_VERSION_1_6;
    }
}
Exemple #15
0
/*
 * converts a Java object into a pointer to CK-type or a CK-structure with the length in Bytes.
 * The memory of *ckpObjectPtr to be freed after use! This function is only used by
 * jAttributeToCKAttribute by now.
 *
 * @param env - used to call JNI funktions to get the Java classes and objects
 * @param jObject - the Java object to convert
 * @param ckpObjectPtr - the reference of the new pointer to the new CK-value or CK-structure
 * @param ckpLength - the reference of the length in bytes of the new CK-value or CK-structure
 */
void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *ckpLength)
{
    jclass jLongClass, jBooleanClass, jByteArrayClass, jCharArrayClass;
    jclass jByteClass, jDateClass, jCharacterClass, jIntegerClass;
    jclass jBooleanArrayClass, jIntArrayClass, jLongArrayClass;
    jclass jStringClass;
    jclass jObjectClass, jClassClass;
    CK_VOID_PTR ckpVoid = *ckpObjectPtr;
    jmethodID jMethod;
    jobject jClassObject;
    jstring jClassNameString;
    char *classNameString, *exceptionMsgPrefix, *exceptionMsg;

    TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtrPtr");
    if (jObject == NULL) {
        *ckpObjectPtr = NULL;
        *ckpLength = 0;
        return;
    }

    jLongClass = (*env)->FindClass(env, "java/lang/Long");
    if (jLongClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
        *ckpObjectPtr = jLongObjectToCKULongPtr(env, jObject);
        *ckpLength = sizeof(CK_ULONG);
        TRACE1("<converted long value %X>", *((CK_ULONG *) *ckpObjectPtr));
        return;
    }

    jBooleanClass = (*env)->FindClass(env, "java/lang/Boolean");
    if (jBooleanClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
        *ckpObjectPtr = jBooleanObjectToCKBBoolPtr(env, jObject);
        *ckpLength = sizeof(CK_BBOOL);
        TRACE0(" <converted boolean value ");
        TRACE0((*((CK_BBOOL *) *ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
        return;
    }

    jByteArrayClass = (*env)->FindClass(env, "[B");
    if (jByteArrayClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
        jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*)ckpObjectPtr, ckpLength);
        return;
    }

    jCharArrayClass = (*env)->FindClass(env, "[C");
    if (jCharArrayClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
        jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
        return;
    }

    jByteClass = (*env)->FindClass(env, "java/lang/Byte");
    if (jByteClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
        *ckpObjectPtr = jByteObjectToCKBytePtr(env, jObject);
        *ckpLength = sizeof(CK_BYTE);
        TRACE1("<converted byte value %X>", *((CK_BYTE *) *ckpObjectPtr));
        return;
    }

    jDateClass = (*env)->FindClass(env, CLASS_DATE);
    if (jDateClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
        *ckpObjectPtr = jDateObjectPtrToCKDatePtr(env, jObject);
        *ckpLength = sizeof(CK_DATE);
        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year, (*((CK_DATE *) *ckpObjectPtr)).month, (*((CK_DATE *) *ckpObjectPtr)).day);
        return;
    }

    jCharacterClass = (*env)->FindClass(env, "java/lang/Character");
    if (jCharacterClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
        *ckpObjectPtr = jCharObjectToCKCharPtr(env, jObject);
        *ckpLength = sizeof(CK_UTF8CHAR);
        TRACE1("<converted char value %c>", *((CK_CHAR *) *ckpObjectPtr));
        return;
    }

    jIntegerClass = (*env)->FindClass(env, "java/lang/Integer");
    if (jIntegerClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
        *ckpObjectPtr = jIntegerObjectToCKULongPtr(env, jObject);
        *ckpLength = sizeof(CK_ULONG);
        TRACE1("<converted integer value %X>", *((CK_ULONG *) *ckpObjectPtr));
        return;
    }

    jBooleanArrayClass = (*env)->FindClass(env, "[Z");
    if (jBooleanArrayClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
        jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**)ckpObjectPtr, ckpLength);
        return;
    }

    jIntArrayClass = (*env)->FindClass(env, "[I");
    if (jIntArrayClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
        return;
    }

    jLongArrayClass = (*env)->FindClass(env, "[J");
    if (jLongArrayClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
        return;
    }

    jStringClass = (*env)->FindClass(env, "java/lang/String");
    if (jStringClass == NULL) { return; }
    if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
        jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
        return;
    }

    /* type of jObject unknown, throw PKCS11RuntimeException */
    jObjectClass = (*env)->FindClass(env, "java/lang/Object");
    if (jObjectClass == NULL) { return; }
    jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
    if (jMethod == NULL) { return; }
    jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
    assert(jClassObject != 0);
    jClassClass = (*env)->FindClass(env, "java/lang/Class");
    if (jClassClass == NULL) { return; }
    jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
    if (jMethod == NULL) { return; }
    jClassNameString = (jstring)
        (*env)->CallObjectMethod(env, jClassObject, jMethod);
    assert(jClassNameString != 0);
    classNameString = (char*)
        (*env)->GetStringUTFChars(env, jClassNameString, NULL);
    if (classNameString == NULL) { return; }
    exceptionMsgPrefix = "Java object of this class cannot be converted to native PKCS#11 type: ";
    exceptionMsg = (char *)
        malloc((strlen(exceptionMsgPrefix) + strlen(classNameString) + 1));
    if (exceptionMsg == NULL) {
        (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
        throwOutOfMemoryError(env, 0);
        return;
    }
    strcpy(exceptionMsg, exceptionMsgPrefix);
    strcat(exceptionMsg, classNameString);
    (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
    throwPKCS11RuntimeException(env, exceptionMsg);
    free(exceptionMsg);
    *ckpObjectPtr = NULL;
    *ckpLength = 0;

    TRACE0("FINISHED\n");
}
Exemple #16
0
EncodedJSValue JSC_HOST_CALL arrayProtoFuncToString(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    bool isRealArray = isJSArray(&exec->globalData(), thisValue);
    if (!isRealArray && !thisValue.inherits(&JSArray::info))
        return throwVMTypeError(exec);
    JSArray* thisObj = asArray(thisValue);
    
    HashSet<JSObject*>& arrayVisitedElements = exec->globalData().arrayVisitedElements;
    if (arrayVisitedElements.size() >= MaxSmallThreadReentryDepth) {
        if (arrayVisitedElements.size() >= exec->globalData().maxReentryDepth)
            return throwVMError(exec, createStackOverflowError(exec));
    }

    bool alreadyVisited = !arrayVisitedElements.add(thisObj).second;
    if (alreadyVisited)
        return JSValue::encode(jsEmptyString(exec)); // return an empty string, avoiding infinite recursion.

//FYWEBKITMOD begin: setting up StringJoiner (while integrating r148721 due to fix of bug 114779). But not using 'ConstructFromLiteral' optimization which we dont have in our webkit.
    unsigned length = thisObj->get(exec, exec->propertyNames().length).toUInt32(exec);
    if (exec->hadException())
        return JSValue::encode(jsUndefined());

	//WebCore::String separator(",", WebCore::String::ConstructFromLiteral);
	//JSStringJoiner stringJoiner(separator, length);
	JSStringJoiner stringJoiner(",", length);
//FYWEBKITMOD end
    unsigned totalSize = length ? length - 1 : 0;
    Vector<RefPtr<UString::Rep>, 256> strBuffer(length);
    for (unsigned k = 0; k < length; k++) {
        JSValue element;
        if (isRealArray && thisObj->canGetIndex(k))
            element = thisObj->getIndex(k);
        else {
            element = thisObj->get(exec, k);
//FYWEBKITMOD begin: added while integrating r148721 due to fix of bug 114779
			if (exec->hadException()) 
				return JSValue::encode(jsUndefined());
//FYWEBKITMOD end
			}
        
//FYWEBKITMOD begin: removed (USE_FIX 1) old implementation which joined the strings manually and added usage of JSStringJoiner (while integrating r148721 due to fix of bug 114779)
#define USE_FIX 1 //keep this defined!!!
#ifdef USE_FIX
		if (element.isUndefinedOrNull()) 
			stringJoiner.append(WebCore::String()); //FYWEBKITMOD: 
		else
			stringJoiner.append(element.toString(exec).rep()); //FYWEBKITMOD: using toString() instead of new toWTFString(). Only difference is an optimization used in the toWTFString() case.

		if (exec->hadException())
			return JSValue::encode(jsUndefined());
		}

	arrayVisitedElements.remove(thisObj);

	return JSValue::encode(stringJoiner.build(exec));

#else
        if (element.isUndefinedOrNull())
            continue;
        
        UString str = element.toString(exec);
        strBuffer[k] = str.rep();
        totalSize += str.size();
        
        if (!strBuffer.data()) {
            throwOutOfMemoryError(exec);
        }
        
        if (exec->hadException())
            break;
    }
Exemple #17
0
/*
 * Class:     sun_security_pkcs11_wrapper_PKCS11
 * Method:    C_Sign
 * Signature: (J[B)[B
 * Parametermapping:                    *PKCS11*
 * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
 * @param   jbyteArray jData            CK_BYTE_PTR pData
 *                                      CK_ULONG ulDataLen
 * @return  jbyteArray jSignature       CK_BYTE_PTR pSignature
 *                                      CK_ULONG_PTR pulSignatureLen
 */
JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Sign
    (JNIEnv *env, jobject obj, jlong jSessionHandle, jbyteArray jData)
{
    CK_SESSION_HANDLE ckSessionHandle;
    CK_BYTE_PTR ckpData = NULL_PTR;
    CK_BYTE_PTR ckpSignature;
    CK_ULONG ckDataLength;
    CK_ULONG ckSignatureLength = 0;
    jbyteArray jSignature = NULL;
    CK_RV rv;

    CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
    if (ckpFunctions == NULL) { return NULL; }

    ckSessionHandle = jLongToCKULong(jSessionHandle);
    jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
    if ((*env)->ExceptionCheck(env)) { return NULL; }

    /* START standard code */

    /* first determine the length of the signature */
    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, NULL_PTR, &ckSignatureLength);
    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
        free(ckpData);
        return NULL;
    }

    ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
    if (ckpSignature == NULL) {
        free(ckpData);
        throwOutOfMemoryError(env, 0);
        return NULL;
    }

    /* now get the signature */
    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
 /* END standard code */


    /* START workaround code for operation abort bug in pkcs#11 of Datakey and iButton */
/*
    ckpSignature = (CK_BYTE_PTR) malloc(256 * sizeof(CK_BYTE));
    if (ckpSignature == NULL) {
        free(ckpData);
        throwOutOfMemoryError(env, 0);
        return NULL;
    }
    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);

    if (rv == CKR_BUFFER_TOO_SMALL) {
        free(ckpSignature);
        ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
        if (ckpSignature == NULL) {
            free(ckpData);
            throwOutOfMemoryError(env, 0);
            return NULL;
        }
        rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
    }
 */
    /* END workaround code */
    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
        jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
    }
    free(ckpData);
    free(ckpSignature);

    return jSignature ;
}
JSValue IntlNumberFormat::formatToParts(ExecState& exec, double value)
{
    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    // FormatNumberToParts (ECMA-402)
    // https://tc39.github.io/ecma402/#sec-formatnumbertoparts
    // https://tc39.github.io/ecma402/#sec-partitionnumberpattern

    if (!m_initializedNumberFormat)
        return throwTypeError(&exec, scope, "Intl.NumberFormat.prototype.formatToParts called on value that's not an object initialized as a NumberFormat"_s);

    UErrorCode status = U_ZERO_ERROR;
    auto fieldItr = std::unique_ptr<UFieldPositionIterator, UFieldPositionIteratorDeleter>(ufieldpositer_open(&status));
    if (U_FAILURE(status))
        return throwTypeError(&exec, scope, "failed to open field position iterator"_s);

    status = U_ZERO_ERROR;
    Vector<UChar, 32> result(32);
    auto resultLength = unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), result.size(), fieldItr.get(), &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        status = U_ZERO_ERROR;
        result.grow(resultLength);
        unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), resultLength, fieldItr.get(), &status);
    }
    if (U_FAILURE(status))
        return throwTypeError(&exec, scope, "failed to format a number."_s);

    int32_t literalFieldType = -1;
    auto literalField = IntlNumberFormatField(literalFieldType, resultLength);
    Vector<IntlNumberFormatField> fields(resultLength, literalField);
    int32_t beginIndex = 0;
    int32_t endIndex = 0;
    auto fieldType = ufieldpositer_next(fieldItr.get(), &beginIndex, &endIndex);
    while (fieldType >= 0) {
        auto size = endIndex - beginIndex;
        for (auto i = beginIndex; i < endIndex; ++i) {
            // Only override previous value if new value is more specific.
            if (fields[i].size >= size)
                fields[i] = IntlNumberFormatField(fieldType, size);
        }
        fieldType = ufieldpositer_next(fieldItr.get(), &beginIndex, &endIndex);
    }

    JSGlobalObject* globalObject = exec.jsCallee()->globalObject(vm);
    JSArray* parts = JSArray::tryCreate(vm, globalObject->arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 0);
    if (!parts)
        return throwOutOfMemoryError(&exec, scope);
    unsigned index = 0;

    auto resultString = String(result.data(), resultLength);
    auto typePropertyName = Identifier::fromString(&vm, "type");
    auto literalString = jsString(&exec, "literal"_s);

    int32_t currentIndex = 0;
    while (currentIndex < resultLength) {
        auto startIndex = currentIndex;
        auto fieldType = fields[currentIndex].type;
        while (currentIndex < resultLength && fields[currentIndex].type == fieldType)
            ++currentIndex;
        auto partType = fieldType == literalFieldType ? literalString : jsString(&exec, partTypeString(UNumberFormatFields(fieldType), value));
        auto partValue = jsSubstring(&vm, resultString, startIndex, currentIndex - startIndex);
        JSObject* part = constructEmptyObject(&exec);
        part->putDirect(vm, typePropertyName, partType);
        part->putDirect(vm, vm.propertyNames->value, partValue);
        parts->putDirectIndex(&exec, index++, part);
        RETURN_IF_EXCEPTION(scope, { });
    }

    return parts;
}
JNIEXPORT jint JNICALL Java_jackpal_androidterm_TermExec_createSubprocessInternal(JNIEnv *env, jclass clazz,
    jstring cmd, jobjectArray args, jobjectArray envVars, jint masterFd)
{
    const jchar* str = cmd ? env->GetStringCritical(cmd, 0) : 0;
    String8 cmd_8;
    if (str) {
        cmd_8.set(str, env->GetStringLength(cmd));
        env->ReleaseStringCritical(cmd, str);
    }

    jsize size = args ? env->GetArrayLength(args) : 0;
    char **argv = NULL;
    String8 tmp_8;
    if (size > 0) {
        argv = (char **)malloc((size+1)*sizeof(char *));
        if (!argv) {
            throwOutOfMemoryError(env, "Couldn't allocate argv array");
            return 0;
        }
        for (int i = 0; i < size; ++i) {
            jstring arg = reinterpret_cast<jstring>(env->GetObjectArrayElement(args, i));
            str = env->GetStringCritical(arg, 0);
            if (!str) {
                throwOutOfMemoryError(env, "Couldn't get argument from array");
                return 0;
            }
            tmp_8.set(str, env->GetStringLength(arg));
            env->ReleaseStringCritical(arg, str);
            argv[i] = strdup(tmp_8.string());
        }
        argv[size] = NULL;
    }

    size = envVars ? env->GetArrayLength(envVars) : 0;
    char **envp = NULL;
    if (size > 0) {
        envp = (char **)malloc((size+1)*sizeof(char *));
        if (!envp) {
            throwOutOfMemoryError(env, "Couldn't allocate envp array");
            return 0;
        }
        for (int i = 0; i < size; ++i) {
            jstring var = reinterpret_cast<jstring>(env->GetObjectArrayElement(envVars, i));
            str = env->GetStringCritical(var, 0);
            if (!str) {
                throwOutOfMemoryError(env, "Couldn't get env var from array");
                return 0;
            }
            tmp_8.set(str, env->GetStringLength(var));
            env->ReleaseStringCritical(var, str);
            envp[i] = strdup(tmp_8.string());
        }
        envp[size] = NULL;
    }

    int ptm = create_subprocess(env, cmd_8.string(), argv, envp, masterFd);

    if (argv) {
        for (char **tmp = argv; *tmp; ++tmp) {
            free(*tmp);
        }
        free(argv);
    }
    if (envp) {
        for (char **tmp = envp; *tmp; ++tmp) {
            free(*tmp);
        }
        free(envp);
    }

    return ptm;
}
Exemple #20
0
/*
 * converts the InitArgs object to a CK_C_INITIALIZE_ARGS structure and sets the functions
 * that will call the right Java mutex functions
 *
 * @param env - used to call JNI funktions to get the Java classes, objects, methods and fields
 * @param pInitArgs - the InitArgs object with the Java mutex functions to call
 * @return - the pointer to the CK_C_INITIALIZE_ARGS structure with the functions that will call
 *           the corresponding Java functions
 */
CK_C_INITIALIZE_ARGS_PTR makeCKInitArgsAdapter(JNIEnv *env, jobject jInitArgs)
{
    CK_C_INITIALIZE_ARGS_PTR ckpInitArgs;
    jclass jInitArgsClass;
    jfieldID fieldID;
    jlong jFlags;
    jobject jReserved;
    CK_ULONG ckReservedLength;
#ifndef NO_CALLBACKS
    jobject jMutexHandler;
#endif /* NO_CALLBACKS */

    if(jInitArgs == NULL) {
        return NULL_PTR;
    }

    /* convert the Java InitArgs object to a pointer to a CK_C_INITIALIZE_ARGS structure */
    ckpInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
    if (ckpInitArgs == NULL) {
        throwOutOfMemoryError(env, 0);
        return NULL_PTR;
    }

    /* Set the mutex functions that will call the Java mutex functions, but
     * only set it, if the field is not null.
     */
    jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
    if (jInitArgsClass == NULL) {
        free(ckpInitArgs);
        return NULL;
    }

#ifdef NO_CALLBACKS
    ckpInitArgs->CreateMutex = NULL_PTR;
    ckpInitArgs->DestroyMutex = NULL_PTR;
    ckpInitArgs->LockMutex = NULL_PTR;
    ckpInitArgs->UnlockMutex = NULL_PTR;
#else
    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "CreateMutex", "Lsun/security/pkcs11/wrapper/CK_CREATEMUTEX;");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
    ckpInitArgs->CreateMutex = (jMutexHandler != NULL) ? &callJCreateMutex : NULL_PTR;

    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "DestroyMutex", "Lsun/security/pkcs11/wrapper/CK_DESTROYMUTEX;");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
    ckpInitArgs->DestroyMutex = (jMutexHandler != NULL) ? &callJDestroyMutex : NULL_PTR;

    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "LockMutex", "Lsun/security/pkcs11/wrapper/CK_LOCKMUTEX;");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
    ckpInitArgs->LockMutex = (jMutexHandler != NULL) ? &callJLockMutex : NULL_PTR;

    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
    ckpInitArgs->UnlockMutex = (jMutexHandler != NULL) ? &callJUnlockMutex : NULL_PTR;

    if ((ckpInitArgs->CreateMutex != NULL_PTR)
            || (ckpInitArgs->DestroyMutex != NULL_PTR)
            || (ckpInitArgs->LockMutex != NULL_PTR)
            || (ckpInitArgs->UnlockMutex != NULL_PTR)) {
        /* we only need to keep a global copy, if we need callbacks */
        /* set the global object jInitArgs so that the right Java mutex functions will be called */
        jInitArgsObject = (*env)->NewGlobalRef(env, jInitArgs);
        ckpGlobalInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
        if (ckpGlobalInitArgs == NULL) {
            free(ckpInitArgs);
            throwOutOfMemoryError(env, 0);
            return NULL_PTR;
        }

        memcpy(ckpGlobalInitArgs, ckpInitArgs, sizeof(CK_C_INITIALIZE_ARGS));
    }
#endif /* NO_CALLBACKS */

    /* convert and set the flags field */
    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "flags", "J");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jFlags = (*env)->GetLongField(env, jInitArgs, fieldID);
    ckpInitArgs->flags = jLongToCKULong(jFlags);

    /* pReserved should be NULL_PTR in this version */
    fieldID = (*env)->GetFieldID(env, jInitArgsClass, "pReserved", "Ljava/lang/Object;");
    if (fieldID == NULL) {
        free(ckpInitArgs);
        return NULL;
    }
    jReserved = (*env)->GetObjectField(env, jInitArgs, fieldID);

    /* we try to convert the reserved parameter also */
    jObjectToPrimitiveCKObjectPtrPtr(env, jReserved, &(ckpInitArgs->pReserved), &ckReservedLength);

    return ckpInitArgs ;
}
Exemple #21
0
static jobject DEF_JNI(createSubprocess,
                       jstring cmd, jstring arg0, jstring arg1,
                       jobjectArray envVars, jintArray processIdArray)
{
    char const* cmd_str = cmd ? env->GetStringUTFChars(cmd, NULL) : NULL;
    char const* arg0_str = arg0 ? env->GetStringUTFChars(arg0, NULL) : NULL;
    char const* arg1_str = arg1 ? env->GetStringUTFChars(arg1, NULL) : NULL;
    LOGI("cmd_str = '%s'", cmd_str);
    LOGI("arg0_str = '%s'", arg0_str);
    LOGI("arg1_str = '%s'", arg1_str);

    int num_env_vars = envVars ? env->GetArrayLength(envVars) : 0;
    char **envp = NULL;
    char const* tmp = NULL;

    if (num_env_vars > 0)
    {
        envp = (char **)malloc((num_env_vars + 1) * sizeof(char*));

        if (!envp)
        {
            throwOutOfMemoryError(env, "Couldn't allocate envp array");
            return NULL;
        }

        for (int i = 0; i < num_env_vars; ++i)
        {
            jobject obj = env->GetObjectArrayElement(envVars, i);
            jstring env_var = reinterpret_cast<jstring>(obj);
            tmp = env->GetStringUTFChars(env_var, 0);

            if (tmp == NULL)
            {
                throwOutOfMemoryError(env, "Couldn't get env var from array");
                return NULL;
            }

            envp[i] = strdup(tmp);

            if (envp[i] == NULL)
            {
                throwOutOfMemoryError(env, "Couldn't strdup() env var");
                return NULL;
            }

            env->ReleaseStringUTFChars(env_var, tmp);
        }

        envp[num_env_vars] = NULL;
    }

    int procId;
    int ptm = create_subprocess(cmd_str, arg0_str, arg1_str, envp, &procId);

    env->ReleaseStringUTFChars(cmd, cmd_str);
    if(arg0 != NULL) env->ReleaseStringUTFChars(arg0, arg0_str);
    if(arg1 != NULL) env->ReleaseStringUTFChars(arg1, arg1_str);

    for (int i = 0; i < num_env_vars; ++i)
        free(envp[i]);

    free(envp);

    if (processIdArray) {
        int procIdLen = env->GetArrayLength(processIdArray);
        if (procIdLen > 0) {
            jboolean isCopy;
    
            int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
            if (pProcId) {
                *pProcId = procId;
                env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
            }
        }
    }
    
    jobject result = env->NewObject(class_fileDescriptor, method_fileDescriptor_init);
    
    if (!result) {
        LOGE("Couldn't create a FileDescriptor.");
    }
    else {
        env->SetIntField(result, field_fileDescriptor_descriptor, ptm);
    }
    
    return result;
}
Exemple #22
0
JSValue collectMatches(VM& vm, ExecState* exec, JSString* string, const String& s, RegExpConstructor* constructor, RegExp* regExp, const FixEndFunc& fixEnd)
{
    auto scope = DECLARE_THROW_SCOPE(vm);

    MatchResult result = constructor->performMatch(vm, regExp, string, s, 0);
    if (!result)
        return jsNull();
    
    static unsigned maxSizeForDirectPath = 100000;
    
    JSArray* array = constructEmptyArray(exec, nullptr);
    if (UNLIKELY(vm.exception()))
        return jsUndefined();

    auto iterate = [&] () {
        size_t end = result.end;
        size_t length = end - result.start;
        array->push(exec, JSRopeString::createSubstringOfResolved(vm, string, result.start, length));
        if (!length)
            end = fixEnd(end);
        result = constructor->performMatch(vm, regExp, string, s, end);
    };
    
    do {
        if (array->length() >= maxSizeForDirectPath) {
            // First do a throw-away match to see how many matches we'll get.
            unsigned matchCount = 0;
            MatchResult savedResult = result;
            do {
                if (array->length() + matchCount >= MAX_STORAGE_VECTOR_LENGTH) {
                    throwOutOfMemoryError(exec, scope);
                    return jsUndefined();
                }
                
                size_t end = result.end;
                matchCount++;
                if (result.empty())
                    end = fixEnd(end);
                
                // Using RegExpConstructor::performMatch() instead of calling RegExp::match()
                // directly is a surprising but profitable choice: it means that when we do OOM, we
                // will leave the cached result in the state it ought to have had just before the
                // OOM! On the other hand, if this loop concludes that the result is small enough,
                // then the iterate() loop below will overwrite the cached result anyway.
                result = constructor->performMatch(vm, regExp, string, s, end);
            } while (result);
            
            // OK, we have a sensible number of matches. Now we can create them for reals.
            result = savedResult;
            do
                iterate();
            while (result);
            
            return array;
        }
        
        iterate();
    } while (result);
    
    return array;
}
Exemple #23
0
// Overview: this methods converts a JSString from holding a string in rope form
// down to a simple UString representation.  It does so by building up the string
// backwards, since we want to avoid recursion, we expect that the tree structure
// representing the rope is likely imbalanced with more nodes down the left side
// (since appending to the string is likely more common) - and as such resolving
// in this fashion should minimize work queue size.  (If we built the queue forwards
// we would likely have to place all of the constituent UString::Reps into the
// Vector before performing any concatenation, but by working backwards we likely
// only fill the queue with the number of substrings at any given level in a
// rope-of-ropes.)
void JSString::resolveRope(ExecState* exec) const
{
    ASSERT(isRope());

    // Allocate the buffer to hold the final string, position initially points to the end.
    UChar* buffer;
    if (PassRefPtr<UStringImpl> newImpl = UStringImpl::tryCreateUninitialized(m_stringLength, buffer))
        m_value = newImpl;
    else {
        for (unsigned i = 0; i < m_ropeLength; ++i) {
            m_fibers[i].deref();
            m_fibers[i] = static_cast<void*>(0);
        }
        m_ropeLength = 0;
        ASSERT(!isRope());
        ASSERT(m_value == UString());
        throwOutOfMemoryError(exec);
        return;
    }
    UChar* position = buffer + m_stringLength;

    // Start with the current Rope.
    Vector<Rope::Fiber, 32> workQueue;
    Rope::Fiber currentFiber;
    for (unsigned i = 0; i < (m_ropeLength - 1); ++i)
        workQueue.append(m_fibers[i]);
    currentFiber = m_fibers[m_ropeLength - 1];
    while (true) {
        if (currentFiber.isRope()) {
            Rope* rope = currentFiber.rope();
            // Copy the contents of the current rope into the workQueue, with the last item in 'currentFiber'
            // (we will be working backwards over the rope).
            unsigned ropeLengthMinusOne = rope->ropeLength() - 1;
            for (unsigned i = 0; i < ropeLengthMinusOne; ++i)
                workQueue.append(rope->fibers(i));
            currentFiber = rope->fibers(ropeLengthMinusOne);
        } else {
            UString::Rep* string = currentFiber.string();
            unsigned length = string->size();
            position -= length;
            UStringImpl::copyChars(position, string->data(), length);

            // Was this the last item in the work queue?
            if (workQueue.isEmpty()) {
                // Create a string from the UChar buffer, clear the rope RefPtr.
                ASSERT(buffer == position);
                for (unsigned i = 0; i < m_ropeLength; ++i) {
                    m_fibers[i].deref();
                    m_fibers[i] = static_cast<void*>(0);
                }
                m_ropeLength = 0;

                ASSERT(!isRope());
                return;
            }

            // No! - set the next item up to process.
            currentFiber = workQueue.last();
            workQueue.removeLast();
        }
    }
}
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    } else {
        // cache classes that are used within other jni methods for performance reasons
        jclass localClosedChannelExceptionClass = (*env)->FindClass(env, "java/nio/channels/ClosedChannelException");
        if (localClosedChannelExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        closedChannelExceptionClass = (jclass) (*env)->NewGlobalRef(env, localClosedChannelExceptionClass);
        if (closedChannelExceptionClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env, "Error allocating memory");
            return JNI_ERR;
        }
        closedChannelExceptionMethodId = (*env)->GetMethodID(env, closedChannelExceptionClass, "<init>", "()V");
        if (closedChannelExceptionMethodId == NULL) {
            throwRuntimeException(env, "Unable to obtain constructor of ClosedChannelException");
            return JNI_ERR;
        }
        jclass localRuntimeExceptionClass = (*env)->FindClass(env, "java/lang/RuntimeException");
        if (localRuntimeExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        runtimeExceptionClass = (jclass) (*env)->NewGlobalRef(env, localRuntimeExceptionClass);
        if (runtimeExceptionClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env, "Error allocating memory");
            return JNI_ERR;
        }

        jclass localIoExceptionClass = (*env)->FindClass(env, "java/io/IOException");
        if (localIoExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        ioExceptionClass = (jclass) (*env)->NewGlobalRef(env, localIoExceptionClass);
        if (ioExceptionClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env, "Error allocating memory");
            return JNI_ERR;
        }

        jclass localInetSocketAddressClass = (*env)->FindClass(env, "java/net/InetSocketAddress");
        if (localIoExceptionClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        inetSocketAddressClass = (jclass) (*env)->NewGlobalRef(env, localInetSocketAddressClass);
        if (inetSocketAddressClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env, "Error allocating memory");
            return JNI_ERR;
        }

        jclass localDatagramSocketAddressClass = (*env)->FindClass(env, "io/netty/channel/epoll/EpollDatagramChannel$DatagramSocketAddress");
        if (localDatagramSocketAddressClass == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        datagramSocketAddressClass = (jclass) (*env)->NewGlobalRef(env, localDatagramSocketAddressClass);
        if (datagramSocketAddressClass == NULL) {
            // out-of-memory!
            throwOutOfMemoryError(env, "Error allocating memory");
            return JNI_ERR;
        }

        void *mem = malloc(1);
        if (mem == NULL) {
            throwOutOfMemoryError(env, "Error allocating native buffer");
            return JNI_ERR;
        }
        jobject directBuffer = (*env)->NewDirectByteBuffer(env, mem, 1);
        if (directBuffer == NULL) {
            throwOutOfMemoryError(env, "Error allocating native buffer");
            return JNI_ERR;
        }

        jclass cls = (*env)->GetObjectClass(env, directBuffer);

        // Get the method id for Buffer.position() and Buffer.limit(). These are used as fallback if
        // it is not possible to obtain the position and limit using the fields directly.
        posId = (*env)->GetMethodID(env, cls, "position", "()I");
        if (posId == NULL) {
            // position method was not found.. something is wrong so bail out
            throwRuntimeException(env, "Unable to find method ByteBuffer.position()");
            return JNI_ERR;
        }

        limitId = (*env)->GetMethodID(env, cls, "limit", "()I");
        if (limitId == NULL) {
            // limit method was not found.. something is wrong so bail out
            throwRuntimeException(env, "Unable to find method ByteBuffer.limit()");
            return JNI_ERR;
        }
        updatePosId = (*env)->GetMethodID(env, cls, "position", "(I)Ljava/nio/Buffer;");
        if (updatePosId == NULL) {
            // position method was not found.. something is wrong so bail out
            throwRuntimeException(env, "Unable to find method ByteBuffer.position(int)");
            return JNI_ERR;
        }
        // Try to get the ids of the position and limit fields. We later then check if we was able
        // to find them and if so use them get the position and limit of the buffer. This is
        // much faster then call back into java via (*env)->CallIntMethod(...).
        posFieldId = (*env)->GetFieldID(env, cls, "position", "I");
        if (posFieldId == NULL) {
            // this is ok as we can still use the method so just clear the exception
            (*env)->ExceptionClear(env);
        }
        limitFieldId = (*env)->GetFieldID(env, cls, "limit", "I");
        if (limitFieldId == NULL) {
            // this is ok as we can still use the method so just clear the exception
            (*env)->ExceptionClear(env);
        }
        jclass fileRegionCls = (*env)->FindClass(env, "io/netty/channel/DefaultFileRegion");
        if (fileRegionCls == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        fileChannelFieldId = (*env)->GetFieldID(env, fileRegionCls, "file", "Ljava/nio/channels/FileChannel;");
        if (fileChannelFieldId == NULL) {
            throwRuntimeException(env, "Unable to obtain FileChannel field for DefaultFileRegion");
            return JNI_ERR;
        }
        transferedFieldId = (*env)->GetFieldID(env, fileRegionCls, "transfered", "J");
        if (transferedFieldId == NULL) {
            throwRuntimeException(env, "Unable to obtain transfered field for DefaultFileRegion");
            return JNI_ERR;
        }

        jclass fileChannelCls = (*env)->FindClass(env, "sun/nio/ch/FileChannelImpl");
        if (fileChannelCls == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        fileDescriptorFieldId = (*env)->GetFieldID(env, fileChannelCls, "fd", "Ljava/io/FileDescriptor;");
        if (fileDescriptorFieldId == NULL) {
            throwRuntimeException(env, "Unable to obtain fd field for FileChannelImpl");
            return JNI_ERR;
        }

        jclass fileDescriptorCls = (*env)->FindClass(env, "java/io/FileDescriptor");
        if (fileDescriptorCls == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        fdFieldId = (*env)->GetFieldID(env, fileDescriptorCls, "fd", "I");
        if (fdFieldId == NULL) {
            throwRuntimeException(env, "Unable to obtain fd field for FileDescriptor");
            return JNI_ERR;
        }

        inetSocketAddrMethodId = (*env)->GetMethodID(env, inetSocketAddressClass, "<init>", "(Ljava/lang/String;I)V");
        if (inetSocketAddrMethodId == NULL) {
            throwRuntimeException(env, "Unable to obtain constructor of InetSocketAddress");
            return JNI_ERR;
        }
        socketType = socket_type();

        datagramSocketAddrMethodId = (*env)->GetMethodID(env, datagramSocketAddressClass, "<init>", "(Ljava/lang/String;II)V");
        if (datagramSocketAddrMethodId == NULL) {
            throwRuntimeException(env, "Unable to obtain constructor of DatagramSocketAddress");
            return JNI_ERR;
        }

        jclass addressEntryClass = (*env)->FindClass(env, "io/netty/channel/epoll/EpollChannelOutboundBuffer$AddressEntry");
        if (addressEntryClass == NULL) {
             // pending exception...
            return JNI_ERR;
        }
        readerIndexFieldId = (*env)->GetFieldID(env, addressEntryClass, "readerIndex", "I");
        if (readerIndexFieldId == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        writerIndexFieldId = (*env)->GetFieldID(env, addressEntryClass, "writerIndex", "I");
        if (writerIndexFieldId == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        memoryAddressFieldId = (*env)->GetFieldID(env, addressEntryClass, "memoryAddress", "J");
        if (memoryAddressFieldId == NULL) {
            // pending exception...
            return JNI_ERR;
        }
        return JNI_VERSION_1_6;
    }
}
Exemple #25
0
/*
 * Class:     sun_security_pkcs11_wrapper_PKCS11
 * Method:    C_GenerateKeyPair
 * Signature: (JLsun/security/pkcs11/wrapper/CK_MECHANISM;[Lsun/security/pkcs11/wrapper/CK_ATTRIBUTE;[Lsun/security/pkcs11/wrapper/CK_ATTRIBUTE;)[J
 * Parametermapping:                          *PKCS11*
 * @param   jlong jSessionHandle              CK_SESSION_HANDLE hSession
 * @param   jobject jMechanism                CK_MECHANISM_PTR pMechanism
 * @param   jobjectArray jPublicKeyTemplate   CK_ATTRIBUTE_PTR pPublicKeyTemplate
 *                                            CK_ULONG ulPublicKeyAttributeCount
 * @param   jobjectArray jPrivateKeyTemplate  CK_ATTRIBUTE_PTR pPrivateKeyTemplate
 *                                            CK_ULONG ulPrivateKeyAttributeCount
 * @return  jlongArray jKeyHandles            CK_OBJECT_HANDLE_PTR phPublicKey
 *                                            CK_OBJECT_HANDLE_PTR phPublicKey
 */
JNIEXPORT jlongArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1GenerateKeyPair
    (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism,
     jobjectArray jPublicKeyTemplate, jobjectArray jPrivateKeyTemplate)
{
    CK_SESSION_HANDLE ckSessionHandle;
    CK_MECHANISM ckMechanism;
    CK_ATTRIBUTE_PTR ckpPublicKeyAttributes = NULL_PTR;
    CK_ATTRIBUTE_PTR ckpPrivateKeyAttributes = NULL_PTR;
    CK_ULONG ckPublicKeyAttributesLength;
    CK_ULONG ckPrivateKeyAttributesLength;
    CK_OBJECT_HANDLE_PTR ckpPublicKeyHandle;  /* pointer to Public Key */
    CK_OBJECT_HANDLE_PTR ckpPrivateKeyHandle; /* pointer to Private Key */
    CK_OBJECT_HANDLE_PTR ckpKeyHandles;     /* pointer to array with Public and Private Key */
    jlongArray jKeyHandles = NULL;
    CK_RV rv;

    CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
    if (ckpFunctions == NULL) { return NULL; }

    ckSessionHandle = jLongToCKULong(jSessionHandle);
    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
    if ((*env)->ExceptionCheck(env)) { return NULL; }

    ckpKeyHandles = (CK_OBJECT_HANDLE_PTR) malloc(2 * sizeof(CK_OBJECT_HANDLE));
    if (ckpKeyHandles == NULL) {
        if (ckMechanism.pParameter != NULL_PTR) {
            free(ckMechanism.pParameter);
        }
        throwOutOfMemoryError(env, 0);
        return NULL;
    }
    ckpPublicKeyHandle = ckpKeyHandles;   /* first element of array is Public Key */
    ckpPrivateKeyHandle = (ckpKeyHandles + 1);  /* second element of array is Private Key */

    jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
    if ((*env)->ExceptionCheck(env)) {
        if (ckMechanism.pParameter != NULL_PTR) {
            free(ckMechanism.pParameter);
        }
        free(ckpKeyHandles);
        return NULL;
    }

    jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
    if ((*env)->ExceptionCheck(env)) {
        if (ckMechanism.pParameter != NULL_PTR) {
            free(ckMechanism.pParameter);
        }
        free(ckpKeyHandles);
        freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
        return NULL;
    }

    rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, &ckMechanism,
                     ckpPublicKeyAttributes, ckPublicKeyAttributesLength,
                     ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength,
                     ckpPublicKeyHandle, ckpPrivateKeyHandle);

    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
        jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
    }

    if(ckMechanism.pParameter != NULL_PTR) {
        free(ckMechanism.pParameter);
    }
    free(ckpKeyHandles);
    freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
    freeCKAttributeArray(ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength);

    return jKeyHandles ;
}