1 /*
2  * Copyright (C) 2023 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 #define LOG_TAG "derive_sdk"
18 
19 #include <sstream>
20 #include "android-base/logging.h"
21 #include "derive_sdk.h"
22 #include "jni.h"
23 
24 namespace android {
25 namespace derivesdk {
26 
27 constexpr const char* DERIVE_SDK_CLASS_NAME = "com/android/os/ext/testing/DeriveSdk";
28 
com_android_os_ext_testing_DeriveSdk_dump(JNIEnv * env)29 jstring com_android_os_ext_testing_DeriveSdk_dump(JNIEnv* env) {
30   std::stringstream stream;
31   PrintDump("/apex", stream);
32 
33   return env->NewStringUTF(stream.str().c_str());
34 }
35 
36 const JNINativeMethod methods[] = {
37     {"native_dump", "()Ljava/lang/String;",
38      reinterpret_cast<void*>(com_android_os_ext_testing_DeriveSdk_dump)},
39 };
40 
register_com_android_os_ext_testing_DeriveSdk(JNIEnv * env)41 void register_com_android_os_ext_testing_DeriveSdk(JNIEnv* env) {
42   auto gDeriveSdkClass =
43       static_cast<jclass>(env->NewGlobalRef(env->FindClass(DERIVE_SDK_CLASS_NAME)));
44 
45   if (gDeriveSdkClass == nullptr) {
46     LOG(FATAL) << "Unable to find class : " << DERIVE_SDK_CLASS_NAME;
47   }
48 
49   if (env->RegisterNatives(gDeriveSdkClass, methods, sizeof(methods) / sizeof(methods[0])) < 0) {
50     LOG(FATAL) << "Unable to register native methods";
51   }
52 }
53 }  // namespace derivesdk
54 }  // namespace android
55 
JNI_OnLoad(JavaVM * vm,void *)56 extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) {
57   JNIEnv* env;
58   if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
59     LOG(ERROR) << "ERROR: GetEnv failed";
60     return JNI_ERR;
61   }
62 
63   android::derivesdk::register_com_android_os_ext_testing_DeriveSdk(env);
64 
65   return JNI_VERSION_1_6;
66 }
67