1 /*
2  * Copyright (C) 2017 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 <jvmti.h>
19 
20 #include "android-base/logging.h"
21 #include "jni_binder.h"
22 #include "jvmti_helper.h"
23 #include "scoped_local_ref.h"
24 #include "test_env.h"
25 
26 namespace art {
27 
InformMainAttach(jvmtiEnv * jenv,JNIEnv * env,const char * class_name,const char * method_name)28 static void InformMainAttach(jvmtiEnv* jenv,
29                              JNIEnv* env,
30                              const char* class_name,
31                              const char* method_name) {
32   // Use JNI to load the class.
33   ScopedLocalRef<jclass> klass(env, FindClass(jenv, env, class_name, nullptr));
34   CHECK(klass.get() != nullptr) << class_name;
35 
36   jmethodID method = env->GetStaticMethodID(klass.get(), method_name, "()V");
37   CHECK(method != nullptr);
38 
39   env->CallStaticVoidMethod(klass.get(), method);
40 }
41 
42 static constexpr const char* kMainClass = "art/CtsMain";
43 static constexpr const char* kMainClassStartup = "startup";
44 
Agent_OnLoad(JavaVM * vm,char * options ATTRIBUTE_UNUSED,void * reserved ATTRIBUTE_UNUSED)45 extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm,
46                                                char* options ATTRIBUTE_UNUSED,
47                                                void* reserved ATTRIBUTE_UNUSED) {
48   if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
49     LOG(FATAL) << "Could not get shared jvmtiEnv";
50   }
51 
52   SetStandardCapabilities(jvmti_env);
53   return 0;
54 }
55 
Agent_OnAttach(JavaVM * vm,char * options ATTRIBUTE_UNUSED,void * reserved ATTRIBUTE_UNUSED)56 extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm,
57                                                  char* options ATTRIBUTE_UNUSED,
58                                                  void* reserved ATTRIBUTE_UNUSED) {
59   JNIEnv* env;
60   CHECK_EQ(0, vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6))
61       << "Could not get JNIEnv";
62 
63   if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
64     LOG(FATAL) << "Could not get shared jvmtiEnv";
65   }
66 
67   SetStandardCapabilities(jvmti_env);
68   InformMainAttach(jvmti_env, env, kMainClass, kMainClassStartup);
69   return 0;
70 }
71 
72 }  // namespace art
73