1 /*
2 * Copyright (C) 2021 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 <string_view>
21
22 namespace ddms_agent {
23
24 using DisablePolicy = jvmtiError (*)(jvmtiEnv*);
25 static constexpr std::string_view kDisablePolicyName =
26 "com.android.art.misc.disable_hidden_api_enforcement_policy";
27
28 static jvmtiEnv* jvmti_env;
29 DisablePolicy disable_ext;
30
31 template <typename T>
Dealloc(T * t)32 static void Dealloc(T* t) {
33 jvmti_env->Deallocate(reinterpret_cast<unsigned char*>(t));
34 }
35
36 template <typename T, typename... Rest>
Dealloc(T * t,Rest...rs)37 static void Dealloc(T* t, Rest... rs) {
38 Dealloc(t);
39 Dealloc(rs...);
40 }
41
DeallocParams(jvmtiParamInfo * params,jint n_params)42 static void DeallocParams(jvmtiParamInfo* params, jint n_params) {
43 for (jint i = 0; i < n_params; i++) {
44 Dealloc(params[i].name);
45 }
46 }
47
GetExtension(const std::string_view & name)48 void* GetExtension(const std::string_view& name) {
49 // Get the extensions.
50 jint n_ext = 0;
51 void* result = nullptr;
52 jvmtiExtensionFunctionInfo* infos = nullptr;
53 if (jvmti_env->GetExtensionFunctions(&n_ext, &infos) != JVMTI_ERROR_NONE) {
54 return nullptr;
55 }
56 for (jint i = 0; i < n_ext; i++) {
57 jvmtiExtensionFunctionInfo* cur_info = &infos[i];
58 if (name == std::string_view(cur_info->id)) {
59 result = reinterpret_cast<void*>(cur_info->func);
60 }
61 // Cleanup the cur_info
62 DeallocParams(cur_info->params, cur_info->param_count);
63 Dealloc(cur_info->id, cur_info->short_description, cur_info->params, cur_info->errors);
64 }
65 // Cleanup the array.
66 Dealloc(infos);
67 if (result == nullptr) {
68 return nullptr;
69 }
70 return result;
71 }
72
Agent_OnAttach(JavaVM * vm,char *,void *)73 extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char*, void*) {
74 vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0);
75 disable_ext = reinterpret_cast<DisablePolicy>(GetExtension(kDisablePolicyName));
76 if (disable_ext == nullptr) {
77 return JNI_ERR;
78 }
79 return JNI_OK;
80 }
81
82 extern "C" JNIEXPORT jint JNICALL
Java_android_jdwptunnel_sampleapp_ddms_DdmsSampleDeviceActivity_ForceNoHiddenapi(JNIEnv *,jclass)83 Java_android_jdwptunnel_sampleapp_ddms_DdmsSampleDeviceActivity_ForceNoHiddenapi(JNIEnv*, jclass) {
84 return disable_ext(jvmti_env);
85 }
86
87 } // namespace ddms_agent