1 /*
2 * Copyright (C) 2018 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 #include <nativehelper/scoped_local_ref.h>
19 #include <pthread.h>
20
21 #include <android-base/logging.h>
22
23 namespace art {
24
25 static JavaVM* vm = nullptr;
26
Runner(void * arg)27 static void* Runner(void* arg) {
28 CHECK(vm != nullptr);
29
30 jobject thread_group = reinterpret_cast<jobject>(arg);
31 JNIEnv* env = nullptr;
32 JavaVMAttachArgs args = { JNI_VERSION_1_6, __FUNCTION__, thread_group };
33 int attach_result = vm->AttachCurrentThread(&env, &args);
34 CHECK_EQ(attach_result, 0);
35
36 {
37 ScopedLocalRef<jclass> klass(env, env->FindClass("Main"));
38 CHECK(klass != nullptr);
39
40 jmethodID id = env->GetStaticMethodID(klass.get(), "runFromNative", "()V");
41 CHECK(id != nullptr);
42
43 env->CallStaticVoidMethod(klass.get(), id);
44 }
45
46 int detach_result = vm->DetachCurrentThread();
47 CHECK_EQ(detach_result, 0);
48 return nullptr;
49 }
50
Java_Main_testNativeThread(JNIEnv * env,jclass,jobject thread_group)51 extern "C" JNIEXPORT void JNICALL Java_Main_testNativeThread(
52 JNIEnv* env, jclass, jobject thread_group) {
53 CHECK_EQ(env->GetJavaVM(&vm), 0);
54 jobject global_thread_group = env->NewGlobalRef(thread_group);
55
56 pthread_t pthread;
57 int pthread_create_result = pthread_create(&pthread, nullptr, Runner, global_thread_group);
58 CHECK_EQ(pthread_create_result, 0);
59 int pthread_join_result = pthread_join(pthread, nullptr);
60 CHECK_EQ(pthread_join_result, 0);
61
62 env->DeleteGlobalRef(global_thread_group);
63 }
64
65 } // namespace art
66