1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <jni.h>
18 
19 #include "libnativehelper_test.h"
20 
TEST_F(LibnativehelperTest,JNI_CreateJavaVM)21 TEST_F(LibnativehelperTest, JNI_CreateJavaVM) {
22     // Android only supports a single runtime, this is already running so no more can be created.
23     JavaVMInitArgs vm_args;
24     JavaVMOption options[] = {
25         { .optionString = "-verbose:jni", .extraInfo = nullptr }
26     };
27     vm_args.version = JNI_VERSION_1_6;
28     vm_args.nOptions = std::size(options);
29     vm_args.options = options;
30     vm_args.ignoreUnrecognized = JNI_TRUE;
31 
32     JavaVM* vm = nullptr;
33     JNIEnv* env = nullptr;
34     EXPECT_EQ(JNI_ERR, JNI_CreateJavaVM(&vm, &env, &vm_args));
35     EXPECT_EQ(nullptr, vm);
36     EXPECT_EQ(nullptr, env);
37 }
38 
TEST_F(LibnativehelperTest,JNI_GetDefaultJavaVMInitArgs)39 TEST_F(LibnativehelperTest, JNI_GetDefaultJavaVMInitArgs) {
40     // JNI_GetDefaultJavaVMInitArgs is historically not supported by ART or Dalvik (at least as
41     // far back as android-r2.2.3_r2).
42     JavaVMInitArgs vm_args;
43     vm_args.version = JNI_VERSION_1_6;
44     vm_args.nOptions = 0;
45     EXPECT_EQ(JNI_ERR, JNI_GetDefaultJavaVMInitArgs(&vm_args));
46 }
47 
TEST_F(LibnativehelperTest,JNI_GetCreatedJavaVMs)48 TEST_F(LibnativehelperTest, JNI_GetCreatedJavaVMs) {
49     JavaVM* vmBuf[3];
50     jsize nVMs;
51     ASSERT_EQ(JNI_OK, JNI_GetCreatedJavaVMs(vmBuf, std::size(vmBuf), &nVMs));
52     ASSERT_EQ(1, nVMs);
53     ASSERT_NE(nullptr, vmBuf[0]);
54 
55     // Check caller can get the JNIEnv.
56     jint versions[] = { JNI_VERSION_1_1, JNI_VERSION_1_2, JNI_VERSION_1_4, JNI_VERSION_1_6 };
57     JNIEnv* env = nullptr;
58     for (jint version : versions) {
59         EXPECT_EQ(JNI_OK, vmBuf[0]->GetEnv(reinterpret_cast<void**>(&env), version))
60             << " for JNI version " << std::hex << version;
61         EXPECT_EQ(mEnv, env);
62     }
63 }
64