file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
CallJniLib/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 buildToolsVersion '29.0.0' defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { //提供给C++编译器的一个标志 可选 cppFlags "" //声明当前Cmake项目使用的Android abi //abiFilters "armeabi-v7a" //提供给Cmake的参数信息 可选 //arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_TOOLCHAIN=clang" //提供给C编译器的一个标志 可选 //cFlags "-D__STDC_FORMAT_MACROS" //指定哪个so库会被打包到apk中去 可选 //targets "libexample-one", "my-executible-demo" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } //CMake的NDK项目它有自己一套运行流程 //Gradle 调用外部构建脚本CMakeLists.txt //CMake 按照构建脚本的命令将 C++ 源文件 testjnilib.cpp 编译到共享的对象库中,并命名为 libtestjnilib.so ,Gradle 随后会将其打包到APK中 externalNativeBuild { cmake { //声明cmake配置文件路径 path "src/main/cpp/CMakeLists.txt" //声明cmake版本 version "3.10.2" } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.annotation:annotation:1.1.0' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CallJniLib/src/main/cpp/calljnilib.cpp
C++
// // Created by 杨充 on 2023/6/16. // #include "calljnilib.h" #include <jni.h> #include <string> #include <assert.h> #include <android/log.h> #include <string.h> using namespace std; //java路径 #define JNI_CLASS_NAME "com/yc/calljni/CallNativeLib" static const char* TAG ="CallJniLib"; #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args) #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args) void callJavaField(JNIEnv* env,jobject obj,jstring className,jstring fieldName){ jboolean iscopy; const char* name = env->GetStringUTFChars(fieldName,&iscopy); LOGD("invoke method:%s",name); /* * 步骤1:定义类的全限定名:const char* str = "java/lang/String" * 步骤2:找到类的jclass:env->FindClass() * 步骤3:读取类的构造函数:env->GetMethodID(c,"<init>","()V"); * 步骤4:根据构造函数创建一个Object对象:env->NewObject(c,constructMethod); * 步骤5:调用对象的字段和方法: * */ //步骤1:定义类的全限定名 const char* classNameStr = env->GetStringUTFChars(className,&iscopy); //步骤2:找到类的jclass jclass c = env->FindClass(classNameStr); //步骤3:读取类的构造函数 jmethodID constructMethod = env->GetMethodID(c,"<init>","()V"); //步骤4:根据构造函数创建一个Object对象 jobject objCallBack = env->NewObject(c,constructMethod); //步骤5:调用对象的字段和方法,需要先获取类的字段id和方法id /* * 获取字段id * 参数1:class * 参数2:字段名称 * 参数3:字段签名格式 * */ jboolean isCopy; const char* _fieldName = env->GetStringUTFChars(fieldName,&isCopy); /* * 此处如果传入一个找不到的字段会报错,如果不做异常处理,应用直接会崩溃,为了更好的知晓问题所在,需要 * 使用jni异常处理机制 * 此处是native异常,有两种异常处理机制: * 方式1:native层处理 * 方式2:抛出给Java层处理 * */ jfieldID field_Name = env->GetFieldID(c,_fieldName,"Ljava/lang/String;"); /*方式1:native层处理*/ /*检测是否有异常*/ jboolean hasException = env->ExceptionCheck(); if(hasException == JNI_TRUE){ //打印异常,同Java中的printExceptionStack; env->ExceptionDescribe(); //清除当前异常 env->ExceptionClear(); //方式2:抛出异常给上面,让Java层去捕获 jclass noFieldClass = env->FindClass("java/lang/Exception"); std::string msg(_fieldName); std::string header = "找不到该字段"; env->ThrowNew(noFieldClass,header.append(msg).c_str()); env->ReleaseStringUTFChars(fieldName,_fieldName); return; } //没有异常去获取字段的值 jstring fieldObj = static_cast<jstring>(env->GetObjectField(objCallBack, field_Name)); const char* fieldC = env->GetStringUTFChars(fieldObj,&isCopy); LOGD("你成功获取了字段%s值:%s",_fieldName,fieldC); env->ReleaseStringUTFChars(fieldObj,fieldC); } jboolean callJavaMethod(JNIEnv* env,jobject obj1,jstring className,jstring methodName){ /* * 1.找到类:FindClass * 2.创建一个对象 * 3.获取这个类对应的方法id * 4.通过对象和方法id调用对应方法 * 5.释放内存 * */ jboolean isCopy; const char* classNameStr = env->GetStringUTFChars(className,&isCopy); //1.找到类:FindClass jclass callbackClass = env->FindClass(classNameStr); //获取构造函数 jmethodID constructMethod = env->GetMethodID(callbackClass,"<init>","()V"); //2.创建一个对象 jobject objCallBack = env->NewObject(callbackClass,constructMethod); const char* _methodName = env->GetStringUTFChars(methodName,&isCopy); //3.获取这个类对应的方法id jmethodID _jmethodName = env->GetMethodID(callbackClass,_methodName,"(Ljava/lang/String;)V"); const char *str = "123"; /*切记JNI返回类型不能直接使用基础类型,而要用jni语法中定义的类型:如String需要转换为jstring * 不然会报错:JNI DETECTED ERROR IN APPLICATION: use of deleted global reference*/ jstring result = env->NewStringUTF(str); //4.通过对象和方法id调用对应方法 env->CallVoidMethod(objCallBack,_jmethodName,result); if(env->ExceptionCheck()){ env->ExceptionDescribe(); env->ExceptionClear(); } //释放字符串内存 env->ReleaseStringUTFChars(methodName,_methodName); env->ReleaseStringUTFChars(className,classNameStr); return JNI_TRUE; } static JNINativeMethod gMethods[] = { {"callJavaField","(Ljava/lang/String;Ljava/lang/String;)V",(void *)callJavaField}, {"callJavaMethod","(Ljava/lang/String;Ljava/lang/String;)Z",(void *)callJavaMethod}, }; int register_dynamic_Methods(JNIEnv *env){ std::string s = JNI_CLASS_NAME; const char* className = s.c_str(); jclass clazz = env->FindClass(className); if(clazz == NULL){ return JNI_FALSE; } //注册JNI方法 if(env->RegisterNatives(clazz,gMethods,sizeof(gMethods)/sizeof(gMethods[0]))<0){ return JNI_FALSE; } return JNI_TRUE; } jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; if(vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK){ return JNI_ERR; } assert(env != NULL); if(!register_dynamic_Methods(env)){ return JNI_ERR; } return JNI_VERSION_1_6; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CallJniLib/src/main/cpp/calljnilib.h
C/C++ Header
#include <jni.h> // // Created by 杨充 on 2023/6/7. // //约定俗成的操作是 .h 文件主要负责类成员变量和方法的声明; .cpp 文件主要负责成员变量和方法的定义。 //ida打开显示为:assume cs:yc #define JNI_SECTION ".yc" //#ifndef YCJNIHELPER_TESTJNILIB_H //#define YCJNIHELPER_TESTJNILIB_H // //#endif //YCJNIHELPER_TESTJNILIB_H //__cplusplus这个宏是微软自定义宏,表示是C++编译 //两个一样的函数,在c在函数是通过函数名来识别的,而在C++中,由于存在函数的重载问题,函数的识别方式通函数名、函数的返回类型、函数参数列表三者组合来完成的。 //因此上面两个相同的函数,经过C,C++编绎后会产生完全不同的名字。所以,如果把一个用c编绎器编绎的目标代码和一个用C++编绎器编绎的目标代码进行连接,就会出现连接失败的错误。 //extern "C" 是为了避免C++编绎器按照C++的方式去编绎C函数, #ifdef __cplusplus //注意:此处对引入的是函数使用了extern "C"对方法进行了包裹,目的就是为了当引用的是cpp文件,extern "C"修饰的函数可以让外部访问到。 extern "C" { #endif void callJavaField(JNIEnv* env,jobject obj,jstring className,jstring fieldName); jboolean callJavaMethod(JNIEnv* env,jobject obj1,jstring className,jstring methodName); #ifdef __cplusplus } #endif
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CallJniLib/src/main/java/com/yc/calljni/CallNativeLib.java
Java
package com.yc.calljni; public class CallNativeLib { private static CallNativeLib instance; // Used to load the 'calljnilib' library on application startup. static { System.loadLibrary("calljnilib"); } public static CallNativeLib getInstance() { if (instance == null) { synchronized (CallNativeLib.class) { if (instance == null) { instance = new CallNativeLib(); } } } return instance; } private void test(){ try{ callJavaField("com/yc/calljni/HelloCallBack","name"); callJavaMethod("com/yc/calljni/HelloCallBack","updateName"); }catch (Exception e){ e.printStackTrace(); } } /** * native调用java代码,c/c++调用java */ public native void callJavaField(String className,String fieldName) ; public native boolean callJavaMethod(String className,String methodName) ; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CallJniLib/src/main/java/com/yc/calljni/HelloCallBack.java
Java
package com.yc.calljni; import android.util.Log; public class HelloCallBack { String name = "HelloCallBack"; void updateName(String name) { this.name = name; Log.d("CallJni", "你成功调用了HelloCallBack的方法:" +name); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 buildToolsVersion '29.0.0' defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { cppFlags "" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" //声明cmake版本 version "3.10.2" } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/cpp/crash_dumper.cpp
C++
#include <jni.h> #include <string> #include <android/log.h> #include <fstream> #include <map> #include <unistd.h> #include <unwind.h> #include <dlfcn.h> #include "stack_tracer.h" JavaVM *g_vm; #define SIGNAL_COUNT 8 static struct sigaction g_oldSigActions[SIGNAL_COUNT] = {0}; char *tombstone_file_path = NULL; // do not need deleteGlobalRef, because process will be killed, or always listening jobject g_crashListener = NULL; /** * handleMode masks,refer to Java class: HandleMode */ #define HANDLE_MODE_DO_NOTHING 0b00 #define HANDLE_MODE_RAISE_ERROR 0b01 #define HANDLE_MODE_NOTICE_CALLBACK 0b10 static int handleMode = HANDLE_MODE_DO_NOTHING; /** * 代表信号量,可以是除 SIGKILL 和 SIGSTOP 外的任何一个特定有效的信号量,SIGKILL和SIGSTOP既不能被捕捉,也不能被忽略。 * 同一个信号在不同的系统中值可能不一样,所以建议最好使用为信号定义的名字。 */ static int signals[SIGNAL_COUNT] = { SIGTRAP, SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGSYS }; static std::map<int, const char *> signal_names = { {SIGTRAP, "SIGTRAP"}, {SIGABRT, "SIGABRT"}, {SIGILL, "SIGILL"}, {SIGSEGV, "SIGSEGV"}, {SIGFPE, "SIGFPE"}, {SIGBUS, "SIGBUS"}, {SIGPIPE, "SIGPIPE"}, {SIGSYS, "SIGSYS"} }; static std::map<int, const char *> si_names = { {SI_USER, "SI_USER"}, {SI_KERNEL, "SI_KERNEL"}, {SI_QUEUE, "SI_QUEUE"}, {SI_TIMER, "SI_TIMER"}, {SI_MESGQ, "SI_MESGQ"}, {SI_ASYNCIO, "SI_ASYNCIO"}, {SI_SIGIO, "SI_SIGIO"}, {SI_TKILL, "SI_TKILL"}, {SI_DETHREAD, "SI_DETHREAD"}, {SI_ASYNCNL, "SI_ASYNCNL"} }; void noticeCallback(int signal, std::string logPath); JNIEnv *attachEnv(bool *handAttached); void detachEnv(JNIEnv *env, bool byAttach); std::string getRegisterInfo(const ucontext_t *ucontext); std::string getDumpFileName() { time_t timep; time(&timep); char tmp[64]; strftime(tmp, sizeof(tmp), "/%Y-%m-%d-%H-%M-%S.txt", localtime(&timep)); return tmp; } std::string getCrashTimeStamp() { time_t timep; time(&timep); char tmp[64]; strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S%z", localtime(&timep)); return tmp; } const char *getABI() { // It's usually most convenient to determine the ABI at build time using #ifdef in conjunction with: // // __arm__ for 32-bit ARM // __aarch64__ for 64-bit ARM // __i386__ for 32-bit X86 // __x86_64__ for 64-bit X86 // Note that 32-bit X86 is called __i386__, not __x86__ as you might expect! // // https://developer.android.google.cn/ndk/guides/cpu-features?hl=en #if defined(__aarch64__) return "arm64"; #elif defined(__arm__) return "arm"; #else return "unknown"; #endif } // 获取header信息 std::string getHeaderInfo() { //Build fingerprint //读取系统的ro.build.fingerprint字段信息即可 char finger[92] = {0}; __system_property_get("ro.build.fingerprint", finger); if (strlen(finger) == 0) { strcpy(finger, "unknown"); } //revision //读取系统的ro.revision字段信息即可 char revision[92] = {0}; __system_property_get("ro.revision", revision); if (strlen(revision) == 0) { strcpy(revision, "unknown"); } //abi //我们可以读取so中的内容判断,也可以在编译期就进行判断,这里选择在编译期判断 const char *abi = getABI(); char result[256] = {0}; sprintf(result, "Build fingerprint: '%s'\r\nRevision: '%s'\r\nABI: '%s'", finger, revision, abi); return result; } void unregisterSigHandler() { for (int i = 0; i < SIGNAL_COUNT; ++i) { sigaction(signals[i], &g_oldSigActions[i], NULL); } memset(g_oldSigActions, 0, sizeof(g_oldSigActions)); } /** * 获取进程名称 * @param pid 进程号 * @return */ std::string get_process_name_by_pid(const int pid) { char processName[256] = {0}; char cmd[64] = {0}; sprintf(cmd, "/proc/%d/cmdline", pid); FILE *f = fopen(cmd, "r"); if (f) { size_t size; size = fread(processName, sizeof(char), 256, f); if (size > 0 && '\n' == processName[size - 1]) { processName[size - 1] = '\0'; } fclose(f); } return processName; } void sigHandler(int sig, siginfo_t *info, void *context) { std::string desc; desc.append("*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\r\n") .append(getHeaderInfo()).append("\r\n") .append("Timestamp: ").append(getCrashTimeStamp()).append("\r\n") .append("pid: ").append(std::to_string(info->_sifields._kill._pid)) .append(", uid: ").append(std::to_string(info->_sifields._kill._uid)) .append(", process: >>> ").append( get_process_name_by_pid(info->_sifields._kill._pid)).append(" <<<\r\n") .append("signal ").append(std::to_string(sig)).append(" (").append(signal_names[sig]) .append("), code ").append(std::to_string(info->si_code)) .append(" (").append(si_names[info->si_code]) .append("), fault addr --------\r\n") .append(getRegisterInfo((const ucontext_t *) context)) .append("\r\nbacktrace:"); std::string result; storeCallStack(&result); std::string path = tombstone_file_path; path += getDumpFileName(); std::ofstream outStream(path.c_str(), std::ios::out); if (outStream) { const char *logContent = result.c_str(); outStream.write(desc.c_str(), desc.length()); outStream.write("\r\n", strlen("\r\n")); outStream.write(logContent, result.length()); outStream.close(); } switch (handleMode) { case HANDLE_MODE_RAISE_ERROR: unregisterSigHandler(); raise(sig); break; case HANDLE_MODE_NOTICE_CALLBACK: noticeCallback(sig, path.c_str()); break; case HANDLE_MODE_DO_NOTHING: default: break; } } std::string getRegisterInfo(const ucontext_t *ucontext) { std::string ctxTxt; #if defined(__aarch64__) for (int i = 0; i < 30; ++i) { if (i % 4 == 0) { ctxTxt.append(" "); } char info[64] = {0}; sprintf(info, "x%d %016lx ", i, ucontext->uc_mcontext.regs[i]); ctxTxt.append(info); if ((i + 1) % 4 == 0) { ctxTxt.append("\r\n"); } } ctxTxt.append("\r\n"); char spInfo[64] = {0}; sprintf(spInfo, "sp %016lx ", ucontext->uc_mcontext.sp); char lrInfo[64] = {0}; sprintf(lrInfo, "lr %016lx ", ucontext->uc_mcontext.regs[30]); char pcInfo[64] = {0}; sprintf(pcInfo, "pc %016lx ", ucontext->uc_mcontext.pc); ctxTxt.append(" ").append(spInfo).append(lrInfo).append(pcInfo); #elif defined(__arm__) char x0Info[64] = {0}; sprintf(x0Info, "x0 %08lx ", ucontext->uc_mcontext.arm_r0); char x1Info[64] = {0}; sprintf(x1Info, "x1 %08lx ", ucontext->uc_mcontext.arm_r1); char x2Info[64] = {0}; sprintf(x2Info, "x2 %08lx ", ucontext->uc_mcontext.arm_r2); char x3Info[64] = {0}; sprintf(x3Info, "x3 %08lx ", ucontext->uc_mcontext.arm_r3); char x4Info[64] = {0}; sprintf(x4Info, "x4 %08lx ", ucontext->uc_mcontext.arm_r4); char x5Info[64] = {0}; sprintf(x5Info, "x5 %08lx ", ucontext->uc_mcontext.arm_r5); char x6Info[64] = {0}; sprintf(x6Info, "x6 %08lx ", ucontext->uc_mcontext.arm_r6); char x7Info[64] = {0}; sprintf(x7Info, "x7 %08lx ", ucontext->uc_mcontext.arm_r7); char x8Info[64] = {0}; sprintf(x8Info, "x8 %08lx ", ucontext->uc_mcontext.arm_r8); char x9Info[64] = {0}; sprintf(x9Info, "x9 %08lx ", ucontext->uc_mcontext.arm_r9); char x10Info[64] = {0}; sprintf(x10Info, "x10 %08lx ", ucontext->uc_mcontext.arm_r10); char ipInfo[64] = {0}; sprintf(ipInfo, "ip %08lx ", ucontext->uc_mcontext.arm_ip); char spInfo[64] = {0}; sprintf(spInfo, "sp %08lx ", ucontext->uc_mcontext.arm_sp); char lrInfo[64] = {0}; sprintf(lrInfo, "lr %08lx ", ucontext->uc_mcontext.arm_lr); char pcInfo[64] = {0}; sprintf(pcInfo, "pc %08lx ", ucontext->uc_mcontext.arm_pc); ctxTxt.append(" ").append(x0Info).append(x1Info).append(x2Info).append(x3Info).append( "\r\n") .append(" ").append(x4Info).append(x5Info).append(x6Info).append(x7Info).append( "\r\n") .append(" ").append(x8Info).append(x9Info).append(x10Info).append("\r\n") .append(" ").append(ipInfo).append(spInfo).append(lrInfo).append(pcInfo); #endif return ctxTxt; } /** * 注册信号处理函数 */ void registerSigHandler() { // create new actions struct sigaction newSigAction; sigemptyset(&newSigAction.sa_mask); newSigAction.sa_flags = SA_SIGINFO; // set custom handle function newSigAction.sa_sigaction = sigHandler; // set new action for each signal, and save old actions memset(g_oldSigActions, 0, sizeof(g_oldSigActions)); for (int i = 0; i < SIGNAL_COUNT; ++i) { //进程通过 sigaction() 函数来指定对某个信号的处理行为。 //sig:代表信号量,可以是除 SIGKILL 和 SIGSTOP 外的任何一个特定有效的信号量,SIGKILL和SIGSTOP既不能被捕捉,也不能被忽略。同一个信号在不同的系统中值可能不一样,所以建议最好使用为信号定义的名字。 //new_action:指向结构体 sigaction 的一个实例的指针,该实例指定了对特定信号的处理,如果设置为空,进程会执行默认处理。 //old_action:和参数 new_action 类似,只不过保存的是原来对相应信号的处理,也可设置为 NULL。 sigaction(signals[i], &newSigAction, &g_oldSigActions[i]); } } void nativeInit(JNIEnv *env, jobject clazz, jstring crash_dump_dir, jobject crash_listener, jint handle_mode) { if (g_crashListener) { env->DeleteGlobalRef(g_crashListener); g_crashListener = NULL; } if (crash_listener) { g_crashListener = env->NewGlobalRef(crash_listener); } handleMode = handle_mode; const char *crashDumpDir = env->GetStringUTFChars(crash_dump_dir, JNI_FALSE); long strLen = strlen(crashDumpDir); if (tombstone_file_path != NULL) { free(tombstone_file_path); } tombstone_file_path = static_cast<char *>(malloc(strLen + 1)); memset(tombstone_file_path, 0, strLen); strcpy(tombstone_file_path, crashDumpDir); env->ReleaseStringUTFChars(crash_dump_dir, crashDumpDir); //注册信号处理函数 registerSigHandler(); } void noticeCallback(int signal, std::string logPath) { if (g_crashListener == NULL) { return; } bool byAttach = false; JNIEnv *env = attachEnv(&byAttach); if (!env) { return; } jclass crashListenerClazz = env->GetObjectClass(g_crashListener); jmethodID onSignalReceivedId = env->GetMethodID(crashListenerClazz, "onSignalReceived", "(ILjava/lang/String;)V"); env->CallVoidMethod(g_crashListener, onSignalReceivedId, signal, env->NewStringUTF(logPath.c_str())); detachEnv(env, byAttach); } JNIEnv *attachEnv(bool *handAttach) { JNIEnv *env; int status = g_vm->GetEnv((void **) &env, JNI_VERSION_1_4); if (status != JNI_OK) { int getEnvCode = g_vm->AttachCurrentThread(&env, NULL); if (JNI_OK == getEnvCode) { *handAttach = true; return env; } else { return NULL; } } else { return env; } } void detachEnv(JNIEnv *env, bool byAttach) { if (env && byAttach) { g_vm->DetachCurrentThread(); } } JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { g_vm = vm; bool byAttach = false; JNIEnv *env = attachEnv(&byAttach); if (env == NULL) { return JNI_ERR; } jclass crashDumperClazz = env->FindClass("com/yc/crash/NativeCrashDumper"); JNINativeMethod jniNativeMethod[] = { {"nativeInit", "(Ljava/lang/String;Lcom/yc/crash/NativeCrashListener;I)V", (void *) nativeInit} }; if (env->RegisterNatives(crashDumperClazz, jniNativeMethod, sizeof(jniNativeMethod) / sizeof((jniNativeMethod)[0])) < 0) { return JNI_ERR; } detachEnv(env, byAttach); return JNI_VERSION_1_4; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/cpp/readelf.cpp
C++
#include "readelf.h" #include <elf.h> #include <string> #include <android/log.h> #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"yc_testjni_readelf" ,__VA_ARGS__) #define SEC_NAME_BUILD_ID ".note.gnu.build-id" #if defined(__aarch64__) #define Elf_Ehdr Elf64_Ehdr #define Elf_Shdr Elf64_Shdr #elif defined(__arm__) #define Elf_Ehdr Elf32_Ehdr #define Elf_Shdr Elf32_Shdr #endif std::string getBuildIdFromFile(const char *path) { FILE *elfFile = fopen(path, "rb"); if (elfFile) { fseek(elfFile, 0L, SEEK_END); long len = ftell(elfFile); fseek(elfFile, 0L, SEEK_SET); auto *elfData = (unsigned char *) malloc(len); fread(elfData, sizeof(char), len, elfFile); fclose(elfFile); std::string buildIdStr = getBuildId(elfData); free(elfData); return buildIdStr; } else { return ""; } } std::string getBuildId(unsigned char *elfData) { Elf_Ehdr *elfHeader = (Elf_Ehdr *) elfData; Elf_Shdr *namesSectionHeader = (Elf_Shdr *) (elfData + elfHeader->e_shoff + elfHeader->e_shstrndx * elfHeader->e_shentsize); char *sectionNames = (char *) (elfData + namesSectionHeader->sh_offset); for (int i = 0; i < elfHeader->e_shnum; ++i) { Elf_Shdr *sectionHeader = (Elf_Shdr *) (elfData + elfHeader->e_shoff + i * elfHeader->e_shentsize); if (strcmp((const char *) sectionNames + sectionHeader->sh_name, SEC_NAME_BUILD_ID) == 0) { char *buildId = (char *) malloc(sectionHeader->sh_size); memcpy(buildId, elfData + sectionHeader->sh_offset, sectionHeader->sh_size); std::string buildIdStr; // offset 0x10 (16) // +----------------+ // | namesz | 32-bit, size of "name" field // +----------------+ // | descsz | 32-bit, size of "desc" field // +----------------+ // | type | 32-bit, vendor specific "type" // +----------------+ // | name | "namesz" bytes, null-terminated string // +----------------+ // | desc | "descsz" bytes, binary data // +----------------+ // https://interrupt.memfault.com/blog/gnu-build-id-for-firmware // // 04000000 14000000 03000000 47 4e 55 00 // namesz descsz type G N U 0 // 4 + 4 + 4 + 4 = 16 int nameSize = *buildId; int descOffset = 4 + 4 + 4 + nameSize; for (int j = descOffset; j < sectionHeader->sh_size; ++j) { char ch[3] = {0}; sprintf(ch, "%02x", buildId[j]); buildIdStr += ch; } free(buildId); return buildIdStr; } } return ""; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/cpp/readelf.h
C/C++ Header
#include <string> /** * return the buildId of shared object * * @param elfData so file data * @return buildId */ std::string getBuildId(unsigned char *elfData); /** * return the buildId of shared object * * @param elfData so file path * @return buildId */ std::string getBuildIdFromFile(const char *path);
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/cpp/stack_tracer.cpp
C++
#include "stack_tracer.h" #include "readelf.h" #include <unwind.h> #include <dlfcn.h> #include <android/log.h> #include <cstdio> #include <malloc.h> #include <fstream> #include <ctime> #include <map> typedef struct TraceInfo { int depth; std::string result; } BackTraceInfo; std::map<const char *, std::string> buildIdMap; std::string getSharedObjectBuildId(const char *path) { std::string buildId = buildIdMap[path]; if (buildId.length() == 0) { buildId = getBuildIdFromFile(path); buildIdMap[path] = buildId; } return buildId; } _Unwind_Reason_Code traceBackCallStack(_Unwind_Context *context, void *hnd) { auto *traceHandle = (BackTraceInfo *) hnd; _Unwind_Word ip = _Unwind_GetIP(context); Dl_info info; int res = dladdr((void *) ip, &info); if (res == 0) { return _URC_END_OF_STACK; } char *desc = (char *) malloc(1024); memset(desc, 0, 1024); std::string buildId; if (info.dli_fname != NULL) { char *symbol = (char *) malloc(256); if (info.dli_sname == NULL) { strcpy(symbol, "unknown"); } else { sprintf(symbol, "%s+%ld", info.dli_sname, ip - (_Unwind_Word) info.dli_saddr); } buildId = getSharedObjectBuildId(info.dli_fname); if (buildId.length() > 0) { buildId = "(BuildId: " + buildId + ")"; } #if defined(__arm__) sprintf(desc, " #%02d pc %08lx %s (%s) ", traceHandle->depth, ip - (_Unwind_Word) info.dli_fbase, info.dli_fname, symbol); #elif defined(__aarch64__) sprintf(desc, " #%02d pc %016lx %s (%s) ", traceHandle->depth, ip - (_Unwind_Word) info.dli_fbase, info.dli_fname, symbol); #endif free(symbol); } if (traceHandle->result.length() != 0) { traceHandle->result.append("\r\n"); } traceHandle->result.append(desc).append(buildId); free(desc); ++traceHandle->depth; // FIXME: crash if call stack is over 5 on ARM32, unknown reason #if !defined(__aarch64__) && defined(__arm__) if (traceHandle->depth == 5) { return _URC_END_OF_STACK; } #endif return _URC_NO_REASON; } void storeCallStack(std::string *result) { BackTraceInfo traceInfo; traceInfo.depth = 0; _Unwind_Backtrace(traceBackCallStack, &traceInfo); *result += traceInfo.result; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/cpp/stack_tracer.h
C/C++ Header
#include <string> void storeCallStack(std::string *result);
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/java/com/yc/crash/NativeCrashDumper.java
Java
package com.yc.crash; import java.io.File; public class NativeCrashDumper { static { //java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList //couldn't find "libcrash_dumper.so" System.loadLibrary("crash_dumper"); } private static final class InstanceHolder { static final NativeCrashDumper instance = new NativeCrashDumper(); } public static NativeCrashDumper getInstance() { return InstanceHolder.instance; } private native void nativeInit(String crashDumpDir, NativeCrashListener nativeCrashListener, int handleMode); public boolean init(String crashDumpDir, NativeCrashListener nativeCrashListener, NativeHandleMode handleMode) { if (crashDumpDir == null) { return false; } File dir = new File(crashDumpDir); if ((dir.exists() && dir.isDirectory()) || dir.mkdirs()) { nativeInit(crashDumpDir, nativeCrashListener, handleMode.mode); return true; } return false; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/java/com/yc/crash/NativeCrashListener.java
Java
package com.yc.crash; public interface NativeCrashListener { void onSignalReceived(int signal, String logPath); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
CrashDumper/src/main/java/com/yc/crash/NativeHandleMode.java
Java
package com.yc.crash; /** * 捕获信号,记录日志后的处理方式 */ public enum NativeHandleMode { /** * 什么都不做 */ DO_NOTHING(0), /** * 将捕获到的SIGNAL重新抛出 */ RAISE_ERROR(1), /** * 通知Java端的Callback */ NOTICE_CALLBACK(2); final int mode; NativeHandleMode(int mode) { this.mode = mode; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 defaultConfig { minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { cppFlags "-std=c++11" // arguments "-DANDROID_TOOLCHAIN=gcc" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } externalNativeBuild { cmake { path 'src/main/cpp/CMakeLists.txt' } } lintOptions { abortOnError false } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } buildToolsVersion '29.0.0' } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "com.github.tiann:FreeReflection:3.1.0" api 'me.weishu.exposed:exposed-xposedapi:0.4.5' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/cpp/art.cpp
C++
/* * Copyright (c) 2017, weishu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "art.h" #include <android/log.h> #include <cstddef> #define LOGV(...) ((void)__android_log_print(ANDROID_LOG_INFO, "epic.Native", __VA_ARGS__)) #define ANDROID_R_API 30 #define MAX_SEARCH_LEN 2000 void* ArtHelper::runtime_instance_ = nullptr; int ArtHelper::api = 0; template <typename T> inline int find_offset(void* hay, int size, T needle) { for (int i = 0; i < size; i += sizeof(T)) { auto current = reinterpret_cast<T*>(reinterpret_cast<char*>(hay) + i); if (*current == needle) { return i; } } return -1; } void ArtHelper::init(JNIEnv* env, int api) { ArtHelper::api = api; JavaVM* javaVM; env->GetJavaVM(&javaVM); JavaVMExt* javaVMExt = (JavaVMExt*)javaVM; void* runtime = javaVMExt->runtime; if (runtime == nullptr) { return; } if (api < ANDROID_R_API) { runtime_instance_ = runtime; } else { int vm_offset = find_offset(runtime, MAX_SEARCH_LEN, javaVM); runtime_instance_ = reinterpret_cast<void*>(reinterpret_cast<char*>(runtime) + vm_offset - offsetof(PartialRuntimeR, java_vm_)); } } void* ArtHelper::getClassLinker() { if (runtime_instance_ == nullptr || api < ANDROID_R_API) { return nullptr; } PartialRuntimeR* runtimeR = (PartialRuntimeR*)runtime_instance_; return runtimeR->class_linker_; } void* ArtHelper::getJniIdManager() { if (runtime_instance_ == nullptr || api < ANDROID_R_API) { return nullptr; } PartialRuntimeR* runtimeR = (PartialRuntimeR*)runtime_instance_; return runtimeR->jni_id_manager_; } void* ArtHelper::getJitCodeCache() { if (runtime_instance_ == nullptr || api < ANDROID_R_API) { return nullptr; } PartialRuntimeR* runtimeR = (PartialRuntimeR*)runtime_instance_; return runtimeR->jit_code_cache_; } void* ArtHelper::getHeap() { if (runtime_instance_ == nullptr) { return nullptr; } if (api < 26) { Runtime_7X* runtime7X = (Runtime_7X*)runtime_instance_; return runtime7X->heap_; } else if (api < ANDROID_R_API) { Runtime_8X* runtime8X = (Runtime_8X*)runtime_instance_; LOGV("bootclasspath : %s", runtime8X->boot_class_path_string_.c_str()); return runtime8X->heap_; } else { PartialRuntimeR* runtimeR = (PartialRuntimeR*)runtime_instance_; return runtimeR->heap_; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/cpp/art.h
C/C++ Header
/* * Copyright (c) 2017, weishu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EPIC_ART_H #define EPIC_ART_H #include <jni.h> #include <list> #include <stdint.h> #include <string> #include <vector> // Android 6.0: http://androidxref.com/6.0.0_r5/xref/art/runtime/runtime.h // Android 7.0: http://androidxref.com/7.0.0_r1/xref/art/runtime/runtime.h // Android 7.1.1: http://androidxref.com/7.1.1_r6/xref/art/runtime/runtime.h // Android 8.0: http://androidxref.com/8.0.0_r4/xref/art/runtime/runtime.h struct Runtime_7X { uint64_t callee_save_methods_[3]; void* pre_allocated_OutOfMemoryError_; void* pre_allocated_NoClassDefFoundError_; void* resolution_method_; void* imt_conflict_method_; // Unresolved method has the same behavior as the conflict method, it is used by the class linker // for differentiating between unfilled imt slots vs conflict slots in superclasses. void* imt_unimplemented_method_; void* sentinel_; int instruction_set_; uint32_t callee_save_method_frame_infos_[9]; // QuickMethodFrameInfo = uint32_t * 3 void* compiler_callbacks_; bool is_zygote_; bool must_relocate_; bool is_concurrent_gc_enabled_; bool is_explicit_gc_disabled_; bool dex2oat_enabled_; bool image_dex2oat_enabled_; std::string compiler_executable_; std::string patchoat_executable_; std::vector<std::string> compiler_options_; std::vector<std::string> image_compiler_options_; std::string image_location_; std::string boot_class_path_string_; std::string class_path_string_; std::vector<std::string> properties_; // The default stack size for managed threads created by the runtime. size_t default_stack_size_; void* heap_; }; struct Runtime_8X { uint64_t callee_save_methods_[3]; void* pre_allocated_OutOfMemoryError_; void* pre_allocated_NoClassDefFoundError_; void* resolution_method_; void* imt_conflict_method_; // Unresolved method has the same behavior as the conflict method, it is used by the class linker // for differentiating between unfilled imt slots vs conflict slots in superclasses. void* imt_unimplemented_method_; void* sentinel_; int instruction_set_; uint32_t callee_save_method_frame_infos_[9]; // QuickMethodFrameInfo = uint32_t * 3 void* compiler_callbacks_; bool is_zygote_; bool must_relocate_; bool is_concurrent_gc_enabled_; bool is_explicit_gc_disabled_; bool dex2oat_enabled_; bool image_dex2oat_enabled_; std::string compiler_executable_; std::string patchoat_executable_; std::vector<std::string> compiler_options_; std::vector<std::string> image_compiler_options_; std::string image_location_; std::string boot_class_path_string_; std::string class_path_string_; std::vector<std::string> properties_; std::list<void*> agents_; std::vector<void*> plugins_; // The default stack size for managed threads created by the runtime. size_t default_stack_size_; void* heap_; }; struct PartialRuntimeR { void* heap_; void* jit_arena_pool_; void* arena_pool_; // Special low 4gb pool for compiler linear alloc. We need ArtFields to be in low 4gb if we are // compiling using a 32 bit image on a 64 bit compiler in case we resolve things in the image // since the field arrays are int arrays in this case. void* low_4gb_arena_pool_; // Shared linear alloc for now. void* linear_alloc_; // The number of spins that are done before thread suspension is used to forcibly inflate. size_t max_spins_before_thin_lock_inflation_; void* monitor_list_; void* monitor_pool_; void* thread_list_; void* intern_table_; void* class_linker_; void* signal_catcher_; void* jni_id_manager_; void* java_vm_; void* jit_; void* jit_code_cache_; }; struct JavaVMExt { void* functions; void* runtime; }; class ArtHelper { public: static void init(JNIEnv*, int); static void* getRuntimeInstance() { return runtime_instance_; } static void* getClassLinker(); static void* getJniIdManager(); static void* getJitCodeCache(); static void* getHeap(); private: static void* runtime_instance_; static int api; }; #endif //EPIC_ART_H
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/cpp/epic.cpp
C++
/* * Original Copyright 2014-2015 Marvin Wißfeld * Modified work Copyright (c) 2017, weishu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <jni.h> #include <android/log.h> #include <sys/mman.h> #include <errno.h> #include <unistd.h> #include <dlfcn.h> #include <cstdlib> #include <sys/system_properties.h> #include <fcntl.h> #include "fake_dlfcn.h" #include "art.h" #undef NDEBUG #ifdef NDEBUG #define LOGV(...) ((void)__android_log_print(ANDROID_LOG_INFO, "epic.Native", __VA_ARGS__)) #else #define LOGV(...) #endif #define JNIHOOK_CLASS "me/weishu/epic/art/EpicNative" jobject (*addWeakGloablReference)(JavaVM *, void *, void *) = nullptr; void* (*jit_load_)(bool*) = nullptr; void* jit_compiler_handle_ = nullptr; bool (*jit_compile_method_)(void*, void*, void*, bool) = nullptr; void* (*JitCodeCache_GetCurrentRegion)(void*) = nullptr; typedef bool (*JIT_COMPILE_METHOD1)(void *, void *, void *, bool); typedef bool (*JIT_COMPILE_METHOD2)(void *, void *, void *, bool, bool); // Android Q typedef bool (*JIT_COMPILE_METHOD3)(void *, void *, void *, void *, bool, bool); // Android R typedef bool (*JIT_COMPILE_METHOD4)(void *, void *, void *, void *, int); // Android S void (*jit_unload_)(void*) = nullptr; class ScopedSuspendAll {}; void (*suspendAll)(ScopedSuspendAll*, char*) = nullptr; void (*resumeAll)(ScopedSuspendAll*) = nullptr; class ScopedJitSuspend {}; void (*startJit)(ScopedJitSuspend*) = nullptr; void (*stopJit)(ScopedJitSuspend*) = nullptr; void (*DisableMovingGc)(void*) = nullptr; void* (*JniIdManager_DecodeMethodId_)(void*, jlong) = nullptr; void* (*ClassLinker_MakeInitializedClassesVisiblyInitialized_)(void*, void*, bool) = nullptr; void* __self() { #ifdef __arm__ register uint32_t r9 asm("r9"); return (void*) r9; #elif defined(__aarch64__) register uint64_t x19 asm("x19"); return (void*) x19; #else #endif }; static int api_level; void init_entries(JNIEnv *env) { char api_level_str[5]; __system_property_get("ro.build.version.sdk", api_level_str); api_level = atoi(api_level_str); LOGV("api level: %d", api_level); ArtHelper::init(env, api_level); if (api_level < 23) { // Android L, art::JavaVMExt::AddWeakGlobalReference(art::Thread*, art::mirror::Object*) void *handle = dlopen("libart.so", RTLD_LAZY | RTLD_GLOBAL); addWeakGloablReference = (jobject (*)(JavaVM *, void *, void *)) dlsym(handle, "_ZN3art9JavaVMExt22AddWeakGlobalReferenceEPNS_6ThreadEPNS_6mirror6ObjectE"); } else if (api_level < 24) { // Android M, art::JavaVMExt::AddWeakGlobalRef(art::Thread*, art::mirror::Object*) void *handle = dlopen("libart.so", RTLD_LAZY | RTLD_GLOBAL); addWeakGloablReference = (jobject (*)(JavaVM *, void *, void *)) dlsym(handle, "_ZN3art9JavaVMExt16AddWeakGlobalRefEPNS_6ThreadEPNS_6mirror6ObjectE"); } else { // Android N and O, Google disallow us use dlsym; void *handle = dlopen_ex("libart.so", RTLD_NOW); void *jit_lib = dlopen_ex("libart-compiler.so", RTLD_NOW); LOGV("fake dlopen install: %p", handle); const char *addWeakGloablReferenceSymbol = api_level <= 25 ? "_ZN3art9JavaVMExt16AddWeakGlobalRefEPNS_6ThreadEPNS_6mirror6ObjectE" : "_ZN3art9JavaVMExt16AddWeakGlobalRefEPNS_6ThreadENS_6ObjPtrINS_6mirror6ObjectEEE"; addWeakGloablReference = (jobject (*)(JavaVM *, void *, void *)) dlsym_ex(handle, addWeakGloablReferenceSymbol); jit_compile_method_ = (bool (*)(void *, void *, void *, bool)) dlsym_ex(jit_lib, "jit_compile_method"); jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym_ex(jit_lib, "jit_load")); bool generate_debug_info = false; jit_compiler_handle_ = (jit_load_)(&generate_debug_info); LOGV("jit compile_method: %p", jit_compile_method_); suspendAll = reinterpret_cast<void (*)(ScopedSuspendAll*, char*)>(dlsym_ex(handle, "_ZN3art16ScopedSuspendAllC1EPKcb")); resumeAll = reinterpret_cast<void (*)(ScopedSuspendAll*)>(dlsym_ex(handle, "_ZN3art16ScopedSuspendAllD1Ev")); if (api_level >= 30) { // Android R would not directly return ArtMethod address but an internal id ClassLinker_MakeInitializedClassesVisiblyInitialized_ = reinterpret_cast<void* (*)(void*, void*, bool)>(dlsym_ex(handle, "_ZN3art11ClassLinker40MakeInitializedClassesVisiblyInitializedEPNS_6ThreadEb")); JniIdManager_DecodeMethodId_ = reinterpret_cast<void* (*)(void*, jlong)>(dlsym_ex(handle, "_ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID")); if (api_level >= 31) { // Android S CompileMethod accepts a CompilationKind enum instead of two booleans // source: https://android.googlesource.com/platform/art/+/refs/heads/android12-release/compiler/jit/jit_compiler.cc jit_compile_method_ = (bool (*)(void *, void *, void *, bool)) dlsym_ex(jit_lib, "_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodENS_15CompilationKindE"); } else { jit_compile_method_ = (bool (*)(void *, void *, void *, bool)) dlsym_ex(jit_lib, "_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodEbb"); } JitCodeCache_GetCurrentRegion = (void* (*)(void*)) dlsym_ex(handle, "_ZN3art3jit12JitCodeCache16GetCurrentRegionEv"); } // Disable this now. // startJit = reinterpret_cast<void(*)(ScopedJitSuspend*)>(dlsym_ex(handle, "_ZN3art3jit16ScopedJitSuspendD1Ev")); // stopJit = reinterpret_cast<void(*)(ScopedJitSuspend*)>(dlsym_ex(handle, "_ZN3art3jit16ScopedJitSuspendC1Ev")); // DisableMovingGc = reinterpret_cast<void(*)(void*)>(dlsym_ex(handle, "_ZN3art2gc4Heap15DisableMovingGcEv")); } LOGV("addWeakGloablReference: %p", addWeakGloablReference); } jboolean epic_compile(JNIEnv *env, jclass, jobject method, jlong self) { LOGV("self from native peer: %p, from register: %p", reinterpret_cast<void*>(self), __self()); jlong art_method = (jlong) env->FromReflectedMethod(method); if (art_method % 2 == 1) { art_method = reinterpret_cast<jlong>(JniIdManager_DecodeMethodId_(ArtHelper::getJniIdManager(), art_method)); } bool ret; if (api_level >= 30) { void* current_region = JitCodeCache_GetCurrentRegion(ArtHelper::getJitCodeCache()); if (api_level >= 31) { ret = ((JIT_COMPILE_METHOD4)jit_compile_method_)(jit_compiler_handle_, reinterpret_cast<void*>(self), reinterpret_cast<void*>(current_region), reinterpret_cast<void*>(art_method), 1); } else { ret = ((JIT_COMPILE_METHOD3)jit_compile_method_)(jit_compiler_handle_, reinterpret_cast<void*>(self), reinterpret_cast<void*>(current_region), reinterpret_cast<void*>(art_method), false, false); } } else if (api_level >= 29) { ret = ((JIT_COMPILE_METHOD2) jit_compile_method_)(jit_compiler_handle_, reinterpret_cast<void *>(art_method), reinterpret_cast<void *>(self), false, false); } else { ret = ((JIT_COMPILE_METHOD1) jit_compile_method_)(jit_compiler_handle_, reinterpret_cast<void *>(art_method), reinterpret_cast<void *>(self), false); } return (jboolean)ret; } jlong epic_suspendAll(JNIEnv *, jclass) { ScopedSuspendAll *scopedSuspendAll = (ScopedSuspendAll *) malloc(sizeof(ScopedSuspendAll)); suspendAll(scopedSuspendAll, "stop_jit"); return reinterpret_cast<jlong >(scopedSuspendAll); } void epic_resumeAll(JNIEnv* env, jclass, jlong obj) { ScopedSuspendAll* scopedSuspendAll = reinterpret_cast<ScopedSuspendAll*>(obj); resumeAll(scopedSuspendAll); } jlong epic_stopJit(JNIEnv*, jclass) { ScopedJitSuspend *scopedJitSuspend = (ScopedJitSuspend *) malloc(sizeof(ScopedJitSuspend)); stopJit(scopedJitSuspend); return reinterpret_cast<jlong >(scopedJitSuspend); } void epic_startJit(JNIEnv*, jclass, jlong obj) { ScopedJitSuspend *scopedJitSuspend = reinterpret_cast<ScopedJitSuspend *>(obj); startJit(scopedJitSuspend); } void epic_disableMovingGc(JNIEnv* env, jclass ,jint api) { void *heap = ArtHelper::getHeap(); DisableMovingGc(heap); } jboolean epic_munprotect(JNIEnv *env, jclass, jlong addr, jlong len) { long pagesize = sysconf(_SC_PAGESIZE); unsigned alignment = (unsigned)((unsigned long long)addr % pagesize); LOGV("munprotect page size: %d, alignment: %d", pagesize, alignment); int i = mprotect((void *) (addr - alignment), (size_t) (alignment + len), PROT_READ | PROT_WRITE | PROT_EXEC); if (i == -1) { LOGV("mprotect failed: %s (%d)", strerror(errno), errno); return JNI_FALSE; } return JNI_TRUE; } jboolean epic_cacheflush(JNIEnv *env, jclass, jlong addr, jlong len) { #if defined(__arm__) int i = cacheflush(addr, addr + len, 0); LOGV("arm cacheflush for, %ul", addr); if (i == -1) { LOGV("cache flush failed: %s (%d)", strerror(errno), errno); return JNI_FALSE; } #elif defined(__aarch64__) char* begin = reinterpret_cast<char*>(addr); __builtin___clear_cache(begin, begin + len); LOGV("aarch64 __builtin___clear_cache, %p", (void*)begin); #endif return JNI_TRUE; } void epic_MakeInitializedClassVisibilyInitialized(JNIEnv *env, jclass, jlong self) { if (api_level >= 30 && ClassLinker_MakeInitializedClassesVisiblyInitialized_ && ArtHelper::getClassLinker()) { ClassLinker_MakeInitializedClassesVisiblyInitialized_(ArtHelper::getClassLinker(), reinterpret_cast<void*>(self), true); } } void epic_memcpy(JNIEnv *env, jclass, jlong src, jlong dest, jint length) { char *srcPnt = (char *) src; char *destPnt = (char *) dest; for (int i = 0; i < length; ++i) { destPnt[i] = srcPnt[i]; } } void epic_memput(JNIEnv *env, jclass, jbyteArray src, jlong dest) { jbyte *srcPnt = env->GetByteArrayElements(src, 0); jsize length = env->GetArrayLength(src); unsigned char *destPnt = (unsigned char *) dest; for (int i = 0; i < length; ++i) { // LOGV("put %d with %d", i, *(srcPnt + i)); destPnt[i] = (unsigned char) srcPnt[i]; } env->ReleaseByteArrayElements(src, srcPnt, 0); } jbyteArray epic_memget(JNIEnv *env, jclass, jlong src, jint length) { jbyteArray dest = env->NewByteArray(length); if (dest == NULL) { return NULL; } unsigned char *destPnt = (unsigned char *) env->GetByteArrayElements(dest, 0); unsigned char *srcPnt = (unsigned char *) src; for (int i = 0; i < length; ++i) { destPnt[i] = srcPnt[i]; } env->ReleaseByteArrayElements(dest, (jbyte *) destPnt, 0); return dest; } jlong epic_mmap(JNIEnv *env, jclass, jint length) { void *space = mmap(0, (size_t) length, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (space == MAP_FAILED) { LOGV("mmap failed: %d", errno); return 0; } return (jlong) space; } void epic_munmap(JNIEnv *env, jclass, jlong addr, jint length) { int r = munmap((void *) addr, (size_t) length); if (r == -1) { LOGV("munmap failed: %d", errno); } } jlong epic_malloc(JNIEnv *env, jclass, jint size) { size_t length = sizeof(void *) * size; void *ptr = malloc(length); LOGV("malloc :%d of memory at: %p", (int) length, ptr); return (jlong) ptr; } jobject epic_getobject(JNIEnv *env, jclass clazz, jlong self, jlong address) { JavaVM *vm; env->GetJavaVM(&vm); LOGV("java vm: %p, self: %p, address: %p", vm, (void*) self, (void*) address); jobject object = addWeakGloablReference(vm, (void *) self, (void *) address); jobject new_local_object = env->NewLocalRef(object); env->DeleteWeakGlobalRef(object); return new_local_object; } jlong epic_getMethodAddress(JNIEnv *env, jclass clazz, jobject method) { jlong art_method = (jlong) env->FromReflectedMethod(method); if (art_method % 2 == 1) { art_method = reinterpret_cast<jlong>(JniIdManager_DecodeMethodId_(ArtHelper::getJniIdManager(), art_method)); } return art_method; } jboolean epic_isGetObjectAvaliable(JNIEnv *, jclass) { return (jboolean) (addWeakGloablReference != nullptr); } jboolean epic_activate(JNIEnv* env, jclass jclazz, jlong jumpToAddress, jlong pc, jlong sizeOfDirectJump, jlong sizeOfBridgeJump, jbyteArray code) { // fetch the array, we can not call this when thread suspend(may lead deadlock) jbyte *srcPnt = env->GetByteArrayElements(code, 0); jsize length = env->GetArrayLength(code); jlong cookie = 0; bool isNougat = api_level >= 24; if (isNougat) { // We do thus things: // 1. modify the code mprotect // 2. modify the code // Ideal, this two operation must be atomic. Below N, this is safe, because no one // modify the code except ourselves; // But in Android N, When the jit is working, between our step 1 and step 2, // if we modity the mprotect of the code, and planning to write the code, // the jit thread may modify the mprotect of the code meanwhile // we must suspend all thread to ensure the atomic operation. LOGV("suspend all thread."); cookie = epic_suspendAll(env, jclazz); } jboolean result = epic_munprotect(env, jclazz, jumpToAddress, sizeOfDirectJump); if (result) { unsigned char *destPnt = (unsigned char *) jumpToAddress; for (int i = 0; i < length; ++i) { destPnt[i] = (unsigned char) srcPnt[i]; } jboolean ret = epic_cacheflush(env, jclazz, pc, sizeOfBridgeJump); if (!ret) { LOGV("cache flush failed!!"); } } else { LOGV("Writing hook failed: Unable to unprotect memory at %d", jumpToAddress); } if (cookie != 0) { LOGV("resume all thread."); epic_resumeAll(env, jclazz, cookie); } env->ReleaseByteArrayElements(code, srcPnt, 0); return result; } static JNINativeMethod dexposedMethods[] = { {"mmap", "(I)J", (void *) epic_mmap}, {"munmap", "(JI)Z", (void *) epic_munmap}, {"memcpy", "(JJI)V", (void *) epic_memcpy}, {"memput", "([BJ)V", (void *) epic_memput}, {"memget", "(JI)[B", (void *) epic_memget}, {"munprotect", "(JJ)Z", (void *) epic_munprotect}, {"getMethodAddress", "(Ljava/lang/reflect/Member;)J", (void *) epic_getMethodAddress}, {"cacheflush", "(JJ)Z", (void *) epic_cacheflush}, {"MakeInitializedClassVisibilyInitialized", "(J)V", (void *) epic_MakeInitializedClassVisibilyInitialized}, {"malloc", "(I)J", (void *) epic_malloc}, {"getObjectNative", "(JJ)Ljava/lang/Object;", (void *) epic_getobject}, {"compileMethod", "(Ljava/lang/reflect/Member;J)Z",(void *) epic_compile}, {"suspendAll", "()J", (void *) epic_suspendAll}, {"resumeAll", "(J)V", (void *) epic_resumeAll}, {"stopJit", "()J", (void *) epic_stopJit}, {"startJit", "(J)V", (void *) epic_startJit}, {"disableMovingGc", "(I)V", (void *) epic_disableMovingGc}, {"activateNative", "(JJJJ[B)Z", (void *) epic_activate}, {"isGetObjectAvailable", "()Z", (void *) epic_isGetObjectAvaliable} }; static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *gMethods, int numMethods) { jclass clazz = env->FindClass(className); if (clazz == NULL) { return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { return JNI_FALSE; } return JNI_TRUE; } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; LOGV("JNI_OnLoad"); if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { return -1; } if (!registerNativeMethods(env, JNIHOOK_CLASS, dexposedMethods, sizeof(dexposedMethods) / sizeof(dexposedMethods[0]))) { return -1; } init_entries(env); return JNI_VERSION_1_6; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/cpp/fake_dlfcn.cpp
C++
// Copyright (c) 2016 avs333 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //fork from https://github.com/avs333/Nougat_dlfunctions //do some modify //support all cpu abi such as x86, x86_64 //support filename search if filename is not start with '/' #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <elf.h> #include <dlfcn.h> #include <sys/system_properties.h> #include <android/log.h> #define TAG_NAME "dlfcn_ex" #ifdef LOG_DBG #define log_info(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG_NAME, (const char *) fmt, ##args) #define log_err(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG_NAME, (const char *) fmt, ##args) #define log_dbg log_info #else #define log_dbg(...) #define log_info(fmt, args...) #define log_err(fmt, args...) #endif #ifdef __LP64__ #define Elf_Ehdr Elf64_Ehdr #define Elf_Shdr Elf64_Shdr #define Elf_Sym Elf64_Sym #else #define Elf_Ehdr Elf32_Ehdr #define Elf_Shdr Elf32_Shdr #define Elf_Sym Elf32_Sym #endif struct ctx { void *load_addr; void *dynstr; void *dynsym; int nsyms; off_t bias; }; extern "C" { static int fake_dlclose(void *handle) { if (handle) { struct ctx *ctx = (struct ctx *) handle; if (ctx->dynsym) free(ctx->dynsym); /* we're saving dynsym and dynstr */ if (ctx->dynstr) free(ctx->dynstr); /* from library file just in case */ free(ctx); } return 0; } /* flags are ignored */ static void *fake_dlopen_with_path(const char *libpath, int flags) { FILE *maps; char buff[256]; struct ctx *ctx = 0; off_t load_addr, size; int k, fd = -1, found = 0; char *shoff; Elf_Ehdr *elf = (Elf_Ehdr *) MAP_FAILED; #define fatal(fmt, args...) do { log_err(fmt,##args); goto err_exit; } while(0) maps = fopen("/proc/self/maps", "r"); if (!maps) fatal("failed to open maps"); while (!found && fgets(buff, sizeof(buff), maps)) { if (strstr(buff, libpath) && (strstr(buff, "r-xp") || strstr(buff, "r--p"))) found = 1; } fclose(maps); if (!found) fatal("%s not found in my userspace", libpath); if (sscanf(buff, "%lx", &load_addr) != 1) fatal("failed to read load address for %s", libpath); log_info("%s loaded in Android at 0x%08lx", libpath, load_addr); /* Now, mmap the same library once again */ fd = open(libpath, O_RDONLY); if (fd < 0) fatal("failed to open %s", libpath); size = lseek(fd, 0, SEEK_END); if (size <= 0) fatal("lseek() failed for %s", libpath); elf = (Elf_Ehdr *) mmap(0, size, PROT_READ, MAP_SHARED, fd, 0); close(fd); fd = -1; if (elf == MAP_FAILED) fatal("mmap() failed for %s", libpath); ctx = (struct ctx *) calloc(1, sizeof(struct ctx)); if (!ctx) fatal("no memory for %s", libpath); ctx->load_addr = (void *) load_addr; shoff = ((char *) elf) + elf->e_shoff; for (k = 0; k < elf->e_shnum; k++, shoff += elf->e_shentsize) { Elf_Shdr *sh = (Elf_Shdr *) shoff; log_dbg("%s: k=%d shdr=%p type=%x", __func__, k, sh, sh->sh_type); switch (sh->sh_type) { case SHT_DYNSYM: if (ctx->dynsym) fatal("%s: duplicate DYNSYM sections", libpath); /* .dynsym */ ctx->dynsym = malloc(sh->sh_size); if (!ctx->dynsym) fatal("%s: no memory for .dynsym", libpath); memcpy(ctx->dynsym, ((char *) elf) + sh->sh_offset, sh->sh_size); ctx->nsyms = (sh->sh_size / sizeof(Elf_Sym)); break; case SHT_STRTAB: if (ctx->dynstr) break; /* .dynstr is guaranteed to be the first STRTAB */ ctx->dynstr = malloc(sh->sh_size); if (!ctx->dynstr) fatal("%s: no memory for .dynstr", libpath); memcpy(ctx->dynstr, ((char *) elf) + sh->sh_offset, sh->sh_size); break; case SHT_PROGBITS: if (!ctx->dynstr || !ctx->dynsym) break; /* won't even bother checking against the section name */ ctx->bias = (off_t) sh->sh_addr - (off_t) sh->sh_offset; k = elf->e_shnum; /* exit for */ break; } } munmap(elf, size); elf = 0; if (!ctx->dynstr || !ctx->dynsym) fatal("dynamic sections not found in %s", libpath); #undef fatal log_dbg("%s: ok, dynsym = %p, dynstr = %p", libpath, ctx->dynsym, ctx->dynstr); return ctx; err_exit: if (fd >= 0) close(fd); if (elf != MAP_FAILED) munmap(elf, size); fake_dlclose(ctx); return 0; } #if defined(__LP64__) static const char *const kSystemLibDir = "/system/lib64/"; static const char *const kOdmLibDir = "/odm/lib64/"; static const char *const kVendorLibDir = "/vendor/lib64/"; static const char *const kApexLibDir = "/apex/com.android.runtime/lib64/"; static const char *const kApexArtNsLibDir = "/apex/com.android.art/lib64/"; #else static const char *const kSystemLibDir = "/system/lib/"; static const char *const kOdmLibDir = "/odm/lib/"; static const char *const kVendorLibDir = "/vendor/lib/"; static const char *const kApexLibDir = "/apex/com.android.runtime/lib/"; static const char *const kApexArtNsLibDir = "/apex/com.android.art/lib/"; #endif static void *fake_dlopen(const char *filename, int flags) { if (strlen(filename) > 0 && filename[0] == '/') { return fake_dlopen_with_path(filename, flags); } else { char buf[512] = {0}; void *handle = NULL; //sysmtem strcpy(buf, kSystemLibDir); strcat(buf, filename); handle = fake_dlopen_with_path(buf, flags); if (handle) { return handle; } // apex in ns com.android.runtime memset(buf, 0, sizeof(buf)); strcpy(buf, kApexLibDir); strcat(buf, filename); handle = fake_dlopen_with_path(buf, flags); if (handle) { return handle; } // apex in ns com.android.art memset(buf, 0, sizeof(buf)); strcpy(buf, kApexArtNsLibDir); strcat(buf, filename); handle = fake_dlopen_with_path(buf, flags); if (handle) { return handle; } //odm memset(buf, 0, sizeof(buf)); strcpy(buf, kOdmLibDir); strcat(buf, filename); handle = fake_dlopen_with_path(buf, flags); if (handle) { return handle; } //vendor memset(buf, 0, sizeof(buf)); strcpy(buf, kVendorLibDir); strcat(buf, filename); handle = fake_dlopen_with_path(buf, flags); if (handle) { return handle; } return fake_dlopen_with_path(filename, flags); } } static void *fake_dlsym(void *handle, const char *name) { int k; struct ctx *ctx = (struct ctx *) handle; Elf_Sym *sym = (Elf_Sym *) ctx->dynsym; char *strings = (char *) ctx->dynstr; for (k = 0; k < ctx->nsyms; k++, sym++) if (strcmp(strings + sym->st_name, name) == 0) { /* NB: sym->st_value is an offset into the section for relocatables, but a VMA for shared libs or exe files, so we have to subtract the bias */ void *ret = (char *) ctx->load_addr + sym->st_value - ctx->bias; log_info("%s found at %p", name, ret); return ret; } return 0; } static const char *fake_dlerror() { return NULL; } // =============== implementation for compat ========== static int SDK_INT = -1; static int get_sdk_level() { if (SDK_INT > 0) { return SDK_INT; } char sdk[PROP_VALUE_MAX] = {0};; __system_property_get("ro.build.version.sdk", sdk); SDK_INT = atoi(sdk); return SDK_INT; } int dlclose_ex(void *handle) { if (get_sdk_level() >= 24) { return fake_dlclose(handle); } else { return dlclose(handle); } } void *dlopen_ex(const char *filename, int flags) { log_info("dlopen: %s", filename); if (get_sdk_level() >= 24) { return fake_dlopen(filename, flags); } else { return dlopen(filename, flags); } } void *dlsym_ex(void *handle, const char *symbol) { if (get_sdk_level() >= 24) { return fake_dlsym(handle, symbol); } else { return dlsym(handle, symbol); } } const char *dlerror_ex() { if (get_sdk_level() >= 24) { return fake_dlerror(); } else { return dlerror(); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/cpp/fake_dlfcn.h
C/C++ Header
// Copyright (c) 2016 avs333 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef DEXPOSED_DLFCN_H #define DEXPOSED_DLFCN_H #include <cstdlib> #include <string.h> #include <unistd.h> extern "C" { void *dlopen_ex(const char *filename, int flags); void *dlsym_ex(void *handle, const char *symbol); int dlclose_ex(void *handle); const char *dlerror_ex(); }; #endif //DEXPOSED_DLFCN_H
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/ClassUtils.java
Java
/* * Original work Copyright (c) 2005-2008, The Android Open Source Project * Modified work Copyright (c) 2013, rovo89 and Tungstwenty * Modified work Copyright (c) 2015, Alibaba Mobile Infrastructure (Android) Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; /** * <p>Operates on classes without using reflection.</p> * * <p>This class handles invalid {@code null} inputs as best it can. * Each method documents its behaviour in more detail.</p> * * <p>The notion of a {@code canonical name} includes the human * readable name for the type, for example {@code int[]}. The * non-canonical method variants work with the JVM names, such as * {@code [I}. </p> * * @since 2.0 * @version $Id: ClassUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ */ public class ClassUtils { /** * <p>The package separator character: <code>'&#x2e;' == {@value}</code>.</p> */ public static final char PACKAGE_SEPARATOR_CHAR = '.'; /** * <p>The package separator String: {@code "&#x2e;"}.</p> */ public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR); /** * <p>The inner class separator character: <code>'$' == {@value}</code>.</p> */ public static final char INNER_CLASS_SEPARATOR_CHAR = '$'; /** * <p>The inner class separator String: {@code "$"}.</p> */ public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR); /** * <p>Empty string.</p> */ public static final String STRING_EMPTY = ""; /** * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}. */ private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>(); static { primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); primitiveWrapperMap.put(Byte.TYPE, Byte.class); primitiveWrapperMap.put(Character.TYPE, Character.class); primitiveWrapperMap.put(Short.TYPE, Short.class); primitiveWrapperMap.put(Integer.TYPE, Integer.class); primitiveWrapperMap.put(Long.TYPE, Long.class); primitiveWrapperMap.put(Double.TYPE, Double.class); primitiveWrapperMap.put(Float.TYPE, Float.class); primitiveWrapperMap.put(Void.TYPE, Void.TYPE); } /** * Maps wrapper {@code Class}es to their corresponding primitive types. */ private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>(); static { for (Class<?> primitiveClass : primitiveWrapperMap.keySet()) { Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass); if (!primitiveClass.equals(wrapperClass)) { wrapperPrimitiveMap.put(wrapperClass, primitiveClass); } } } /** * Maps a primitive class name to its corresponding abbreviation used in array class names. */ private static final Map<String, String> abbreviationMap = new HashMap<String, String>(); /** * Maps an abbreviation used in array class names to corresponding primitive class name. */ private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>(); /** * Add primitive type abbreviation to maps of abbreviations. * * @param primitive Canonical name of primitive type * @param abbreviation Corresponding abbreviation of primitive type */ private static void addAbbreviation(String primitive, String abbreviation) { abbreviationMap.put(primitive, abbreviation); reverseAbbreviationMap.put(abbreviation, primitive); } /** * Feed abbreviation maps */ static { addAbbreviation("int", "I"); addAbbreviation("boolean", "Z"); addAbbreviation("float", "F"); addAbbreviation("long", "J"); addAbbreviation("short", "S"); addAbbreviation("byte", "B"); addAbbreviation("double", "D"); addAbbreviation("char", "C"); } /** * <p>ClassUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as * {@code ClassUtils.getShortClassName(cls)}.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public ClassUtils() { super(); } // Short class name // ---------------------------------------------------------------------- /** * <p>Gets the class name minus the package name for an {@code Object}.</p> * * @param object the class to get the short name for, may be null * @param valueIfNull the value to return if null * @return the class name of the object without the package name, or the null value */ public static String getShortClassName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getShortClassName(object.getClass()); } /** * <p>Gets the class name minus the package name from a {@code Class}.</p> * * <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead. * The one known difference is that this code will return {@code "Map.Entry"} while * the {@code java.lang.Class} variant will simply return {@code "Entry"}. </p> * * @param cls the class to get the short name for. * @return the class name without the package name or an empty string */ public static String getShortClassName(Class<?> cls) { if (cls == null) { return ""; } return getShortClassName(cls.getName()); } /** * <p>Gets the class name minus the package name from a String.</p> * * <p>The string passed in is assumed to be a class name - it is not checked.</p> * <p>Note that this method differs from Class.getSimpleName() in that this will * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply * return {@code "Entry"}. </p> * * @param className the className to get the short name for * @return the class name of the class without the package name or an empty string */ public static String getShortClassName(String className) { if (className == null) { return STRING_EMPTY; } if (className.length() == 0) { return STRING_EMPTY; } StringBuilder arrayPrefix = new StringBuilder(); // Handle array encoding if (className.startsWith("[")) { while (className.charAt(0) == '[') { className = className.substring(1); arrayPrefix.append("[]"); } // Strip Object type encoding if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { className = className.substring(1, className.length() - 1); } } if (reverseAbbreviationMap.containsKey(className)) { className = reverseAbbreviationMap.get(className); } int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); int innerIdx = className.indexOf( INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1); String out = className.substring(lastDotIdx + 1); if (innerIdx != -1) { out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR); } return out + arrayPrefix; } /** * <p>Null-safe version of <code>aClass.getSimpleName()</code></p> * * @param cls the class for which to get the simple name. * @return the simple class name. * @since 3.0 * @see Class#getSimpleName() */ public static String getSimpleName(Class<?> cls) { if (cls == null) { return STRING_EMPTY; } return cls.getSimpleName(); } /** * <p>Null-safe version of <code>aClass.getSimpleName()</code></p> * * @param object the object for which to get the simple class name. * @param valueIfNull the value to return if <code>object</code> is <code>null</code> * @return the simple class name. * @since 3.0 * @see Class#getSimpleName() */ public static String getSimpleName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getSimpleName(object.getClass()); } // Package name // ---------------------------------------------------------------------- /** * <p>Gets the package name of an {@code Object}.</p> * * @param object the class to get the package name for, may be null * @param valueIfNull the value to return if null * @return the package name of the object, or the null value */ public static String getPackageName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getPackageName(object.getClass()); } /** * <p>Gets the package name of a {@code Class}.</p> * * @param cls the class to get the package name for, may be {@code null}. * @return the package name or an empty string */ public static String getPackageName(Class<?> cls) { if (cls == null) { return STRING_EMPTY; } return getPackageName(cls.getName()); } /** * <p>Gets the package name from a {@code String}.</p> * * <p>The string passed in is assumed to be a class name - it is not checked.</p> * <p>If the class is unpackaged, return an empty string.</p> * * @param className the className to get the package name for, may be {@code null} * @return the package name or an empty string */ public static String getPackageName(String className) { if (className == null || className.length() == 0) { return STRING_EMPTY; } // Strip array encoding while (className.charAt(0) == '[') { className = className.substring(1); } // Strip Object type encoding if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { className = className.substring(1); } int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (i == -1) { return STRING_EMPTY; } return className.substring(0, i); } // Superclasses/Superinterfaces // ---------------------------------------------------------------------- /** * <p>Gets a {@code List} of superclasses for the given class.</p> * * @param cls the class to look up, may be {@code null} * @return the {@code List} of superclasses in order going up from this one * {@code null} if null input */ public static List<Class<?>> getAllSuperclasses(Class<?> cls) { if (cls == null) { return null; } List<Class<?>> classes = new ArrayList<Class<?>>(); Class<?> superclass = cls.getSuperclass(); while (superclass != null) { classes.add(superclass); superclass = superclass.getSuperclass(); } return classes; } /** * <p>Gets a {@code List} of all interfaces implemented by the given * class and its superclasses.</p> * * <p>The order is determined by looking through each interface in turn as * declared in the source file and following its hierarchy up. Then each * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.</p> * * @param cls the class to look up, may be {@code null} * @return the {@code List} of interfaces in order, * {@code null} if null input */ public static List<Class<?>> getAllInterfaces(Class<?> cls) { if (cls == null) { return null; } LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>(); getAllInterfaces(cls, interfacesFound); return new ArrayList<Class<?>>(interfacesFound); } /** * Get the interfaces for the specified class. * * @param cls the class to look up, may be {@code null} * @param interfacesFound the {@code Set} of interfaces for the class */ private static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) { while (cls != null) { Class<?>[] interfaces = cls.getInterfaces(); for (Class<?> i : interfaces) { if (interfacesFound.add(i)) { getAllInterfaces(i, interfacesFound); } } cls = cls.getSuperclass(); } } // Convert list // ---------------------------------------------------------------------- /** * <p>Given a {@code List} of class names, this method converts them into classes.</p> * * <p>A new {@code List} is returned. If the class name cannot be found, {@code null} * is stored in the {@code List}. If the class name in the {@code List} is * {@code null}, {@code null} is stored in the output {@code List}.</p> * * @param classNames the classNames to change * @return a {@code List} of Class objects corresponding to the class names, * {@code null} if null input * @throws ClassCastException if classNames contains a non String entry */ public static List<Class<?>> convertClassNamesToClasses(List<String> classNames) { if (classNames == null) { return null; } List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size()); for (String className : classNames) { try { classes.add(Class.forName(className)); } catch (Exception ex) { classes.add(null); } } return classes; } /** * <p>Given a {@code List} of {@code Class} objects, this method converts * them into class names.</p> * * <p>A new {@code List} is returned. {@code null} objects will be copied into * the returned list as {@code null}.</p> * * @param classes the classes to change * @return a {@code List} of class names corresponding to the Class objects, * {@code null} if null input * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry */ public static List<String> convertClassesToClassNames(List<Class<?>> classes) { if (classes == null) { return null; } List<String> classNames = new ArrayList<String>(classes.size()); for (Class<?> cls : classes) { if (cls == null) { classNames.add(null); } else { classNames.add(cls.getName()); } } return classNames; } // Class loading // ---------------------------------------------------------------------- /** * Returns the class represented by {@code className} using the * {@code classLoader}. This implementation supports the syntaxes * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}". * * @param classLoader the class loader to use to load the class * @param className the class name * @param initialize whether the class must be initialized * @return the class represented by {@code className} using the {@code classLoader} * @throws ClassNotFoundException if the class is not found */ public static Class<?> getClass( ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException { try { Class<?> clazz; if (abbreviationMap.containsKey(className)) { String clsName = "[" + abbreviationMap.get(className); clazz = Class.forName(clsName, initialize, classLoader).getComponentType(); } else { clazz = Class.forName(toCanonicalName(className), initialize, classLoader); } return clazz; } catch (ClassNotFoundException ex) { // allow path separators (.) as inner class name separators int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (lastDotIndex != -1) { try { return getClass(classLoader, className.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1), initialize); } catch (ClassNotFoundException ex2) { // NOPMD // ignore exception } } throw ex; } } /** * Returns the (initialized) class represented by {@code className} * using the {@code classLoader}. This implementation supports * the syntaxes "{@code java.util.Map.Entry[]}", * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", * and "{@code [Ljava.util.Map$Entry;}". * * @param classLoader the class loader to use to load the class * @param className the class name * @return the class represented by {@code className} using the {@code classLoader} * @throws ClassNotFoundException if the class is not found */ public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException { return getClass(classLoader, className, true); } /** * Returns the (initialized) class represented by {@code className} * using the current thread's context class loader. This implementation * supports the syntaxes "{@code java.util.Map.Entry[]}", * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", * and "{@code [Ljava.util.Map$Entry;}". * * @param className the class name * @return the class represented by {@code className} using the current thread's context class loader * @throws ClassNotFoundException if the class is not found */ public static Class<?> getClass(String className) throws ClassNotFoundException { return getClass(className, true); } /** * Returns the class represented by {@code className} using the * current thread's context class loader. This implementation supports the * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}". * * @param className the class name * @param initialize whether the class must be initialized * @return the class represented by {@code className} using the current thread's context class loader * @throws ClassNotFoundException if the class is not found */ public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException { ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL; return getClass(loader, className, initialize); } // ---------------------------------------------------------------------- /** * Converts a class name to a JLS style class name. * * @param className the class name * @return the converted name */ private static String toCanonicalName(String className) { className = deleteWhitespace(className); if (className == null) { throw new NullPointerException("className must not be null."); } else if (className.endsWith("[]")) { StringBuilder classNameBuffer = new StringBuilder(); while (className.endsWith("[]")) { className = className.substring(0, className.length() - 2); classNameBuffer.append("["); } String abbreviation = abbreviationMap.get(className); if (abbreviation != null) { classNameBuffer.append(abbreviation); } else { classNameBuffer.append("L").append(className).append(";"); } className = classNameBuffer.toString(); } return className; } /** * <p>Converts an array of {@code Object} in to an array of {@code Class} objects. * If any of these objects is null, a null element will be inserted into the array.</p> * * <p>This method returns {@code null} for a {@code null} input array.</p> * * @param array an {@code Object} array * @return a {@code Class} array, {@code null} if null array input * @since 2.4 */ public static Class<?>[] toClass(Object... array) { if (array == null) { return null; } else if (array.length == 0) { return new Class[0]; } Class<?>[] classes = new Class[array.length]; for (int i = 0; i < array.length; i++) { classes[i] = array[i] == null ? null : array[i].getClass(); } return classes; } // Delete //----------------------------------------------------------------------- /** * <p>Deletes all whitespaces from a String as defined by * {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.deleteWhitespace(null) = null * StringUtils.deleteWhitespace("") = "" * StringUtils.deleteWhitespace("abc") = "abc" * StringUtils.deleteWhitespace(" ab c ") = "abc" * </pre> * * @param str the String to delete whitespace from, may be null * @return the String without whitespaces, {@code null} if null String input */ public static String deleteWhitespace(String str) { if (isEmpty(str)) { return str; } int sz = str.length(); char[] chs = new char[sz]; int count = 0; for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { chs[count++] = str.charAt(i); } } if (count == sz) { return str; } return new String(chs, 0, count); } // Empty checks //----------------------------------------------------------------------- /** * <p>Checks if a CharSequence is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/DeviceCheck.java
Java
/* * Original work Copyright (c) 2005-2008, The Android Open Source Project * Modified work Copyright (c) 2013, rovo89 and Tungstwenty * Modified work Copyright (c) 2015, Alibaba Mobile Infrastructure (Android) Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class DeviceCheck { private static final String SELECT_RUNTIME_PROPERTY = "persist.sys.dalvik.vm.lib"; private static final String LIB_DALVIK = "libdvm.so"; private static final String LIB_ART = "libart.so"; private static final String LIB_ART_D = "libartd.so"; private static boolean isCheckedDeviceSupport = false; private static boolean isDeviceSupportable = false; private static boolean isDalvikMode() { String vmMode = getCurrentRuntimeValue(); if("Dalvik".equals(vmMode)){ return true; } return false; } private static String getCurrentRuntimeValue() { try { Class<?> systemProperties = Class .forName("android.os.SystemProperties"); try { Method get = systemProperties.getMethod("get", String.class, String.class); if (get == null) { return "WTF?!"; } try { final String value = (String) get.invoke(systemProperties, SELECT_RUNTIME_PROPERTY, /* Assuming default is */"Dalvik"); if (LIB_DALVIK.equals(value)) { return "Dalvik"; } else if (LIB_ART.equals(value)) { return "ART"; } else if (LIB_ART_D.equals(value)) { return "ART debug build"; } return value; } catch (IllegalAccessException e) { return "IllegalAccessException"; } catch (IllegalArgumentException e) { return "IllegalArgumentException"; } catch (InvocationTargetException e) { return "InvocationTargetException"; } } catch (NoSuchMethodException e) { return "SystemProperties.get(String key, String def) method is not found"; } } catch (ClassNotFoundException e) { return "SystemProperties class is not found"; } } private static boolean isSupportSDKVersion() { if (android.os.Build.VERSION.SDK_INT >= 14 && android.os.Build.VERSION.SDK_INT < 20) { return true; } else if(android.os.Build.VERSION.SDK_INT == 10 || android.os.Build.VERSION.SDK_INT == 9){ return true; } return false; } private static boolean isX86CPU() { Process process = null; String abi = null; InputStreamReader ir = null; BufferedReader input = null; try { process = Runtime.getRuntime().exec("getprop ro.product.cpu.abi"); ir = new InputStreamReader(process.getInputStream()); input = new BufferedReader(ir); abi = input.readLine(); if (abi.contains("x86")) { return true; } } catch (Exception e) { } finally { if (input != null) { try { input.close(); } catch (Exception e) { } } if (ir != null) { try { ir.close(); } catch (Exception e) { } } if (process != null) { try { process.destroy(); } catch (Exception e) { } } } return false; } public static synchronized boolean isDeviceSupport(Context context) { // return memory checked value. try { if (isCheckedDeviceSupport) return isDeviceSupportable; if (!isX86CPU() && !isYunOS()) { isDeviceSupportable = true; } else { isDeviceSupportable = false; } } finally { Log.d("hotpatch", "device support is " + isDeviceSupportable + "checked" + isCheckedDeviceSupport); isCheckedDeviceSupport = true; } return isDeviceSupportable; } @SuppressLint("DefaultLocale") public static boolean isYunOS() { String s1 = null; String s2 = null; try { Method m = Class.forName("android.os.SystemProperties").getMethod( "get", String.class); s1 = (String) m.invoke(null, "ro.yunos.version"); s2 = (String) m.invoke(null, "java.vm.name"); } catch (NoSuchMethodException a) { } catch (ClassNotFoundException b) { } catch (IllegalAccessException c) { } catch (InvocationTargetException d) { } if ((s2 != null && s2.toLowerCase().contains("lemur")) || (s1 != null && s1.trim().length() > 0)) { return true; } else { return false; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/Debug.java
Java
/* * Original work Copyright (c) 2014-2015, Marvin Wißfeld * Modified work Copyright (c) 2016, Alibaba Mobile Infrastructure (Android) Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed.utility; import android.util.Log; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import me.weishu.epic.BuildConfig; import me.weishu.epic.art.method.ArtMethod; public final class Debug { private static final String TAG = "Dexposed"; public static final boolean DEBUG = BuildConfig.DEBUG; private static final String RELASE_WRAN_STRING = "none in release mode."; private Debug() { } public static String addrHex(long i) { if (!DEBUG) { return RELASE_WRAN_STRING; } if (Runtime.is64Bit()) { return longHex(i); } else { return intHex((int) i); } } public static String longHex(long i) { return String.format("0x%016X", i); } public static String intHex(int i) { return String.format("0x%08X", i); } public static String byteHex(byte b) { return String.format("%02X", b); } public static String dump(byte[] b, long start) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { if (i % 8 == 0) { sb.append(addrHex(start + i)).append(":"); } sb.append(byteHex(b[i])).append(" "); if (i % 8 == 7) { sb.append("\n"); } } return sb.toString(); } public static String hexdump(byte[] bytes, long start) { if (!DEBUG) { return RELASE_WRAN_STRING; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { if (i % 8 == 0) { sb.append(addrHex(start + i)).append(":"); } sb.append(byteHex(bytes[i])).append(" "); if (i % 8 == 7) { sb.append("\n"); } } return sb.toString(); } public static String methodDescription(Method method) { return method.getDeclaringClass().getName() + "->" + method.getName() + " @" + addrHex(ArtMethod.of(method).getEntryPointFromQuickCompiledCode()) + " +" + addrHex(ArtMethod.of(method).getAddress()); } public static void dumpMaps() { BufferedReader br = null; try { br = new BufferedReader(new FileReader("/proc/self/maps")); String line; while ((line = br.readLine()) != null) { Log.i(TAG, line); } } catch (IOException e) { Log.e(TAG, "dumpMaps error"); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore. } } } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/Logger.java
Java
package com.taobao.android.dexposed.utility; import android.util.Log; /** * Created by weishu on 17/11/10. */ public class Logger { private static final boolean DEBUG = Debug.DEBUG; public static final String preFix = "epic."; public static void i(String tag, String msg) { if (DEBUG) { Log.i(preFix + tag, msg); } } public static void d(String tagSuffix, String msg) { if (DEBUG) { Log.d(preFix + tagSuffix, msg); } } public static void w(String tag, String msg) { Log.w(preFix + tag, msg); } public static void e(String tag, String msg) { if (DEBUG) { Log.e(preFix + tag, msg); } } public static void e(String tag, String msg, Throwable e) { if (DEBUG) { Log.e(preFix + tag, msg, e); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/NeverCalled.java
Java
package com.taobao.android.dexposed.utility; import android.util.Log; /** * This Class is used for get the art_quick_to_interpreter_bridge address * Do not call this forever!!! */ public class NeverCalled { private void fake(int a) { Log.i(getClass().getSimpleName(), a + "Do not inline me!!"); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/NougatPolicy.java
Java
package com.taobao.android.dexposed.utility; import android.content.Context; import android.os.SystemClock; import android.util.Log; import java.lang.reflect.Method; public class NougatPolicy { private static class TraceLogger { static void i(String tag, String msg) { Log.i(tag, msg); } static void e(String tag, String msg) { Log.i(tag, msg); } static void e(String tag, String msg, Throwable e) { Log.i(tag, msg, e); } } private static final String TAG = "NougatPolicy"; public static boolean fullCompile(Context context) { try { long t1 = SystemClock.elapsedRealtime(); Object pm = getPackageManagerBinderProxy(); if (pm == null) { TraceLogger.e(TAG, "can not found package service"); return false; } /* @Override public boolean performDexOptMode(String packageName, boolean checkProfiles, String targetCompilerFilter, boolean force) { int dexOptStatus = performDexOptTraced(packageName, checkProfiles, targetCompilerFilter, force); return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; */ final Method performDexOptMode = pm.getClass().getDeclaredMethod("performDexOptMode", String.class, boolean.class, String.class, boolean.class); boolean ret = (boolean) performDexOptMode.invoke(pm, context.getPackageName(), false, "speed", true); long cost = SystemClock.elapsedRealtime() - t1; Log.i(TAG, "full Compile cost: " + cost + " result:" + ret); return ret; } catch (Throwable e) { TraceLogger.e(TAG, "fullCompile failed:", e); return false; } } public static boolean clearCompileData(Context context) { boolean ret; try { Object pm = getPackageManagerBinderProxy(); final Method performDexOpt = pm.getClass().getDeclaredMethod("performDexOpt", String.class, boolean.class, int.class, boolean.class); ret = (Boolean) performDexOpt.invoke(pm, context.getPackageName(), false, 2 /*install*/, true); } catch (Throwable e) { TraceLogger.e(TAG, "clear compile data failed", e); ret = false; } return ret; } private static Object getPackageManagerBinderProxy() throws Exception { Class<?> activityThread = Class.forName("android.app.ActivityThread"); final Method getPackageManager = activityThread.getDeclaredMethod("getPackageManager"); return getPackageManager.invoke(null); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/Platform.java
Java
/* * Original work Copyright (c) 2016, Lody * Modified work Copyright (c) 2016, Alibaba Mobile Infrastructure (Android) Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed.utility; import java.nio.ByteBuffer; import java.nio.ByteOrder; public abstract class Platform { /*package*/ static Platform PLATFORM_INTERNAL; static { if (Runtime.is64Bit()) { PLATFORM_INTERNAL = new Platform64Bit(); }else { PLATFORM_INTERNAL = new Platform32Bit(); } } public static Platform getPlatform() { return PLATFORM_INTERNAL; } /** * Convert a byte array to int, * Use this function to get address from memory. * * @param data byte array * @return long */ public abstract int orderByteToInt(byte[] data); /** * Convert a byte array to long, * Use this function to get address from memory. * * @param data byte array * @return long */ public abstract long orderByteToLong(byte[] data); public abstract byte[] orderLongToByte(long serial, int length); public abstract byte[] orderIntToByte(int serial); public abstract int getIntSize(); static class Platform32Bit extends Platform { @Override public int orderByteToInt(byte[] data) { return ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getInt(); } @Override public long orderByteToLong(byte[] data) { return ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL; } @Override public byte[] orderLongToByte(long serial, int length) { return ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN).putInt((int) serial).array(); } @Override public byte[] orderIntToByte(int serial) { return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(serial).array(); } @Override public int getIntSize() { return 4; } } static class Platform64Bit extends Platform { @Override public int orderByteToInt(byte[] data) { return ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getInt(); } @Override public long orderByteToLong(byte[] data) { return ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getLong(); } @Override public byte[] orderLongToByte(long serial, int length) { return ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN).putLong(serial).array(); } @Override public byte[] orderIntToByte(int serial) { return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(serial).array(); } @Override public int getIntSize() { return 8; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/Runtime.java
Java
/* * Original work Copyright (c) 2016, Lody * Modified work Copyright (c) 2016, Alibaba Mobile Infrastructure (Android) Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed.utility; import android.util.Log; import java.lang.reflect.Method; import me.weishu.epic.art.method.ArtMethod; public class Runtime { private static final String TAG = "Runtime"; private volatile static Boolean isThumb = null; private volatile static boolean g64 = false; private volatile static boolean isArt = true; static { try { g64 = (boolean) Class.forName("dalvik.system.VMRuntime").getDeclaredMethod("is64Bit").invoke(Class.forName("dalvik.system.VMRuntime").getDeclaredMethod("getRuntime").invoke(null)); } catch (Exception e) { Log.e(TAG, "get is64Bit failed, default not 64bit!", e); g64 = false; } isArt = System.getProperty("java.vm.version").startsWith("2"); Log.i(TAG, "is64Bit: " + g64 + ", isArt: " + isArt); } public static boolean is64Bit() { return g64; } public static boolean isArt() { return isArt; } public static boolean isThumb2() { if (isThumb != null) { return isThumb; } try { Method method = String.class.getDeclaredMethod("hashCode"); ArtMethod artMethodStruct = ArtMethod.of(method); long entryPointFromQuickCompiledCode = artMethodStruct.getEntryPointFromQuickCompiledCode(); Logger.w("Runtime", "isThumb2, entry: " + Long.toHexString(entryPointFromQuickCompiledCode)); isThumb = ((entryPointFromQuickCompiledCode & 1) == 1); return isThumb; } catch (Throwable e) { Logger.w("Runtime", "isThumb2, error: " + e); return true; // Default Thumb2. } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/com/taobao/android/dexposed/utility/Unsafe.java
Java
/* * Copyright 2014-2015 Marvin Wißfeld * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.android.dexposed.utility; import android.util.Log; import java.lang.reflect.Field; public final class Unsafe { private static final String TAG = "Unsafe"; private static Object unsafe; private static Class unsafeClass; static { try { unsafeClass = Class.forName("sun.misc.Unsafe"); Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); unsafe = theUnsafe.get(null); } catch (Exception e) { try { final Field theUnsafe = unsafeClass.getDeclaredField("THE_ONE"); theUnsafe.setAccessible(true); unsafe = theUnsafe.get(null); } catch (Exception e2) { Log.w(TAG, "Unsafe not found o.O"); } } } private Unsafe() { } @SuppressWarnings("unchecked") public static int arrayBaseOffset(Class cls) { try { return (int) unsafeClass.getDeclaredMethod("arrayBaseOffset", Class.class).invoke(unsafe, cls); } catch (Exception e) { Log.w(TAG, e); return 0; } } @SuppressWarnings("unchecked") public static int arrayIndexScale(Class cls) { try { return (int) unsafeClass.getDeclaredMethod("arrayIndexScale", Class.class).invoke(unsafe, cls); } catch (Exception e) { Log.w(TAG, e); return 0; } } @SuppressWarnings("unchecked") public static long objectFieldOffset(Field field) { try { return (long) unsafeClass.getDeclaredMethod("objectFieldOffset", Field.class).invoke(unsafe, field); } catch (Exception e) { Log.w(TAG, e); return 0; } } @SuppressWarnings("unchecked") public static int getInt(Object array, long offset) { try { return (int) unsafeClass.getDeclaredMethod("getInt", Object.class, long.class).invoke(unsafe, array, offset); } catch (Exception e) { Log.w(TAG, e); return 0; } } @SuppressWarnings("unchecked") public static long getLong(Object array, long offset) { try { return (long) unsafeClass.getDeclaredMethod("getLong", Object.class, long.class).invoke(unsafe, array, offset); } catch (Exception e) { Log.w(TAG, e); return 0; } } @SuppressWarnings("unchecked") public static void putLong(Object array, long offset, long value) { try { unsafeClass.getDeclaredMethod("putLongVolatile", Object.class, long.class, long.class).invoke(unsafe, array, offset, value); } catch (Exception e) { try { unsafeClass.getDeclaredMethod("putLong", Object.class, long.class, long.class).invoke(unsafe, array, offset, value); } catch (Exception e1) { Log.w(TAG, e); } } } @SuppressWarnings("unchecked") public static void putInt(Object array, long offset, int value) { try { unsafeClass.getDeclaredMethod("putIntVolatile", Object.class, long.class, int.class).invoke(unsafe, array, offset, value); } catch (Exception e) { try { unsafeClass.getDeclaredMethod("putIntVolatile", Object.class, long.class, int.class).invoke(unsafe, array, offset, value); } catch (Exception e1) { Log.w(TAG, e); } } } public static long getObjectAddress(Object obj) { try { Object[] array = new Object[]{obj}; if (arrayIndexScale(Object[].class) == 8) { return getLong(array, arrayBaseOffset(Object[].class)); } else { return 0xffffffffL & getInt(array, arrayBaseOffset(Object[].class)); } } catch (Exception e) { Log.w(TAG, e); return -1; } } /** * get Object from address, refer: http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ * @param address the address of a object. * @return */ public static Object getObject(long address) { Object[] array = new Object[]{null}; long baseOffset = arrayBaseOffset(Object[].class); if (Runtime.is64Bit()) { putLong(array, baseOffset, address); } else { putInt(array, baseOffset, (int) address); } return array[0]; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/de/robv/android/xposed/DexposedBridge.java
Java
/* * Original work Copyright (c) 2005-2008, The Android Open Source Project * Modified work Copyright (c) 2013, rovo89 and Tungstwenty * Modified work Copyright (c) 2015, Alibaba Mobile Infrastructure (Android) Team * Modified work Copyright (c) 2017, weishu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.robv.android.xposed; import android.app.AndroidAppHelper; import android.os.Build; import android.util.Log; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.Runtime; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import me.weishu.epic.art.Epic; import me.weishu.epic.art.method.ArtMethod; import me.weishu.reflection.Reflection; import static de.robv.android.xposed.XposedHelpers.getIntField; public final class DexposedBridge { static { try { if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { System.loadLibrary("epic"); } else if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH){ System.loadLibrary("dexposed"); } else { throw new RuntimeException("unsupported api level: " + Build.VERSION.SDK_INT); } Reflection.unseal(AndroidAppHelper.currentApplication()); } catch (Throwable e) { log(e); } } private static final String TAG = "DexposedBridge"; private static final Object[] EMPTY_ARRAY = new Object[0]; public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader(); // built-in handlers private static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> hookedMethodCallbacks = new HashMap<Member, CopyOnWriteSortedSet<XC_MethodHook>>(); private static final ArrayList<XC_MethodHook.Unhook> allUnhookCallbacks = new ArrayList<XC_MethodHook.Unhook>(); /** * Writes a message to BASE_DIR/log/debug.log (needs to have chmod 777) * @param text log message */ public synchronized static void log(String text) { Log.i(TAG, text); } /** * Log the stack trace * @param t The Throwable object for the stacktrace * @see DexposedBridge#log(String) */ public synchronized static void log(Throwable t) { log(Log.getStackTraceString(t)); } /** * Hook any method with the specified callback * * @param hookMethod The method to be hooked * @param callback */ public static XC_MethodHook.Unhook hookMethod(Member hookMethod, XC_MethodHook callback) { if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) { throw new IllegalArgumentException("only methods and constructors can be hooked"); } boolean newMethod = false; CopyOnWriteSortedSet<XC_MethodHook> callbacks; synchronized (hookedMethodCallbacks) { callbacks = hookedMethodCallbacks.get(hookMethod); if (callbacks == null) { callbacks = new CopyOnWriteSortedSet<XC_MethodHook>(); hookedMethodCallbacks.put(hookMethod, callbacks); newMethod = true; } } Logger.w(TAG, "hook: " + hookMethod + ", newMethod ? " + newMethod); callbacks.add(callback); if (newMethod) { if (Runtime.isArt()) { if (hookMethod instanceof Method) { Epic.hookMethod(((Method) hookMethod)); } else { Epic.hookMethod(((Constructor) hookMethod)); } } else { Class<?> declaringClass = hookMethod.getDeclaringClass(); int slot = getIntField(hookMethod, "slot"); Class<?>[] parameterTypes; Class<?> returnType; if (hookMethod instanceof Method) { parameterTypes = ((Method) hookMethod).getParameterTypes(); returnType = ((Method) hookMethod).getReturnType(); } else { parameterTypes = ((Constructor<?>) hookMethod).getParameterTypes(); returnType = null; } AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks, parameterTypes, returnType); hookMethodNative(hookMethod, declaringClass, slot, additionalInfo); } } return callback.new Unhook(hookMethod); } /** * Removes the callback for a hooked method * @param hookMethod The method for which the callback should be removed * @param callback The reference to the callback as specified in {@link #hookMethod} */ public static void unhookMethod(Member hookMethod, XC_MethodHook callback) { CopyOnWriteSortedSet<XC_MethodHook> callbacks; synchronized (hookedMethodCallbacks) { callbacks = hookedMethodCallbacks.get(hookMethod); if (callbacks == null) return; } callbacks.remove(callback); } public static Set<XC_MethodHook.Unhook> hookAllMethods(Class<?> hookClass, String methodName, XC_MethodHook callback) { Set<XC_MethodHook.Unhook> unhooks = new HashSet<XC_MethodHook.Unhook>(); for (Member method : hookClass.getDeclaredMethods()) if (method.getName().equals(methodName)) unhooks.add(hookMethod(method, callback)); return unhooks; } public static XC_MethodHook.Unhook findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) { if (parameterTypesAndCallback.length == 0 || !(parameterTypesAndCallback[parameterTypesAndCallback.length-1] instanceof XC_MethodHook)) throw new IllegalArgumentException("no callback defined"); XC_MethodHook callback = (XC_MethodHook) parameterTypesAndCallback[parameterTypesAndCallback.length-1]; Method m = XposedHelpers.findMethodExact(clazz, methodName, parameterTypesAndCallback); XC_MethodHook.Unhook unhook = hookMethod(m, callback); synchronized (allUnhookCallbacks) { allUnhookCallbacks.add(unhook); } return unhook; } public static void unhookAllMethods() { synchronized (allUnhookCallbacks) { for (int i = 0; i < allUnhookCallbacks.size(); i++) { ((XC_MethodHook.Unhook) allUnhookCallbacks.get(i)).unhook(); } allUnhookCallbacks.clear(); } } public static Set<XC_MethodHook.Unhook> hookAllConstructors(Class<?> hookClass, XC_MethodHook callback) { Set<XC_MethodHook.Unhook> unhooks = new HashSet<XC_MethodHook.Unhook>(); for (Member constructor : hookClass.getDeclaredConstructors()) unhooks.add(hookMethod(constructor, callback)); return unhooks; } public static Object handleHookedArtMethod(Object artMethodObject, Object thisObject, Object[] args) { CopyOnWriteSortedSet<XC_MethodHook> callbacks; ArtMethod artmethod = (ArtMethod ) artMethodObject; synchronized (hookedMethodCallbacks) { callbacks = hookedMethodCallbacks.get(artmethod.getExecutable()); } Object[] callbacksSnapshot = callbacks.getSnapshot(); final int callbacksLength = callbacksSnapshot.length; //Logger.d(TAG, "callbacksLength:" + callbacksLength + ", this:" + thisObject + ", args:" + Arrays.toString(args)); if (callbacksLength == 0) { try { ArtMethod method = Epic.getBackMethod(artmethod); return method.invoke(thisObject, args); } catch (Exception e) { log(e.getCause()); } } XC_MethodHook.MethodHookParam param = new XC_MethodHook.MethodHookParam(); param.method = (Member) (artmethod).getExecutable(); param.thisObject = thisObject; param.args = args; // call "before method" callbacks int beforeIdx = 0; do { try { ((XC_MethodHook) callbacksSnapshot[beforeIdx]).beforeHookedMethod(param); } catch (Throwable t) { log(t); // reset result (ignoring what the unexpectedly exiting callback did) param.setResult(null); param.returnEarly = false; continue; } if (param.returnEarly) { // skip remaining "before" callbacks and corresponding "after" callbacks beforeIdx++; break; } } while (++beforeIdx < callbacksLength); // call original method if not requested otherwise if (!param.returnEarly) { try { ArtMethod method = Epic.getBackMethod(artmethod); Object result = method.invoke(thisObject, args); param.setResult(result); } catch (Exception e) { // log(e); origin throw exception is normal. param.setThrowable(e); } } // call "after method" callbacks int afterIdx = beforeIdx - 1; do { Object lastResult = param.getResult(); Throwable lastThrowable = param.getThrowable(); try { ((XC_MethodHook) callbacksSnapshot[afterIdx]).afterHookedMethod(param); } catch (Throwable t) { DexposedBridge.log(t); // reset to last result (ignoring what the unexpectedly exiting callback did) if (lastThrowable == null) param.setResult(lastResult); else param.setThrowable(lastThrowable); } } while (--afterIdx >= 0); if (param.hasThrowable()) { final Throwable throwable = param.getThrowable(); if (throwable instanceof IllegalAccessException || throwable instanceof InvocationTargetException || throwable instanceof InstantiationException) { // reflect exception, get the origin cause final Throwable cause = throwable.getCause(); // We can not change the exception flow of origin call, rethrow // Logger.e(TAG, "origin call throw exception (not a real crash, just record for debug):", cause); DexposedBridge.<RuntimeException>throwNoCheck(param.getThrowable().getCause(), null); return null; //never reach. } else { // the exception cause by epic self, just log. Logger.e(TAG, "epic cause exception in call bridge!!", throwable); } return null; // never reached. } else { final Object result = param.getResult(); //Logger.d(TAG, "return :" + result); return result; } } /** * Just for throw an checked exception without check * @param exception The checked exception. * @param dummy dummy. * @param <T> fake type * @throws T the checked exception. */ @SuppressWarnings("unchecked") private static <T extends Throwable> void throwNoCheck(Throwable exception, Object dummy) throws T { throw (T) exception; } /** * This method is called as a replacement for hooked methods. */ private static Object handleHookedMethod(Member method, int originalMethodId, Object additionalInfoObj, Object thisObject, Object[] args) throws Throwable { AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj; Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot(); final int callbacksLength = callbacksSnapshot.length; if (callbacksLength == 0) { try { return invokeOriginalMethodNative(method, originalMethodId, additionalInfo.parameterTypes, additionalInfo.returnType, thisObject, args); } catch (InvocationTargetException e) { throw e.getCause(); } } XC_MethodHook.MethodHookParam param = new XC_MethodHook.MethodHookParam(); param.method = method; param.thisObject = thisObject; param.args = args; // call "before method" callbacks int beforeIdx = 0; do { try { ((XC_MethodHook) callbacksSnapshot[beforeIdx]).beforeHookedMethod(param); } catch (Throwable t) { log(t); // reset result (ignoring what the unexpectedly exiting callback did) param.setResult(null); param.returnEarly = false; continue; } if (param.returnEarly) { // skip remaining "before" callbacks and corresponding "after" callbacks beforeIdx++; break; } } while (++beforeIdx < callbacksLength); // call original method if not requested otherwise if (!param.returnEarly) { try { param.setResult(invokeOriginalMethodNative(method, originalMethodId, additionalInfo.parameterTypes, additionalInfo.returnType, param.thisObject, param.args)); } catch (InvocationTargetException e) { param.setThrowable(e.getCause()); } } // call "after method" callbacks int afterIdx = beforeIdx - 1; do { Object lastResult = param.getResult(); Throwable lastThrowable = param.getThrowable(); try { ((XC_MethodHook) callbacksSnapshot[afterIdx]).afterHookedMethod(param); } catch (Throwable t) { DexposedBridge.log(t); // reset to last result (ignoring what the unexpectedly exiting callback did) if (lastThrowable == null) param.setResult(lastResult); else param.setThrowable(lastThrowable); } } while (--afterIdx >= 0); // return if (param.hasThrowable()) throw param.getThrowable(); else return param.getResult(); } private native static Object invokeSuperNative(Object obj, Object[] args, Member method, Class<?> declaringClass, Class<?>[] parameterTypes, Class<?> returnType, int slot) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException; public static Object invokeSuper(Object obj, Member method, Object... args) throws NoSuchFieldException { try { int slot = 0; if(!Runtime.isArt()) { //get the super method slot Method m = XposedHelpers.findMethodExact(obj.getClass().getSuperclass(), method.getName(), ((Method) method).getParameterTypes()); slot = (int) getIntField(m, "slot"); } return invokeSuperNative(obj, args, method, method.getDeclaringClass(), ((Method) method).getParameterTypes(), ((Method) method).getReturnType(), slot); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (IllegalArgumentException e) { throw e; } catch (InvocationTargetException e) { throw new XposedHelpers.InvocationTargetError(e.getCause()); } } /** * Intercept every call to the specified method and call a handler function instead. * @param method The method to intercept */ private native synchronized static void hookMethodNative(Member method, Class<?> declaringClass, int slot, Object additionalInfo); private native static Object invokeOriginalMethodNative(Member method, int methodId, Class<?>[] parameterTypes, Class<?> returnType, Object thisObject, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException; /** * Basically the same as {@link Method#invoke}, but calls the original method * as it was before the interception by Xposed. Also, access permissions are not checked. * * @param method Method to be called * @param thisObject For non-static calls, the "this" pointer * @param args Arguments for the method call as Object[] array * @return The result returned from the invoked method * @throws NullPointerException * if {@code receiver == null} for a non-static method * @throws IllegalAccessException * if this method is not accessible (see {@link AccessibleObject}) * @throws IllegalArgumentException * if the number of arguments doesn't match the number of parameters, the receiver * is incompatible with the declaring class, or an argument could not be unboxed * or converted by a widening conversion to the corresponding parameter type * @throws InvocationTargetException * if an exception was thrown by the invoked method */ public static Object invokeOriginalMethod(Member method, Object thisObject, Object[] args) throws NullPointerException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (args == null) { args = EMPTY_ARRAY; } Class<?>[] parameterTypes; Class<?> returnType; if (method instanceof Method) { parameterTypes = ((Method) method).getParameterTypes(); returnType = ((Method) method).getReturnType(); } else if (method instanceof Constructor) { parameterTypes = ((Constructor<?>) method).getParameterTypes(); returnType = null; } else { throw new IllegalArgumentException("method must be of type Method or Constructor"); } if (Runtime.isArt()) { ArtMethod artMethod; if (method instanceof Method) { artMethod = ArtMethod.of((Method) method); } else { artMethod = ArtMethod.of((Constructor)method); } try { return Epic.getBackMethod(artMethod).invoke(thisObject, args); } catch (InstantiationException e) { DexposedBridge.<RuntimeException>throwNoCheck(e, null); } } return invokeOriginalMethodNative(method, 0, parameterTypes, returnType, thisObject, args); } public static class CopyOnWriteSortedSet<E> { private transient volatile Object[] elements = EMPTY_ARRAY; public synchronized boolean add(E e) { int index = indexOf(e); if (index >= 0) return false; Object[] newElements = new Object[elements.length + 1]; System.arraycopy(elements, 0, newElements, 0, elements.length); newElements[elements.length] = e; Arrays.sort(newElements); elements = newElements; return true; } public synchronized boolean remove(E e) { int index = indexOf(e); if (index == -1) return false; Object[] newElements = new Object[elements.length - 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index + 1, newElements, index, elements.length - index - 1); elements = newElements; return true; } public synchronized void clear(){ elements = EMPTY_ARRAY; } private int indexOf(Object o) { for (int i = 0; i < elements.length; i++) { if (o.equals(elements[i])) return i; } return -1; } public Object[] getSnapshot() { return elements; } } private static class AdditionalHookInfo { final CopyOnWriteSortedSet<XC_MethodHook> callbacks; final Class<?>[] parameterTypes; final Class<?> returnType; private AdditionalHookInfo(CopyOnWriteSortedSet<XC_MethodHook> callbacks, Class<?>[] parameterTypes, Class<?> returnType) { this.callbacks = callbacks; this.parameterTypes = parameterTypes; this.returnType = returnType; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/Epic.java
Java
/* * Copyright (c) 2017, weishu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art; import android.os.Build; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.Runtime; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import me.weishu.epic.art.arch.Arm64; import me.weishu.epic.art.arch.ShellCode; import me.weishu.epic.art.arch.Thumb2; import me.weishu.epic.art.method.ArtMethod; /** * Hook Center. */ public final class Epic { private static final String TAG = "Epic"; private static final Map<String, ArtMethod> backupMethodsMapping = new ConcurrentHashMap<>(); private static final Map<Long, MethodInfo> originSigs = new ConcurrentHashMap<>(); private static final Map<Long, Trampoline> scripts = new HashMap<>(); private static ShellCode ShellCode; static { boolean isArm = true; // TODO: 17/11/21 TODO int apiLevel = Build.VERSION.SDK_INT; boolean thumb2 = true; if (isArm) { if (Runtime.is64Bit()) { ShellCode = new Arm64(); } else if (Runtime.isThumb2()) { ShellCode = new Thumb2(); } else { thumb2 = false; ShellCode = new Thumb2(); Logger.w(TAG, "ARM32, not support now."); } } if (ShellCode == null) { throw new RuntimeException("Do not support this ARCH now!! API LEVEL:" + apiLevel + " thumb2 ? : " + thumb2); } Logger.i(TAG, "Using: " + ShellCode.getName()); } public static boolean hookMethod(Constructor origin) { return hookMethod(ArtMethod.of(origin)); } public static boolean hookMethod(Method origin) { ArtMethod artOrigin = ArtMethod.of(origin); return hookMethod(artOrigin); } private static boolean hookMethod(ArtMethod artOrigin) { MethodInfo methodInfo = new MethodInfo(); methodInfo.isStatic = Modifier.isStatic(artOrigin.getModifiers()); final Class<?>[] parameterTypes = artOrigin.getParameterTypes(); if (parameterTypes != null) { methodInfo.paramNumber = parameterTypes.length; methodInfo.paramTypes = parameterTypes; } else { methodInfo.paramNumber = 0; methodInfo.paramTypes = new Class<?>[0]; } methodInfo.returnType = artOrigin.getReturnType(); methodInfo.method = artOrigin; originSigs.put(artOrigin.getAddress(), methodInfo); if (!artOrigin.isAccessible()) { artOrigin.setAccessible(true); } artOrigin.ensureResolved(); long originEntry = artOrigin.getEntryPointFromQuickCompiledCode(); if (originEntry == ArtMethod.getQuickToInterpreterBridge()) { Logger.i(TAG, "this method is not compiled, compile it now. current entry: 0x" + Long.toHexString(originEntry)); boolean ret = artOrigin.compile(); if (ret) { originEntry = artOrigin.getEntryPointFromQuickCompiledCode(); Logger.i(TAG, "compile method success, new entry: 0x" + Long.toHexString(originEntry)); } else { Logger.e(TAG, "compile method failed..."); return false; // return hookInterpreterBridge(artOrigin); } } ArtMethod backupMethod = artOrigin.backup(); Logger.i(TAG, "backup method address:" + Debug.addrHex(backupMethod.getAddress())); Logger.i(TAG, "backup method entry :" + Debug.addrHex(backupMethod.getEntryPointFromQuickCompiledCode())); ArtMethod backupList = getBackMethod(artOrigin); if (backupList == null) { setBackMethod(artOrigin, backupMethod); } final long key = originEntry; final EntryLock lock = EntryLock.obtain(originEntry); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (lock) { if (!scripts.containsKey(key)) { scripts.put(key, new Trampoline(ShellCode, originEntry)); } Trampoline trampoline = scripts.get(key); boolean ret = trampoline.install(artOrigin); // Logger.d(TAG, "hook Method result:" + ret); return ret; } } /* private static boolean hookInterpreterBridge(ArtMethod artOrigin) { String identifier = artOrigin.getIdentifier(); ArtMethod backupMethod = artOrigin.backup(); Logger.d(TAG, "backup method address:" + Debug.addrHex(backupMethod.getAddress())); Logger.d(TAG, "backup method entry :" + Debug.addrHex(backupMethod.getEntryPointFromQuickCompiledCode())); List<ArtMethod> backupList = backupMethodsMapping.get(identifier); if (backupList == null) { backupList = new LinkedList<ArtMethod>(); backupMethodsMapping.put(identifier, backupList); } backupList.add(backupMethod); long originalEntryPoint = ShellCode.toMem(artOrigin.getEntryPointFromQuickCompiledCode()); Logger.d(TAG, "originEntry Point(bridge):" + Debug.addrHex(originalEntryPoint)); originalEntryPoint += 16; Logger.d(TAG, "originEntry Point(offset8):" + Debug.addrHex(originalEntryPoint)); if (!scripts.containsKey(originalEntryPoint)) { scripts.put(originalEntryPoint, new Trampoline(ShellCode, artOrigin)); } Trampoline trampoline = scripts.get(originalEntryPoint); boolean ret = trampoline.install(); Logger.i(TAG, "hook Method result:" + ret); return ret; }*/ public synchronized static ArtMethod getBackMethod(ArtMethod origin) { String identifier = origin.getIdentifier(); return backupMethodsMapping.get(identifier); } public static synchronized void setBackMethod(ArtMethod origin, ArtMethod backup) { String identifier = origin.getIdentifier(); backupMethodsMapping.put(identifier, backup); } public static MethodInfo getMethodInfo(long address) { return originSigs.get(address); } public static int getQuickCompiledCodeSize(ArtMethod method) { long entryPoint = ShellCode.toMem(method.getEntryPointFromQuickCompiledCode()); long sizeInfo1 = entryPoint - 4; byte[] bytes = EpicNative.get(sizeInfo1, 4); int size = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(); Logger.d(TAG, "getQuickCompiledCodeSize: " + size); return size; } public static class MethodInfo { public boolean isStatic; public int paramNumber; public Class<?>[] paramTypes; public Class<?> returnType; public ArtMethod method; @Override public String toString() { return method.toGenericString(); } } private static class EntryLock { static Map<Long, EntryLock> sLockPool = new HashMap<>(); static synchronized EntryLock obtain(long entry) { if (sLockPool.containsKey(entry)) { return sLockPool.get(entry); } else { EntryLock entryLock = new EntryLock(); sLockPool.put(entry, entryLock); return entryLock; } } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/EpicNative.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art; import android.util.Log; import com.taobao.android.dexposed.DeviceCheck; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.Unsafe; import java.lang.reflect.Member; import de.robv.android.xposed.XposedHelpers; import static com.taobao.android.dexposed.utility.Debug.addrHex; public final class EpicNative { private static final String TAG = "EpicNative"; private static volatile boolean useUnsafe = false; static { try { System.loadLibrary("epic"); useUnsafe = DeviceCheck.isYunOS() || !isGetObjectAvailable(); Log.i(TAG, "use unsafe ? " + useUnsafe); } catch (Throwable e) { Log.e(TAG, "init EpicNative error", e); } } public static native long mmap(int length); public static native boolean munmap(long address, int length); public static native void memcpy(long src, long dest, int length); public static native void memput(byte[] bytes, long dest); public static native byte[] memget(long src, int length); public static native boolean munprotect(long addr, long len); public static native long getMethodAddress(Member method); public static native void MakeInitializedClassVisibilyInitialized(long self); public static native boolean cacheflush(long addr, long len); public static native long malloc(int sizeOfPtr); public static native Object getObjectNative(long self, long address); private static native boolean isGetObjectAvailable(); public static Object getObject(long self, long address) { if (useUnsafe) { return Unsafe.getObject(address); } else { return getObjectNative(self, address); } } public static native boolean compileMethod(Member method, long self); /** * suspend all running thread momently * @return a handle to resume all thread, used by {@link #resumeAll(long)} */ public static native long suspendAll(); /** * resume all thread which are suspend by {@link #suspendAll()} * only work abobe Android N * @param cookie the cookie return by {@link #suspendAll()} */ public static native void resumeAll(long cookie); /** * stop jit compiler in runtime. * Warning: Just for experiment Do not call this now!!! * @return cookie use by {@link #startJit(long)} */ public static native long stopJit(); /** * start jit compiler stop by {@link #stopJit()} * Warning: Just for experiment Do not call this now!!! * @param cookie the cookie return by {@link #stopJit()} */ public static native void startJit(long cookie); // FIXME: 17/12/29 reimplement it with pure native code. static native boolean activateNative(long jumpToAddress, long pc, long sizeOfTargetJump, long sizeOfBridgeJump, byte[] code); /** * Disable the moving gc of runtime. * Warning: Just for experiment Do not call this now!!! * @param api the api level */ public static native void disableMovingGc(int api); private EpicNative() { } public static boolean compileMethod(Member method) { final long nativePeer = XposedHelpers.getLongField(Thread.currentThread(), "nativePeer"); return compileMethod(method, nativePeer); } public static Object getObject(long address) { final long nativePeer = XposedHelpers.getLongField(Thread.currentThread(), "nativePeer"); return getObject(nativePeer, address); } public static void MakeInitializedClassVisibilyInitialized() { final long nativePeer = XposedHelpers.getLongField(Thread.currentThread(), "nativePeer"); MakeInitializedClassVisibilyInitialized(nativePeer); } public static long map(int length) { long m = mmap(length); Logger.i(TAG, "Mapped memory of size " + length + " at " + addrHex(m)); return m; } public static boolean unmap(long address, int length) { Logger.d(TAG, "Removing mapped memory of size " + length + " at " + addrHex(address)); return munmap(address, length); } public static void put(byte[] bytes, long dest) { if (Debug.DEBUG) { Logger.d(TAG, "Writing memory to: " + addrHex(dest)); Logger.d(TAG, Debug.hexdump(bytes, dest)); } memput(bytes, dest); } public static byte[] get(long src, int length) { Logger.d(TAG, "Reading " + length + " bytes from: " + addrHex(src)); byte[] bytes = memget(src, length); Logger.d(TAG, Debug.hexdump(bytes, src)); return bytes; } public static boolean unprotect(long addr, long len) { Logger.d(TAG, "Disabling mprotect from " + addrHex(addr)); return munprotect(addr, len); } public static void copy(long src, long dst, int length) { Logger.d(TAG, "Copy " + length + " bytes form " + addrHex(src) + " to " + addrHex(dst)); memcpy(src, dst, length); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/Trampoline.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.Runtime; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import me.weishu.epic.art.arch.ShellCode; import me.weishu.epic.art.entry.Entry; import me.weishu.epic.art.entry.Entry64; import me.weishu.epic.art.method.ArtMethod; class Trampoline { private static final String TAG = "Trampoline"; private final ShellCode shellCode; private final long jumpToAddress; private final byte[] originalCode; private int trampolineSize; private long trampolineAddress; private boolean active; // private ArtMethod artOrigin; private Set<ArtMethod> segments = new HashSet<>(); Trampoline(ShellCode shellCode, long entryPoint) { this.shellCode = shellCode; this.jumpToAddress = shellCode.toMem(entryPoint); this.originalCode = EpicNative.get(jumpToAddress, shellCode.sizeOfDirectJump()); } public boolean install(ArtMethod originMethod){ boolean modified = segments.add(originMethod); if (!modified) { // Already hooked, ignore Logger.d(TAG, originMethod + " is already hooked, return."); return true; } byte[] page = create(); EpicNative.put(page, getTrampolineAddress()); int quickCompiledCodeSize = Epic.getQuickCompiledCodeSize(originMethod); int sizeOfDirectJump = shellCode.sizeOfDirectJump(); if (quickCompiledCodeSize < sizeOfDirectJump) { Logger.w(TAG, originMethod.toGenericString() + " quickCompiledCodeSize: " + quickCompiledCodeSize); originMethod.setEntryPointFromQuickCompiledCode(getTrampolinePc()); return true; } // 这里是绝对不能改EntryPoint的,碰到GC就挂(GC暂停线程的时候,遍历所有线程堆栈,如果被hook的方法在堆栈上,那就GG) // source.setEntryPointFromQuickCompiledCode(script.getTrampolinePc()); return activate(); } private long getTrampolineAddress() { if (getSize() != trampolineSize) { alloc(); } return trampolineAddress; } private long getTrampolinePc() { return shellCode.toPC(getTrampolineAddress()); } private void alloc() { if (trampolineAddress != 0) { free(); } trampolineSize = getSize(); trampolineAddress = EpicNative.map(trampolineSize); Logger.d(TAG, "Trampoline alloc:" + trampolineSize + ", addr: 0x" + Long.toHexString(trampolineAddress)); } private void free() { if (trampolineAddress != 0) { EpicNative.unmap(trampolineAddress, trampolineSize); trampolineAddress = 0; trampolineSize = 0; } if (active) { EpicNative.put(originalCode, jumpToAddress); } } private int getSize() { int count = 0; count += shellCode.sizeOfBridgeJump() * segments.size(); count += shellCode.sizeOfCallOrigin(); return count; } private byte[] create() { Logger.d(TAG, "create trampoline." + segments); byte[] mainPage = new byte[getSize()]; int offset = 0; for (ArtMethod method : segments) { byte[] bridgeJump = createTrampoline(method); int length = bridgeJump.length; System.arraycopy(bridgeJump, 0, mainPage, offset, length); offset += length; } byte[] callOriginal = shellCode.createCallOrigin(jumpToAddress, originalCode); System.arraycopy(callOriginal, 0, mainPage, offset, callOriginal.length); return mainPage; } private boolean activate() { long pc = getTrampolinePc(); Logger.d(TAG, "Writing direct jump entry " + Debug.addrHex(pc) + " to origin entry: 0x" + Debug.addrHex(jumpToAddress)); synchronized (Trampoline.class) { return EpicNative.activateNative(jumpToAddress, pc, shellCode.sizeOfDirectJump(), shellCode.sizeOfBridgeJump(), shellCode.createDirectJump(pc)); } } @Override protected void finalize() throws Throwable { free(); super.finalize(); } private byte[] createTrampoline(ArtMethod source){ final Epic.MethodInfo methodInfo = Epic.getMethodInfo(source.getAddress()); final Class<?> returnType = methodInfo.returnType; // Method bridgeMethod = Runtime.is64Bit() ? (Build.VERSION.SDK_INT == 23 ? Entry64_2.getBridgeMethod(methodInfo) : Entry64.getBridgeMethod(returnType)) // : Entry.getBridgeMethod(returnType); Method bridgeMethod = Runtime.is64Bit() ? Entry64.getBridgeMethod(returnType) : Entry.getBridgeMethod(returnType); final ArtMethod target = ArtMethod.of(bridgeMethod); long targetAddress = target.getAddress(); long targetEntry = target.getEntryPointFromQuickCompiledCode(); long sourceAddress = source.getAddress(); long structAddress = EpicNative.malloc(4); Logger.d(TAG, "targetAddress:"+ Debug.longHex(targetAddress)); Logger.d(TAG, "sourceAddress:"+ Debug.longHex(sourceAddress)); Logger.d(TAG, "targetEntry:"+ Debug.longHex(targetEntry)); Logger.d(TAG, "structAddress:"+ Debug.longHex(structAddress)); return shellCode.createBridgeJump(targetAddress, targetEntry, sourceAddress, structAddress); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/arch/Arm64.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.arch; import java.nio.ByteOrder; public class Arm64 extends ShellCode { @Override public int sizeOfDirectJump() { return 4 * 4; } @Override public byte[] createDirectJump(long targetAddress) { byte[] instructions = new byte[]{ 0x50, 0x00, 0x00, 0x58, // ldr x9, _targetAddress 0x00, 0x02, 0x1F, (byte) 0xD6, // br x9 0x00, 0x00, 0x00, 0x00, // targetAddress 0x00, 0x00, 0x00, 0x00 // targetAddress }; writeLong(targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); return instructions; } @Override public byte[] createBridgeJump(long targetAddress, long targetEntry, long srcAddress, long structAddress) { byte[] instructions = new byte[]{ 0x1f, 0x20, 0x03, (byte) 0xd5, // nop 0x69, 0x02, 0x00, 0x58, // ldr x9, source_method 0x1f, 0x00, 0x09, (byte) 0xeb, // cmp x0, x9 (byte) 0xa1, 0x02, 0x00, 0x54, // bne 5f (byte) 0x80, 0x01, 0x00, 0x58, // ldr x0, target_method 0x29, 0x02, 0x00, 0x58, // ldr x9, struct (byte) 0xea, 0x03, 0x00, (byte) 0x91, // mov x10, sp 0x2a, 0x01, 0x00, (byte) 0xf9, // str x10, [x9, #0] 0x22, 0x05, 0x00, (byte) 0xf9, // str x2, [x9, #8] 0x23, 0x09, 0x00, (byte) 0xf9, // str x3, [x9, #16] (byte) 0xe3, 0x03, 0x09, (byte) 0xaa, // mov x3, x9 0x22, 0x01, 0x00, 0x58, // ldr x2, source_method 0x22, 0x0d, 0x00, (byte) 0xf9, // str x2, [x9, #24] (byte) 0xe2, 0x03, 0x13, (byte) 0xaa, // mov x2, x19 (byte) 0x89, 0x00, 0x00, 0x58, // ldr x9, target_method_entry 0x20, 0x01, 0x1f, (byte) 0xd6, // br x9 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // target_method_address 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // target_method_entry 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // source_method 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // struct }; writeLong(targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 32); writeLong(targetEntry, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 24); writeLong(srcAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 16); writeLong(structAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); return instructions; } @Override public int sizeOfBridgeJump() { return 24 * 4; } @Override public long toPC(long code) { return code; } @Override public long toMem(long pc) { return pc; } @Override public String getName() { return "64-bit ARM"; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/arch/Arm64_2.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.arch; import java.nio.ByteOrder; public class Arm64_2 extends ShellCode { @Override public int sizeOfDirectJump() { return 4 * 4; } @Override public byte[] createDirectJump(long targetAddress) { byte[] instructions = new byte[]{ 0x50, 0x00, 0x00, 0x58, // ldr x16, _targetAddress 0x00, 0x02, 0x1F, (byte) 0xD6, // br x16 0x00, 0x00, 0x00, 0x00, // targetAddress 0x00, 0x00, 0x00, 0x00 // targetAddress }; writeLong(targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); return instructions; } @Override public byte[] createBridgeJump(long targetAddress, long targetEntry, long srcAddress, long structAddress) { byte[] instructions = new byte[] { /* ldr x17, 3f cmp x0, x17 bne 5f ldr x0, 1f ldr x17, 4f mov x16, sp str x16, [x17, #0] str x2, [x17, #8] ldr x16, 3f str x16, [x17, #16] mov x2, x17 ldr x17, 2f br x17 1: .quad 0x0 2: .quad 0x0 3: .quad 0x0 4: .quad 0x0 5: mov x0, x17 */ 0x1f, 0x20, 0x03, (byte) 0xd5, // nop 0x31, 0x02, 0x00, 0x58, 0x1f, 0x00, 0x11, (byte)0xeb, (byte)0x61, 0x02, 0x00, 0x54, (byte)0x40, 0x01, 0x00, 0x58, (byte)0xf1, 0x01, 0x00, 0x58, (byte)0xf0, 0x03, 0x00, (byte)0x91, (byte)0x30, 0x02, 0x00, (byte)0xf9, 0x22, 0x06, 0x00, (byte)0xf9, 0x30, 0x01, 0x00, (byte)0x58, (byte)0x30, 0x0a, 0x00, (byte)0xf9, (byte)0xe2, 0x03, 0x11, (byte)0xaa, (byte)0x91, 0x00, 0x00, 0x58, (byte)0x20, 0x02, 0x1f, (byte)0xd6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // target_method_address 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // target_method_entry 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // source_method 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // struct }; writeLong(targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 32); writeLong(targetEntry, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 24); writeLong(srcAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 16); writeLong(structAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); return instructions; } @Override public int sizeOfBridgeJump() { return 22 * 4; } @Override public long toPC(long code) { return code; } @Override public long toMem(long pc) { return pc; } @Override public String getName() { return "64-bit ARM(Android M)"; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/arch/ShellCode.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.arch; import java.nio.ByteBuffer; import java.nio.ByteOrder; public abstract class ShellCode { public abstract byte[] createDirectJump(long targetAddress); public abstract int sizeOfDirectJump(); public abstract long toPC(long code); public abstract long toMem(long pc); public byte[] createCallOrigin(long originalAddress, byte[] originalPrologue) { byte[] callOriginal = new byte[sizeOfCallOrigin()]; System.arraycopy(originalPrologue, 0, callOriginal, 0, sizeOfDirectJump()); byte[] directJump = createDirectJump(toPC(originalAddress + sizeOfDirectJump())); System.arraycopy(directJump, 0, callOriginal, sizeOfDirectJump(), directJump.length); return callOriginal; } public int sizeOfCallOrigin() { return sizeOfDirectJump() * 2; } public abstract int sizeOfBridgeJump(); public byte[] createBridgeJump(long targetAddress, long targetEntry, long srcAddress, long structAddress) { throw new RuntimeException("not impled"); } static void writeInt(int i, ByteOrder order, byte[] target, int pos) { System.arraycopy(ByteBuffer.allocate(4).order(order).putInt(i).array(), 0, target, pos, 4); } static void writeLong(long i, ByteOrder order, byte[] target, int pos) { System.arraycopy(ByteBuffer.allocate(8).order(order).putLong(i).array(), 0, target, pos, 8); } public abstract String getName(); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/arch/Thumb2.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.arch; import java.nio.ByteOrder; public class Thumb2 extends ShellCode { @Override public int sizeOfDirectJump() { return 12; } @Override public byte[] createDirectJump(long targetAddress) { byte[] instructions = new byte[] { (byte) 0xdf, (byte) 0xf8, 0x00, (byte) 0xf0, // ldr pc, [pc] 0, 0, 0, 0 }; writeInt((int) targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 4); return instructions; } @Override public byte[] createBridgeJump(long targetAddress, long targetEntry, long srcAddress, long structAddress) { // 有问题,参数丢失。 // byte[] instructions = new byte[] { // (byte) 0xdf, (byte) 0xf8, 0x18, (byte) 0xc0, // ldr ip, [pc, #24], ip = source_method_address // // (byte) 0x01, (byte) 0x91, // str r1, [sp, #4] // (byte) 0x02, (byte) 0x92, // str r2, [sp, #8] // // (byte) 0x03, (byte) 0x93, // str r3, [sp, #12] // (byte) 0x62, (byte) 0x46, // mov r2, ip // // 0x01, 0x48, // ldr r0, [pc, #4] // 0x6b, 0x46, // mov r3, sp // // (byte) 0xdf, (byte) 0xf8, 0x04, (byte) 0xf0, // ldr pc, [pc, #4] // // 0x0, 0x0, 0x0, 0x0, // target_method_pos_x // 0x0, 0x0, 0x0, 0x0, // target_method_entry_point // 0x0, 0x0, 0x0, 0x0, // src_method_pos_x // }; // writeInt((int) targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, // instructions.length - 12); // writeInt((int) targetEntry, // ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); // writeInt((int) srcAddress, ByteOrder.LITTLE_ENDIAN, instructions, // instructions.length - 4); byte[] instructions = new byte[]{ (byte) 0xdf, (byte) 0xf8, (byte) 0x30, (byte) 0xc0, // ldr ip, [pc, #48] ip = source method address (byte) 0x60, (byte) 0x45, // cmp r0, ip if r0 != ip (byte) 0x40, (byte) 0xf0, (byte) 0x19, (byte) 0x80, // bne.w 1f jump label 1: (byte) 0x08, (byte) 0x48, // ldr r0, [pc, #28] r0 = target_method_address (byte) 0xdf, (byte) 0xf8, (byte) 0x28, (byte) 0xc0, // ldr ip, [pc, #38] ip = struct address (byte) 0xcc, (byte) 0xf8, (byte) 0x00, (byte) 0xd0, // str sp, [ip, #0] (byte) 0xcc, (byte) 0xf8, (byte) 0x04, (byte) 0x20, // str r2, [ip, #4] (byte) 0xcc, (byte) 0xf8, (byte) 0x08, (byte) 0x30, // str r3, [ip, #8] (byte) 0x63, (byte) 0x46, // mov r3, ip (byte) 0x05, (byte) 0x4a, // ldr r2, [pc, #16] r2 = source_method_address (byte) 0xcc, (byte) 0xf8, (byte) 0x0c, (byte) 0x20, // str r2, [ip, #12] (byte) 0x4a, (byte) 0x46, // move r2, r9 (byte) 0x4a, (byte) 0x46, // move r2, r9 (byte) 0xdf, (byte) 0xf8, (byte) 0x04, (byte) 0xf0, // ldr pc, [pc, #4] 0x0, 0x0, 0x0, 0x0, // target_method_pos_x 0x0, 0x0, 0x0, 0x0, // target_method_entry_point 0x0, 0x0, 0x0, 0x0, // src_method_address 0x0, 0x0, 0x0, 0x0, // struct address (sp, r1, r2) // 1: }; writeInt((int) targetAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 16); writeInt((int) targetEntry, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 12); writeInt((int) srcAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 8); writeInt((int) structAddress, ByteOrder.LITTLE_ENDIAN, instructions, instructions.length - 4); return instructions; } @Override public int sizeOfBridgeJump() { return 15 * 4; } @Override public long toPC(long code) { return toMem(code) + 1; } @Override public long toMem(long pc) { return pc & ~0x1; } @Override public String getName() { return "Thumb2"; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/entry/Entry.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.entry; import android.os.Build; import android.util.Pair; import de.robv.android.xposed.DexposedBridge; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import me.weishu.epic.art.Epic; import me.weishu.epic.art.EpicNative; @SuppressWarnings({"unused", "ConstantConditions"}) public class Entry { private final static String TAG = "Entry"; private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; //region ---------------callback--------------- private static int onHookInt(Object artmethod, Object receiver, Object[] args) { return (Integer) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static long onHookLong(Object artmethod, Object receiver, Object[] args) { return (Long) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static double onHookDouble(Object artmethod, Object receiver, Object[] args) { return (Double) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static char onHookChar(Object artmethod, Object receiver, Object[] args) { return (Character) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static short onHookShort(Object artmethod, Object receiver, Object[] args) { return (Short) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static float onHookFloat(Object artmethod, Object receiver, Object[] args) { return (Float) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static Object onHookObject(Object artmethod, Object receiver, Object[] args) { return DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static void onHookVoid(Object artmethod, Object receiver, Object[] args) { DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static boolean onHookBoolean(Object artmethod, Object receiver, Object[] args) { return (Boolean) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static byte onHookByte(Object artmethod, Object receiver, Object[] args) { return (Byte) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } //endregion //region ---------------bridge--------------- private static void voidBridge(int r1, int self, int struct) { referenceBridge(r1, self, struct); } private static boolean booleanBridge(int r1, int self, int struct) { return (Boolean) referenceBridge(r1, self, struct); } private static byte byteBridge(int r1, int self, int struct) { return (Byte) referenceBridge(r1, self, struct); } private static short shortBridge(int r1, int self, int struct) { return (Short) referenceBridge(r1, self, struct); } private static char charBridge(int r1, int self, int struct) { return (Character) referenceBridge(r1, self, struct); } private static int intBridge(int r1, int self, int struct) { return (Integer) referenceBridge(r1, self, struct); } private static long longBridge(int r1, int self, int struct) { return (Long) referenceBridge(r1, self, struct); } private static float floatBridge(int r1, int self, int struct) { return (Float) referenceBridge(r1, self, struct); } private static double doubleBridge(int r1, int self, int struct) { return (Double) referenceBridge(r1, self, struct); } //endregion private static Object referenceBridge(int r1, int self, int struct) { Logger.i(TAG, "enter bridge function."); // struct { // void* sp; // void* r2; // void* r3; // void* sourceMethod // } // sp + 16 = r4 Logger.i(TAG, "struct:" + Long.toHexString(struct)); final int sp = ByteBuffer.wrap(EpicNative.get(struct, 4)).order(ByteOrder.LITTLE_ENDIAN).getInt(); // Logger.i(TAG, "stack:" + Debug.hexdump(EpicNative.get(sp, 96), 0)); final byte[] rr1 = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(r1).array(); final byte[] r2 = EpicNative.get(struct + 4, 4); final byte[] r3 = EpicNative.get(struct + 8, 4); Logger.d(TAG, "r1:" + Debug.hexdump(rr1, 0)); Logger.d(TAG, "r2:" + Debug.hexdump(r2, 0)); Logger.d(TAG, "r3:" + Debug.hexdump(r3, 0)); final byte[] sourceAddr = EpicNative.get(struct + 12, 4); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]); byteBuffer.put(sourceAddr); byteBuffer.put(new byte[] {0, 0, 0, 0}); byteBuffer.flip(); final long sourceMethod = byteBuffer.order(ByteOrder.LITTLE_ENDIAN).getLong(); Logger.i(TAG, "sourceMethod:" + Long.toHexString(sourceMethod)); Epic.MethodInfo originMethodInfo = Epic.getMethodInfo(sourceMethod); Logger.i(TAG, "originMethodInfo :" + originMethodInfo); final Pair<Object, Object[]> constructArguments = constructArguments(originMethodInfo, self, rr1, r2, r3, sp); Object receiver = constructArguments.first; Object[] arguments = constructArguments.second; Logger.i(TAG, "arguments:" + Arrays.toString(arguments)); Class<?> returnType = originMethodInfo.returnType; Object artMethod = originMethodInfo.method; Logger.i(TAG, "leave bridge function"); if (returnType == void.class) { onHookVoid(artMethod, receiver, arguments); return 0; } else if (returnType == char.class) { return onHookChar(artMethod, receiver, arguments); } else if (returnType == byte.class) { return onHookByte(artMethod, receiver, arguments); } else if (returnType == short.class) { return onHookShort(artMethod, receiver, arguments); } else if (returnType == int.class) { return onHookInt(artMethod, receiver, arguments); } else if (returnType == long.class) { return onHookLong(artMethod, receiver, arguments); } else if (returnType == float.class) { return onHookFloat(artMethod, receiver, arguments); } else if (returnType == double.class) { return onHookDouble(artMethod, receiver, arguments); } else if (returnType == boolean.class) { return onHookBoolean(artMethod, receiver, arguments); } else { return onHookObject(artMethod, receiver, arguments); } } /** * construct the method arguments from register r1, r2, r3 and stack * @param r1 register r1 value * @param r2 register r2 value * @param r3 register r3 value * @param sp stack pointer * @return arguments passed to the callee method */ private static Pair<Object, Object[]> constructArguments(Epic.MethodInfo originMethodInfo, int self, byte[] r1, byte[] r2, byte[] r3, int sp) { boolean isStatic = originMethodInfo.isStatic; int numberOfArgs; Class<?>[] typeOfArgs; if (isStatic) { // static argument, r1, r2, r3, sp + 16 // sp + 0 = ArtMethod (ourself) // sp + 4 = r1 (may be earased) // sp + 8 = r2 (may be earased) // sp + 12 = r3 (may be earased) // sp + 16 = r4, remain numberOfArgs = originMethodInfo.paramNumber; typeOfArgs = originMethodInfo.paramTypes; } else { // non-static, r1 = receiver; r2, r3, sp + 16 is arguments. // sp + 0 = ArtMethod (ourself) // sp + 4 = r1 = this (may be earased) // sp + 8 = r2 = first argument (may be earased) // sp + 12 = r3 = second argument (may be earased) // sp + 16 = third argument, remain numberOfArgs = 1 + originMethodInfo.paramNumber; typeOfArgs = new Class<?>[numberOfArgs]; typeOfArgs[0] = Object.class; // this System.arraycopy(originMethodInfo.paramTypes, 0, typeOfArgs, 1, originMethodInfo.paramTypes.length); } Object[] arguments = new Object[numberOfArgs]; int currentStackPosition = 4; // sp + 0 = ArtMethod, sp + 4... start store arguments. final int argumentStackBegin = 16; // sp + 4 = r1, sp + 8 = r2, sp + 12 = r3, sp + 16 start in stack. int[] argStartPos = new int[numberOfArgs]; for (int i = 0; i < numberOfArgs; i++) { Class<?> typeOfArg = typeOfArgs[i]; int typeLength = getTypeLength(typeOfArg); argStartPos[i] = currentStackPosition; currentStackPosition += typeLength; } int argTotalLength = currentStackPosition; byte[] argBytes = new byte[argTotalLength]; do { if (argTotalLength <= 4) break; boolean align = Build.VERSION.SDK_INT >= 23 && numberOfArgs > 0 && getTypeLength(typeOfArgs[0]) == 8; if (align) { System.arraycopy(r2, 0, argBytes, 4, 4); System.arraycopy(r3, 0, argBytes, 8, 4); if (argTotalLength <= 12) break; System.arraycopy(EpicNative.get(sp + 12, 4), 0, argBytes, 12, 4); } else { System.arraycopy(r1, 0, argBytes, 4, 4); if (argTotalLength <= 8) break; System.arraycopy(r2, 0, argBytes, 8, 4); if (argTotalLength <= 12) break; System.arraycopy(r3, 0, argBytes, 12, 4); } if (argTotalLength <= 16) break; byte[] argInStack = EpicNative.get(sp + 16, argTotalLength - 16); System.arraycopy(argInStack, 0, argBytes, 16, argTotalLength - 16); } while (false); //region ---------------Process Arguments passing in Android M--------------- if (Build.VERSION.SDK_INT == 23) { // Android M, fix sp + 12 if (argTotalLength <= 12) { // Nothing } else { if (argTotalLength <= 16) { if (getTypeLength(typeOfArgs[0]) == 8) { // first is 8byte System.arraycopy(EpicNative.get(sp + 44, 4), 0, argBytes, 12, 4); } else { // 48, 444: normal. } } else { boolean isR3Grabbed = true; if (numberOfArgs >= 2) { int arg1TypeLength = getTypeLength(typeOfArgs[0]); int arg2TypeLength = getTypeLength(typeOfArgs[1]); if (arg1TypeLength == 4 && arg2TypeLength == 8) { isR3Grabbed = false; } if (numberOfArgs == 2 && arg1TypeLength == 8 && arg2TypeLength == 8) { // in this case, we have no reference register to local r3, just hard code now :( System.arraycopy(EpicNative.get(sp + 44, 4), 0, argBytes, 12, 4); isR3Grabbed = false; } } if (numberOfArgs >= 3) { int arg1TypeLength = getTypeLength(typeOfArgs[0]); int arg2TypeLength = getTypeLength(typeOfArgs[1]); int arg3TypeLength = getTypeLength(typeOfArgs[2]); if (arg1TypeLength == 4 && arg2TypeLength == 4 && arg3TypeLength == 4) { // in this case: r1 = arg1; r2 = arg2; r3 = arg3, normal. isR3Grabbed = false; } if (numberOfArgs == 3 && arg1TypeLength == 8 && arg2TypeLength == 4 && arg3TypeLength == 8) { // strange case :) System.arraycopy(EpicNative.get(sp + 52, 4), 0, argBytes, 12, 4); isR3Grabbed = false; } } if (isR3Grabbed) { byte[] otherStoreInStack = Arrays.copyOfRange(argBytes, argumentStackBegin, argBytes.length); int otherStoreInStackLength = otherStoreInStack.length; int searchRegion = 0; for (int i = argumentStackBegin + otherStoreInStackLength; ; i = i + 4) { final byte[] bytes = EpicNative.get(sp + i, otherStoreInStackLength); searchRegion += otherStoreInStackLength; if (Arrays.equals(bytes, otherStoreInStack)) { int originR3Index = sp + i - 4; final byte[] originR3 = EpicNative.get(originR3Index, 4); Logger.d(TAG, "found other arguments in stack, index:" + i + ", origin r3:" + Arrays.toString(originR3)); System.arraycopy(originR3, 0, argBytes, 12, 4); break; } if (searchRegion > (1 << 10)) { throw new RuntimeException("can not found the modify r3 register!!!"); } } } } } } //endregion Logger.d(TAG, "argBytes: " + Debug.hexdump(argBytes, 0)); for (int i = 0; i < numberOfArgs; i++) { final Class<?> typeOfArg = typeOfArgs[i]; final int startPos = argStartPos[i]; final int typeLength = getTypeLength(typeOfArg); byte[] argWithBytes = Arrays.copyOfRange(argBytes, startPos, startPos + typeLength); arguments[i] = wrapArgument(typeOfArg, self, argWithBytes); // Logger.d(TAG, "argument[" + i + "], startPos:" + startPos + ", typeOfLength:" + typeLength); // Logger.d(TAG, "argWithBytes:" + Debug.hexdump(argWithBytes, 0) + ", value:" + arguments[i]); } Object thiz = null; Object[] parameters = EMPTY_OBJECT_ARRAY; if (isStatic) { parameters = arguments; } else { thiz = arguments[0]; int argumentLength = arguments.length; if (argumentLength > 1) { parameters = Arrays.copyOfRange(arguments, 1, argumentLength); } } return Pair.create(thiz, parameters); } private static Object wrapArgument(Class<?> type, int self, byte[] value) { final ByteBuffer byteBuffer = ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN); Logger.d(TAG, "wrapArgument: type:" + type); if (type.isPrimitive()) { if (type == int.class) { return byteBuffer.getInt(); } else if (type == long.class) { return byteBuffer.getLong(); } else if (type == float.class) { return byteBuffer.getFloat(); } else if (type == short.class) { return byteBuffer.getShort(); } else if (type == byte.class) { return byteBuffer.get(); } else if (type == char.class) { return byteBuffer.getChar(); } else if (type == double.class) { return byteBuffer.getDouble(); } else if (type == boolean.class) { return byteBuffer.getInt() != 0; } else { throw new RuntimeException("unknown type:" + type); } } else { int address = byteBuffer.getInt(); Object object = EpicNative.getObject(self, address); // Logger.i(TAG, "wrapArgument, address: 0x" + Long.toHexString(address) + ", value:" + object); return object; } } private static Map<Class<?>, String> bridgeMethodMap = new HashMap<>(); static { Class<?>[] primitiveTypes = new Class[]{boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class}; for (Class<?> primitiveType : primitiveTypes) { bridgeMethodMap.put(primitiveType, primitiveType.getName() + "Bridge"); } bridgeMethodMap.put(Object.class, "referenceBridge"); bridgeMethodMap.put(void.class, "voidBridge"); } public static Method getBridgeMethod(Class<?> returnType) { try { final String bridgeMethod = bridgeMethodMap.get(returnType.isPrimitive() ? returnType : Object.class); Logger.i(TAG, "bridge method:" + bridgeMethod + ", map:" + bridgeMethodMap); Method method = Entry.class.getDeclaredMethod(bridgeMethod, int.class, int.class, int.class); method.setAccessible(true); return method; } catch (Throwable e) { throw new RuntimeException("error", e); } } private static int getTypeLength(Class<?> clazz) { if (clazz == long.class || clazz == double.class) { return 8; // double & long are 8 bytes. } else { return 4; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/entry/Entry64.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.entry; import com.taobao.android.dexposed.utility.Logger; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.robv.android.xposed.DexposedBridge; import de.robv.android.xposed.XposedHelpers; import me.weishu.epic.art.Epic; import me.weishu.epic.art.EpicNative; @SuppressWarnings({"unused", "ConstantConditions"}) public class Entry64 { private final static String TAG = "Entry64"; //region ---------------callback--------------- private static int onHookInt(Object artmethod, Object receiver, Object[] args) { return (Integer) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static long onHookLong(Object artmethod, Object receiver, Object[] args) { return (Long) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static double onHookDouble(Object artmethod, Object receiver, Object[] args) { return (Double) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static char onHookChar(Object artmethod, Object receiver, Object[] args) { return (Character) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static short onHookShort(Object artmethod, Object receiver, Object[] args) { return (Short) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static float onHookFloat(Object artmethod, Object receiver, Object[] args) { return (Float) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static Object onHookObject(Object artmethod, Object receiver, Object[] args) { return DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static void onHookVoid(Object artmethod, Object receiver, Object[] args) { DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static boolean onHookBoolean(Object artmethod, Object receiver, Object[] args) { return (Boolean) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static byte onHookByte(Object artmethod, Object receiver, Object[] args) { return (Byte) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } //endregion //region ---------------bridge--------------- private static void voidBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static boolean booleanBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Boolean) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static byte byteBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Byte) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static short shortBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Short) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static char charBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Character) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static int intBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Integer) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static long longBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Long) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static float floatBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Float) referenceBridge(r1, self, struct, x4, x5, x6, x7); } private static double doubleBridge(long r1, long self, long struct, long x4, long x5, long x6, long x7) { return (Double) referenceBridge(r1, self, struct, x4, x5, x6, x7); } //endregion private static Object referenceBridge(long x1, long self, long struct, long x4, long x5, long x6, long x7) { Logger.i(TAG, "enter bridge function."); // struct { // void* sp; // void* r2; // void* r3; // void* sourceMethod // } // sp + 16 = r4 Logger.d(TAG, "self:" + Long.toHexString(self)); final long nativePeer = XposedHelpers.getLongField(Thread.currentThread(), "nativePeer"); Logger.d(TAG, "java thread native peer:" + Long.toHexString(nativePeer)); Logger.d(TAG, "struct:" + Long.toHexString(struct)); final long sp = ByteBuffer.wrap(EpicNative.get(struct, 8)).order(ByteOrder.LITTLE_ENDIAN).getLong(); Logger.d(TAG, "stack:" + sp); final byte[] rr1 = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(x1).array(); final byte[] r2 = EpicNative.get(struct + 8, 8); final byte[] r3 = EpicNative.get(struct + 16, 8); final long sourceMethod = ByteBuffer.wrap(EpicNative.get(struct + 24, 8)).order(ByteOrder.LITTLE_ENDIAN).getLong(); Logger.d(TAG, "sourceMethod:" + Long.toHexString(sourceMethod)); Epic.MethodInfo originMethodInfo = Epic.getMethodInfo(sourceMethod); Logger.d(TAG, "originMethodInfo :" + originMethodInfo); boolean isStatic = originMethodInfo.isStatic; int numberOfArgs = originMethodInfo.paramNumber; Class<?>[] typeOfArgs = originMethodInfo.paramTypes; Object[] arguments = new Object[numberOfArgs]; Object receiver; self = nativePeer; if (isStatic) { receiver = null; do { if (numberOfArgs == 0) break; arguments[0] = wrapArgument(typeOfArgs[0], self, rr1); if (numberOfArgs == 1) break; arguments[1] = wrapArgument(typeOfArgs[1], self, r2); if (numberOfArgs == 2) break; arguments[2] = wrapArgument(typeOfArgs[2], self, r3); if (numberOfArgs == 3) break; arguments[3] = wrapArgument(typeOfArgs[3], self, x4); if (numberOfArgs == 4) break; arguments[4] = wrapArgument(typeOfArgs[4], self, x5); if (numberOfArgs == 5) break; arguments[5] = wrapArgument(typeOfArgs[5], self, x6); if (numberOfArgs == 6) break; arguments[6] = wrapArgument(typeOfArgs[6], self, x7); if (numberOfArgs == 7) break; for (int i = 7; i < numberOfArgs; i++) { byte[] argsInStack = EpicNative.get(sp + i * 8 + 8, 8); arguments[i] = wrapArgument(typeOfArgs[i], self, argsInStack); } } while (false); } else { receiver = EpicNative.getObject(self, x1); //Logger.i(TAG, "this :" + receiver); do { if (numberOfArgs == 0) break; arguments[0] = wrapArgument(typeOfArgs[0], self, r2); if (numberOfArgs == 1) break; arguments[1] = wrapArgument(typeOfArgs[1], self, r3); if (numberOfArgs == 2) break; arguments[2] = wrapArgument(typeOfArgs[2], self, x4); if (numberOfArgs == 3) break; arguments[3] = wrapArgument(typeOfArgs[3], self, x5); if (numberOfArgs == 4) break; arguments[4] = wrapArgument(typeOfArgs[4], self, x6); if (numberOfArgs == 5) break; arguments[5] = wrapArgument(typeOfArgs[5], self, x7); if (numberOfArgs == 6) break; for (int i = 6; i < numberOfArgs; i++) { byte[] argsInStack = EpicNative.get(sp + i * 8 + 16, 8); arguments[i] = wrapArgument(typeOfArgs[i], self, argsInStack); } } while (false); } Logger.i(TAG, "arguments:" + Arrays.toString(arguments)); Class<?> returnType = originMethodInfo.returnType; Object artMethod = originMethodInfo.method; Logger.d(TAG, "leave bridge function"); if (returnType == void.class) { onHookVoid(artMethod, receiver, arguments); return 0; } else if (returnType == char.class) { return onHookChar(artMethod, receiver, arguments); } else if (returnType == byte.class) { return onHookByte(artMethod, receiver, arguments); } else if (returnType == short.class) { return onHookShort(artMethod, receiver, arguments); } else if (returnType == int.class) { return onHookInt(artMethod, receiver, arguments); } else if (returnType == long.class) { return onHookLong(artMethod, receiver, arguments); } else if (returnType == float.class) { return onHookFloat(artMethod, receiver, arguments); } else if (returnType == double.class) { return onHookDouble(artMethod, receiver, arguments); } else if (returnType == boolean.class) { return onHookBoolean(artMethod, receiver, arguments); } else { return onHookObject(artMethod, receiver, arguments); } } private static Object wrapArgument(Class<?> type, long self, long value) { return wrapArgument(type, self, ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array()); } private static Object wrapArgument(Class<?> type, long self, byte[] value) { final ByteBuffer byteBuffer = ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN); if (type.isPrimitive()) { if (type == int.class) { return byteBuffer.getInt(); } else if (type == long.class) { return byteBuffer.getLong(); } else if (type == float.class) { return byteBuffer.getFloat(); } else if (type == short.class) { return byteBuffer.getShort(); } else if (type == byte.class) { return byteBuffer.get(); } else if (type == char.class) { return byteBuffer.getChar(); } else if (type == double.class) { return byteBuffer.getDouble(); } else if (type == boolean.class) { return byteBuffer.getInt() == 0; } else { throw new RuntimeException("unknown type:" + type); } } else { long address = byteBuffer.getLong(); Object object = EpicNative.getObject(self, address); //Logger.i(TAG, "wrapArgument, address: 0x" + Long.toHexString(address) + ", value:" + object); return object; } } private static Map<Class<?>, String> bridgeMethodMap = new HashMap<>(); static { Class<?>[] primitiveTypes = new Class[]{boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class}; for (Class<?> primitiveType : primitiveTypes) { bridgeMethodMap.put(primitiveType, primitiveType.getName() + "Bridge"); } bridgeMethodMap.put(void.class, "voidBridge"); bridgeMethodMap.put(Object.class, "referenceBridge"); } public static Method getBridgeMethod(Class<?> returnType) { try { final String bridgeMethod = bridgeMethodMap.get(returnType.isPrimitive() ? returnType : Object.class); Logger.d(TAG, "bridge method:" + bridgeMethod + ", map:" + bridgeMethodMap); Method method = Entry64.class.getDeclaredMethod(bridgeMethod, long.class, long.class, long.class, long.class, long.class, long.class, long.class); method.setAccessible(true); return method; } catch (Throwable e) { throw new RuntimeException("error", e); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/entry/Entry64_2.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.entry; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.robv.android.xposed.DexposedBridge; import de.robv.android.xposed.XposedHelpers; import me.weishu.epic.art.Epic; import me.weishu.epic.art.EpicNative; @SuppressWarnings({"unused", "ConstantConditions"}) public class Entry64_2 { private final static String TAG = "Entry64"; //region ---------------callback--------------- private static int onHookInt(Object artmethod, Object receiver, Object[] args) { return (Integer) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static long onHookLong(Object artmethod, Object receiver, Object[] args) { return (Long) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static double onHookDouble(Object artmethod, Object receiver, Object[] args) { return (Double) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static char onHookChar(Object artmethod, Object receiver, Object[] args) { return (Character) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static short onHookShort(Object artmethod, Object receiver, Object[] args) { return (Short) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static float onHookFloat(Object artmethod, Object receiver, Object[] args) { return (Float) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static Object onHookObject(Object artmethod, Object receiver, Object[] args) { return DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static void onHookVoid(Object artmethod, Object receiver, Object[] args) { DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static boolean onHookBoolean(Object artmethod, Object receiver, Object[] args) { return (Boolean) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } private static byte onHookByte(Object artmethod, Object receiver, Object[] args) { return (Byte) DexposedBridge.handleHookedArtMethod(artmethod, receiver, args); } //endregion //region ---------------voidBridge--------------- private static void voidBridge(long x1, long struct) { referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static void voidBridge(long x1, long struct, long x3) { referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static void voidBridge(long x1, long struct, long x3, long x4) { referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static void voidBridge(long r1, long struct, long x3, long x4, long x5) { referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static void voidBridge(long r1, long struct, long x3, long x4, long x5, long x6) { referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static void voidBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------booleanBridge--------------- private static boolean booleanBridge(long x1, long struct) { return (Boolean) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static boolean booleanBridge(long x1, long struct, long x3) { return (Boolean) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static boolean booleanBridge(long x1, long struct, long x3, long x4) { return (Boolean) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static boolean booleanBridge(long r1, long struct, long x3, long x4, long x5) { return (Boolean) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static boolean booleanBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Boolean) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static boolean booleanBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Boolean) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------byteBridge--------------- private static byte byteBridge(long x1, long struct) { return (Byte) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static byte byteBridge(long x1, long struct, long x3) { return (Byte) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static byte byteBridge(long x1, long struct, long x3, long x4) { return (Byte) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static byte byteBridge(long r1, long struct, long x3, long x4, long x5) { return (Byte) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static byte byteBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Byte) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static byte byteBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Byte) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------shortBridge--------------- private static short shortBridge(long x1, long struct) { return (Short) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static short shortBridge(long x1, long struct, long x3) { return (Short) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static short shortBridge(long x1, long struct, long x3, long x4) { return (Short) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static short shortBridge(long r1, long struct, long x3, long x4, long x5) { return (Short) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static short shortBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Short) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static short shortBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Short) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------charBridge--------------- private static char charBridge(long x1, long struct) { return (Character) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static char charBridge(long x1, long struct, long x3) { return (Character) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static char charBridge(long x1, long struct, long x3, long x4) { return (Character) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static char charBridge(long r1, long struct, long x3, long x4, long x5) { return (Character) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static char charBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Character) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static char charBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Character) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------intBridge--------------- private static int intBridge(long x1, long struct) { return (Integer) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static int intBridge(long x1, long struct, long x3) { return (Integer) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static int intBridge(long x1, long struct, long x3, long x4) { return (Integer) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static int intBridge(long r1, long struct, long x3, long x4, long x5) { return (Integer) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static int intBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Integer) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static int intBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Integer) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------longBridge--------------- private static long longBridge(long x1, long struct) { return (Long) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static long longBridge(long x1, long struct, long x3) { return (Long) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static long longBridge(long x1, long struct, long x3, long x4) { return (Long) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static long longBridge(long r1, long struct, long x3, long x4, long x5) { return (Long) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static long longBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Long) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static long longBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Long) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------floatBridge--------------- private static float floatBridge(long x1, long struct) { return (Float) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static float floatBridge(long x1, long struct, long x3) { return (Float) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static float floatBridge(long x1, long struct, long x3, long x4) { return (Float) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static float floatBridge(long r1, long struct, long x3, long x4, long x5) { return (Float) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static float floatBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Float) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static float floatBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Float) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------doubleBridge--------------- private static double doubleBridge(long x1, long struct) { return (Double) referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static double doubleBridge(long x1, long struct, long x3) { return (Double) referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static double doubleBridge(long x1, long struct, long x3, long x4) { return (Double) referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static double doubleBridge(long r1, long struct, long x3, long x4, long x5) { return (Double) referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static double doubleBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return (Double) referenceBridge(r1, struct, x3, x4, x5, x6, 0); } private static double doubleBridge(long r1, long struct, long x3, long x4, long x5, long x6, long x7) { return (Double) referenceBridge(r1, struct, x3, x4, x5, x6, x7); } //endregion //region ---------------referenceBridge--------------- private static Object referenceBridge(long x1, long struct) { return referenceBridge(x1, struct, 0, 0, 0, 0, 0); } private static Object referenceBridge(long x1, long struct, long x3) { return referenceBridge(x1, struct, x3, 0, 0, 0, 0); } private static Object referenceBridge(long x1, long struct, long x3, long x4) { return referenceBridge(x1, struct, x3, x4, 0, 0, 0); } private static Object referenceBridge(long r1, long struct, long x3, long x4, long x5) { return referenceBridge(r1, struct, x3, x4, x5, 0, 0); } private static Object referenceBridge(long r1, long struct, long x3, long x4, long x5, long x6) { return referenceBridge(r1, struct, x3, x4, x5, x6, 0); } //endregion private static Object referenceBridge(long x1, long struct, long x3, long x4, long x5, long x6, long x7) { Logger.i(TAG, "enter bridge function."); // struct { // void* sp; // void* x2; // void* sourceMethod // } final long self = XposedHelpers.getLongField(Thread.currentThread(), "nativePeer"); Logger.d(TAG, "java thread native peer:" + Long.toHexString(self)); Logger.d(TAG, "struct:" + Long.toHexString(struct)); Logger.d(TAG, "struct:" + Debug.hexdump(EpicNative.get(struct, 24), struct)); final long sp = ByteBuffer.wrap(EpicNative.get(struct, 8)).order(ByteOrder.LITTLE_ENDIAN).getLong(); Logger.d(TAG, "stack:" + sp); final byte[] rr1 = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(x1).array(); final byte[] r2 = EpicNative.get(struct + 8, 8); final long sourceMethod = ByteBuffer.wrap(EpicNative.get(struct + 16, 8)).order(ByteOrder.LITTLE_ENDIAN).getLong(); Logger.d(TAG, "sourceMethod:" + Long.toHexString(sourceMethod)); Epic.MethodInfo originMethodInfo = Epic.getMethodInfo(sourceMethod); Logger.d(TAG, "originMethodInfo :" + originMethodInfo); boolean isStatic = originMethodInfo.isStatic; int numberOfArgs = originMethodInfo.paramNumber; Class<?>[] typeOfArgs = originMethodInfo.paramTypes; Object[] arguments = new Object[numberOfArgs]; Object receiver; if (isStatic) { receiver = null; do { if (numberOfArgs == 0) break; arguments[0] = wrapArgument(typeOfArgs[0], self, rr1); if (numberOfArgs == 1) break; arguments[1] = wrapArgument(typeOfArgs[1], self, r2); if (numberOfArgs == 2) break; arguments[2] = wrapArgument(typeOfArgs[2], self, x3); if (numberOfArgs == 3) break; arguments[3] = wrapArgument(typeOfArgs[3], self, x4); if (numberOfArgs == 4) break; arguments[4] = wrapArgument(typeOfArgs[4], self, x5); if (numberOfArgs == 5) break; arguments[5] = wrapArgument(typeOfArgs[5], self, x6); if (numberOfArgs == 6) break; arguments[6] = wrapArgument(typeOfArgs[6], self, x7); if (numberOfArgs == 7) break; for (int i = 7; i < numberOfArgs; i++) { byte[] argsInStack = EpicNative.get(sp + i * 8 + 8, 8); arguments[i] = wrapArgument(typeOfArgs[i], self, argsInStack); } } while (false); } else { receiver = EpicNative.getObject(self, x1); Logger.i(TAG, "this :" + receiver); do { if (numberOfArgs == 0) break; arguments[0] = wrapArgument(typeOfArgs[0], self, r2); if (numberOfArgs == 1) break; arguments[1] = wrapArgument(typeOfArgs[1], self, x3); if (numberOfArgs == 2) break; arguments[2] = wrapArgument(typeOfArgs[2], self, x4); if (numberOfArgs == 3) break; arguments[3] = wrapArgument(typeOfArgs[3], self, x5); if (numberOfArgs == 4) break; arguments[4] = wrapArgument(typeOfArgs[4], self, x6); if (numberOfArgs == 5) break; arguments[5] = wrapArgument(typeOfArgs[5], self, x7); if (numberOfArgs == 6) break; for (int i = 6; i < numberOfArgs; i++) { byte[] argsInStack = EpicNative.get(sp + i * 8 + 16, 8); arguments[i] = wrapArgument(typeOfArgs[i], self, argsInStack); } } while (false); } Logger.i(TAG, "arguments:" + Arrays.toString(arguments)); Class<?> returnType = originMethodInfo.returnType; Object artMethod = originMethodInfo.method; Logger.d(TAG, "leave bridge function"); if (returnType == void.class) { onHookVoid(artMethod, receiver, arguments); return 0; } else if (returnType == char.class) { return onHookChar(artMethod, receiver, arguments); } else if (returnType == byte.class) { return onHookByte(artMethod, receiver, arguments); } else if (returnType == short.class) { return onHookShort(artMethod, receiver, arguments); } else if (returnType == int.class) { return onHookInt(artMethod, receiver, arguments); } else if (returnType == long.class) { return onHookLong(artMethod, receiver, arguments); } else if (returnType == float.class) { return onHookFloat(artMethod, receiver, arguments); } else if (returnType == double.class) { return onHookDouble(artMethod, receiver, arguments); } else if (returnType == boolean.class) { return onHookBoolean(artMethod, receiver, arguments); } else { return onHookObject(artMethod, receiver, arguments); } } private static Object wrapArgument(Class<?> type, long self, long value) { return wrapArgument(type, self, ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array()); } private static Object wrapArgument(Class<?> type, long self, byte[] value) { final ByteBuffer byteBuffer = ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN); if (type.isPrimitive()) { if (type == int.class) { return byteBuffer.getInt(); } else if (type == long.class) { return byteBuffer.getLong(); } else if (type == float.class) { return byteBuffer.getFloat(); } else if (type == short.class) { return byteBuffer.getShort(); } else if (type == byte.class) { return byteBuffer.get(); } else if (type == char.class) { return byteBuffer.getChar(); } else if (type == double.class) { return byteBuffer.getDouble(); } else if (type == boolean.class) { return byteBuffer.getInt() == 0; } else { throw new RuntimeException("unknown type:" + type); } } else { long address = byteBuffer.getLong(); Object object = EpicNative.getObject(self, address); // Logger.d(TAG, "wrapArgument, address: 0x" + Long.toHexString(address) + ", value:" + object); return object; } } private static Map<Class<?>, String> bridgeMethodMap = new HashMap<>(); static { Class<?>[] primitiveTypes = new Class[]{boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class}; for (Class<?> primitiveType : primitiveTypes) { bridgeMethodMap.put(primitiveType, primitiveType.getName() + "Bridge"); } bridgeMethodMap.put(void.class, "voidBridge"); bridgeMethodMap.put(Object.class, "referenceBridge"); } public static Method getBridgeMethod(Epic.MethodInfo methodInfo) { try { Class<?> returnType = methodInfo.returnType; int paramNumber = methodInfo.isStatic ? methodInfo.paramNumber : methodInfo.paramNumber + 1; Class<?>[] bridgeParamTypes; if (paramNumber <= 2) { paramNumber = 2; } bridgeParamTypes = new Class[paramNumber]; for (int i = 0; i < paramNumber; i++) { bridgeParamTypes[i] = long.class; } final String bridgeMethod = bridgeMethodMap.get(returnType.isPrimitive() ? returnType : Object.class); Logger.d(TAG, "bridge method:" + bridgeMethod + ", map:" + bridgeMethodMap); Method method = Entry64_2.class.getDeclaredMethod(bridgeMethod, bridgeParamTypes); method.setAccessible(true); return method; } catch (Throwable e) { throw new RuntimeException("can not found bridge." , e); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/method/ArtMethod.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.method; import android.os.Build; import android.util.Log; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.NeverCalled; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.Arrays; import de.robv.android.xposed.XposedHelpers; import me.weishu.epic.art.EpicNative; /** * Object stands for a Java Method, may be a constructor or a method. */ public class ArtMethod { private static final String TAG = "ArtMethod"; /** * The address of the Art method. this is not the real memory address of the java.lang.reflect.Method * But the address used by VM which stand for the Java method. * generally, it was the address of art::mirror::ArtMethod. @{link #objectAddress} */ private long address; /** * the origin object if this is a constructor */ private Constructor constructor; /** * the origin object if this is a method; */ private Method method; /** * the origin ArtMethod if this method is a backup of someone, null when this is not backup */ private ArtMethod origin; /** * The size of ArtMethod, usually the java part of ArtMethod may not stand for the whole one * may be some native field is placed in the end of header. */ private static int artMethodSize = -1; private ArtMethod(Constructor constructor) { if (constructor == null) { throw new IllegalArgumentException("constructor can not be null"); } this.constructor = constructor; init(); } private ArtMethod(Method method, long address) { if (method == null) { throw new IllegalArgumentException("method can not be null"); } this.method = method; if (address != -1) { this.address = address; } else { init(); } } private void init() { if (constructor != null) { address = EpicNative.getMethodAddress(constructor); } else { address = EpicNative.getMethodAddress(method); } } public static ArtMethod of(Method method) { return new ArtMethod(method, -1); } public static ArtMethod of(Method method, long address) { return new ArtMethod(method, address); } public static ArtMethod of(Constructor constructor) { return new ArtMethod(constructor); } public ArtMethod backup() { try { // Before Oreo, it is: java.lang.reflect.AbstractMethod // After Oreo, it is: java.lang.reflect.Executable Class<?> abstractMethodClass = Method.class.getSuperclass(); Object executable = this.getExecutable(); ArtMethod artMethod; if (Build.VERSION.SDK_INT < 23) { Class<?> artMethodClass = Class.forName("java.lang.reflect.ArtMethod"); //Get the original artMethod field Field artMethodField = abstractMethodClass.getDeclaredField("artMethod"); if (!artMethodField.isAccessible()) { artMethodField.setAccessible(true); } Object srcArtMethod = artMethodField.get(executable); Constructor<?> constructor = artMethodClass.getDeclaredConstructor(); constructor.setAccessible(true); Object destArtMethod = constructor.newInstance(); //Fill the fields to the new method we created for (Field field : artMethodClass.getDeclaredFields()) { if (!field.isAccessible()) { field.setAccessible(true); } field.set(destArtMethod, field.get(srcArtMethod)); } Method newMethod = Method.class.getConstructor(artMethodClass).newInstance(destArtMethod); newMethod.setAccessible(true); artMethod = ArtMethod.of(newMethod); artMethod.setEntryPointFromQuickCompiledCode(getEntryPointFromQuickCompiledCode()); artMethod.setEntryPointFromJni(getEntryPointFromJni()); } else { Constructor<Method> constructor = Method.class.getDeclaredConstructor(); // we can't use constructor.setAccessible(true); because Google does not like it // AccessibleObject.setAccessible(new AccessibleObject[]{constructor}, true); Field override = AccessibleObject.class.getDeclaredField( Build.VERSION.SDK_INT == Build.VERSION_CODES.M ? "flag" : "override"); override.setAccessible(true); override.set(constructor, true); Method m = constructor.newInstance(); m.setAccessible(true); for (Field field : abstractMethodClass.getDeclaredFields()) { field.setAccessible(true); field.set(m, field.get(executable)); } Field artMethodField = abstractMethodClass.getDeclaredField("artMethod"); artMethodField.setAccessible(true); int artMethodSize = getArtMethodSize(); long memoryAddress = EpicNative.map(artMethodSize); byte[] data = EpicNative.get(address, artMethodSize); EpicNative.put(data, memoryAddress); artMethodField.set(m, memoryAddress); // From Android R, getting method address may involve the jni_id_manager which uses // ids mapping instead of directly returning the method address. During resolving the // id->address mapping, it will assume the art method to be from the "methods_" array // in class. However this address may be out of the range of the methods array. Thus // it will cause a crash during using the method offset to resolve method array. artMethod = ArtMethod.of(m, memoryAddress); } artMethod.makePrivate(); artMethod.setAccessible(true); artMethod.origin = this; // save origin method. return artMethod; } catch (Throwable e) { Log.e(TAG, "backup method error:", e); throw new IllegalStateException("Cannot create backup method from :: " + getExecutable(), e); } } /** * @return is method/constructor accessible */ public boolean isAccessible() { if (constructor != null) { return constructor.isAccessible(); } else { return method.isAccessible(); } } /** * make the constructor or method accessible * @param accessible accessible */ public void setAccessible(boolean accessible) { if (constructor != null) { constructor.setAccessible(accessible); } else { method.setAccessible(accessible); } } /** * get the origin method's name * @return constructor name of method name */ public String getName() { if (constructor != null) { return constructor.getName(); } else { return method.getName(); } } public Class<?> getDeclaringClass() { if (constructor != null) { return constructor.getDeclaringClass(); } else { return method.getDeclaringClass(); } } /** * Force compile the method to avoid interpreter mode. * This is only used above Android N * @return if compile success return true, otherwise false. */ public boolean compile() { if (constructor != null) { return EpicNative.compileMethod(constructor); } else { return EpicNative.compileMethod(method); } } /** * invoke the origin method * @param receiver the receiver * @param args origin method/constructor's parameters * @return origin method's return value. * @throws IllegalAccessException throw if no access, impossible. * @throws InvocationTargetException invoke target error. * @throws InstantiationException throw when the constructor can not create instance. */ public Object invoke(Object receiver, Object... args) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (origin != null) { byte[] currentAddress = EpicNative.get(origin.address, 4); byte[] backupAddress = EpicNative.get(address, 4); if (!Arrays.equals(currentAddress, backupAddress)) { if (Debug.DEBUG) { Logger.i(TAG, "the address of java method was moved by gc, backup it now! origin address: 0x" + Arrays.toString(currentAddress) + " , currentAddress: 0x" + Arrays.toString(backupAddress)); } EpicNative.put(currentAddress, address); return invokeInternal(receiver, args); } else { Logger.i(TAG, "the address is same with last invoke, not moved by gc"); } } } return invokeInternal(receiver, args); } private Object invokeInternal(Object receiver, Object... args) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (constructor != null) { return constructor.newInstance(args); } else { return method.invoke(receiver, args); } } /** * get the modifiers of origin method/constructor * @return the modifiers */ public int getModifiers() { if (constructor != null) { return constructor.getModifiers(); } else { return method.getModifiers(); } } /** * get the parameter type of origin method/constructor * @return the parameter types. */ public Class<?>[] getParameterTypes() { if (constructor != null) { return constructor.getParameterTypes(); } else { return method.getParameterTypes(); } } /** * get the return type of origin method/constructor * @return the return type, if it is a constructor, return Object.class */ public Class<?> getReturnType() { if (constructor != null) { return Object.class; } else { return method.getReturnType(); } } /** * get the exception declared by the method/constructor * @return the array of declared exception. */ public Class<?>[] getExceptionTypes() { if (constructor != null) { return constructor.getExceptionTypes(); } else { return method.getExceptionTypes(); } } public String toGenericString() { if (constructor != null) { return constructor.toGenericString(); } else { return method.toGenericString(); } } /** * @return the origin method/constructor */ public Object getExecutable() { if (constructor != null) { return constructor; } else { return method; } } /** * get the memory address of the inner constructor/method * @return the method address, in general, it was the pointer of art::mirror::ArtMethod */ public long getAddress() { return address; } /** * get the unique identifier of the constructor/method * @return the method identifier */ public String getIdentifier() { // Can we use address, may gc move it?? return String.valueOf(getAddress()); } /** * force set the private flag of the method. */ public void makePrivate() { int accessFlags = getAccessFlags(); accessFlags &= ~Modifier.PUBLIC; accessFlags |= Modifier.PRIVATE; setAccessFlags(accessFlags); } /** * the static method is lazy resolved, when not resolved, the entry point is a trampoline of * a bridge, we can not hook these entry. this method force the static method to be resolved. */ public void ensureResolved() { if (!Modifier.isStatic(getModifiers())) { Logger.d(TAG, "not static, ignore."); return; } try { invoke(null); Logger.d(TAG, "ensure resolved"); } catch (Exception ignored) { // we should never make a successful call. } finally { EpicNative.MakeInitializedClassVisibilyInitialized(); } } /** * The entry point of the quick compiled code. * @return the entry point. */ public long getEntryPointFromQuickCompiledCode() { return Offset.read(address, Offset.ART_QUICK_CODE_OFFSET); } /** * @param pointer_entry_point_from_quick_compiled_code the entry point. */ public void setEntryPointFromQuickCompiledCode(long pointer_entry_point_from_quick_compiled_code) { Offset.write(address, Offset.ART_QUICK_CODE_OFFSET, pointer_entry_point_from_quick_compiled_code); } /** * @return the access flags of the method/constructor, not only stand for the modifiers. */ public int getAccessFlags() { return (int) Offset.read(address, Offset.ART_ACCESS_FLAG_OFFSET); } public void setAccessFlags(int newFlags) { Offset.write(address, Offset.ART_ACCESS_FLAG_OFFSET, newFlags); } public void setEntryPointFromJni(long entryPointFromJni) { Offset.write(address, Offset.ART_JNI_ENTRY_OFFSET, entryPointFromJni); } public long getEntryPointFromJni() { return Offset.read(address, Offset.ART_JNI_ENTRY_OFFSET); } /** * The size of an art::mirror::ArtMethod, we use two rule method to measure the size * @return the size */ public static int getArtMethodSize() { if (artMethodSize > 0) { return artMethodSize; } final Method rule1 = XposedHelpers.findMethodExact(ArtMethod.class, "rule1"); final Method rule2 = XposedHelpers.findMethodExact(ArtMethod.class, "rule2"); final long rule2Address = EpicNative.getMethodAddress(rule2); final long rule1Address = EpicNative.getMethodAddress(rule1); final long size = Math.abs(rule2Address - rule1Address); artMethodSize = (int) size; Logger.d(TAG, "art Method size: " + size); return artMethodSize; } private void rule1() { Log.i(TAG, "do not inline me!!"); } private void rule2() { Log.i(TAG, "do not inline me!!"); } public static long getQuickToInterpreterBridge() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return -1L; } final Method fake = XposedHelpers.findMethodExact(NeverCalled.class, "fake", int.class); return ArtMethod.of(fake).getEntryPointFromQuickCompiledCode(); } public long getFieldOffset() { // searchOffset(address, ) return 0L; } /** * search Offset in memory * @param base base address * @param range search range * @param value search value * @return the first address of value if found */ public static long searchOffset(long base, long range, int value) { final int align = 4; final long step = range / align; for (long i = 0; i < step; i++) { long offset = i * align; final byte[] bytes = EpicNative.memget(base + i * align, align); final int valueInOffset = ByteBuffer.allocate(4).put(bytes).getInt(); if (valueInOffset == value) { return offset; } } return -1; } public static long searchOffset(long base, long range, long value) { final int align = 4; final long step = range / align; for (long i = 0; i < step; i++) { long offset = i * align; final byte[] bytes = EpicNative.memget(base + i * align, align); final long valueInOffset = ByteBuffer.allocate(8).put(bytes).getLong(); if (valueInOffset == value) { return offset; } } return -1; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
EpicJniLib/src/main/java/me/weishu/epic/art/method/Offset.java
Java
/* * Copyright (c) 2017, weishu twsxtd@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.weishu.epic.art.method; import android.os.Build; import com.taobao.android.dexposed.utility.Debug; import com.taobao.android.dexposed.utility.Logger; import com.taobao.android.dexposed.utility.Runtime; import java.nio.ByteBuffer; import java.nio.ByteOrder; import me.weishu.epic.art.EpicNative; /** * The Offset of field in an ArtMethod */ class Offset { private static final String TAG = "Offset"; /** * the offset of the entry point */ static Offset ART_QUICK_CODE_OFFSET; /** * the offset of the access flag */ static Offset ART_ACCESS_FLAG_OFFSET; /** * the offset of a jni entry point */ static Offset ART_JNI_ENTRY_OFFSET; static { initFields(); } private enum BitWidth { DWORD(4), QWORD(8); BitWidth(int width) { this.width = width; } int width; } private long offset; private BitWidth length; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public BitWidth getLength() { return length; } public void setLength(BitWidth length) { this.length = length; } public static long read(long base, Offset offset) { long address = base + offset.offset; byte[] bytes = EpicNative.get(address, offset.length.width); if (offset.length == BitWidth.DWORD) { return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL; } else { return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getLong(); } } public static void write(long base, Offset offset, long value) { long address = base + offset.offset; byte[] bytes; if (offset.length == BitWidth.DWORD) { if (value > 0xFFFFFFFFL) { throw new IllegalStateException("overflow may occur"); } else { bytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) value).array(); } } else { bytes = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array(); } EpicNative.put(bytes, address); } private static void initFields() { ART_QUICK_CODE_OFFSET = new Offset(); ART_ACCESS_FLAG_OFFSET = new Offset(); ART_JNI_ENTRY_OFFSET = new Offset(); ART_ACCESS_FLAG_OFFSET.setLength(Offset.BitWidth.DWORD); final int apiLevel = Build.VERSION.SDK_INT; if (Runtime.is64Bit()) { ART_QUICK_CODE_OFFSET.setLength(Offset.BitWidth.QWORD); ART_JNI_ENTRY_OFFSET.setLength(BitWidth.QWORD); switch (apiLevel) { /*case Build.VERSION_CODES.S: // source: https://android.googlesource.com/platform/art/+/refs/heads/android12-release/runtime/art_method.h ART_QUICK_CODE_OFFSET.setOffset(24); ART_JNI_ENTRY_OFFSET.setOffset(16); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.R:*/ case Build.VERSION_CODES.Q: case Build.VERSION_CODES.P: ART_QUICK_CODE_OFFSET.setOffset(32); ART_JNI_ENTRY_OFFSET.setOffset(24); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.O_MR1: case Build.VERSION_CODES.O: ART_QUICK_CODE_OFFSET.setOffset(40); ART_JNI_ENTRY_OFFSET.setOffset(32); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.N_MR1: case Build.VERSION_CODES.N: ART_QUICK_CODE_OFFSET.setOffset(48); ART_JNI_ENTRY_OFFSET.setOffset(40); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.M: ART_QUICK_CODE_OFFSET.setOffset(48); ART_JNI_ENTRY_OFFSET.setOffset(40); ART_ACCESS_FLAG_OFFSET.setOffset(12); break; case Build.VERSION_CODES.LOLLIPOP_MR1: ART_QUICK_CODE_OFFSET.setOffset(56); ART_JNI_ENTRY_OFFSET.setOffset(44); ART_ACCESS_FLAG_OFFSET.setOffset(20); break; case Build.VERSION_CODES.LOLLIPOP: ART_QUICK_CODE_OFFSET.setOffset(40); ART_QUICK_CODE_OFFSET.setLength(BitWidth.QWORD); ART_JNI_ENTRY_OFFSET.setOffset(32); ART_JNI_ENTRY_OFFSET.setLength(BitWidth.QWORD); ART_ACCESS_FLAG_OFFSET.setOffset(56); break; case Build.VERSION_CODES.KITKAT: ART_QUICK_CODE_OFFSET.setOffset(32); ART_ACCESS_FLAG_OFFSET.setOffset(28); break; default: throw new RuntimeException("API LEVEL: " + apiLevel + " is not supported now : ("); } } else { ART_QUICK_CODE_OFFSET.setLength(Offset.BitWidth.DWORD); ART_JNI_ENTRY_OFFSET.setLength(BitWidth.DWORD); switch (apiLevel) { /*case Build.VERSION_CODES.S: ART_QUICK_CODE_OFFSET.setOffset(20); ART_JNI_ENTRY_OFFSET.setOffset(16); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.R:*/ case Build.VERSION_CODES.Q: case Build.VERSION_CODES.P: ART_QUICK_CODE_OFFSET.setOffset(24); ART_JNI_ENTRY_OFFSET.setOffset(20); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.O_MR1: case Build.VERSION_CODES.O: ART_QUICK_CODE_OFFSET.setOffset(28); ART_JNI_ENTRY_OFFSET.setOffset(24); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.N_MR1: case Build.VERSION_CODES.N: ART_QUICK_CODE_OFFSET.setOffset(32); ART_JNI_ENTRY_OFFSET.setOffset(28); ART_ACCESS_FLAG_OFFSET.setOffset(4); break; case Build.VERSION_CODES.M: ART_QUICK_CODE_OFFSET.setOffset(36); ART_JNI_ENTRY_OFFSET.setOffset(32); ART_ACCESS_FLAG_OFFSET.setOffset(12); break; case Build.VERSION_CODES.LOLLIPOP_MR1: ART_QUICK_CODE_OFFSET.setOffset(44); ART_JNI_ENTRY_OFFSET.setOffset(40); ART_ACCESS_FLAG_OFFSET.setOffset(20); break; case Build.VERSION_CODES.LOLLIPOP: ART_QUICK_CODE_OFFSET.setOffset(40); ART_QUICK_CODE_OFFSET.setLength(BitWidth.QWORD); ART_JNI_ENTRY_OFFSET.setOffset(32); ART_JNI_ENTRY_OFFSET.setLength(BitWidth.QWORD); ART_ACCESS_FLAG_OFFSET.setOffset(56); break; case Build.VERSION_CODES.KITKAT: ART_QUICK_CODE_OFFSET.setOffset(32); ART_ACCESS_FLAG_OFFSET.setOffset(28); break; default: throw new RuntimeException("API LEVEL: " + apiLevel + " is not supported now : ("); } } if (Debug.DEBUG) { Logger.i(TAG, "quick code offset: " + ART_QUICK_CODE_OFFSET.getOffset()); Logger.i(TAG, "access flag offset: " + ART_ACCESS_FLAG_OFFSET.getOffset()); Logger.i(TAG, "jni code offset: " + ART_JNI_ENTRY_OFFSET.getOffset()); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 buildToolsVersion '29.0.0' defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { // uncomment this line to support armeabi // abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } } // change this line to next line to support armeabi by using android-ndk-r16b ndkVersion = '25.0.8775105' // ndkVersion = '16.1.4479499' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" version "3.10.2" } } } configurations { javadocDeps } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.annotation:annotation:1.6.0' javadocDeps 'androidx.annotation:annotation:1.6.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test:runner:1.5.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/androidTest/java/com/tencent/mmkv/MMKVTest.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; import static org.junit.Assert.*; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import androidx.test.InstrumentationRegistry; import java.util.HashSet; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class MMKVTest { static MMKV mmkv; static final String KeyNotExist = "Key_Not_Exist"; static final float Delta = 0.000001f; @BeforeClass public static void setUp() throws Exception { Context appContext = InstrumentationRegistry.getTargetContext(); MMKV.initialize(appContext); mmkv = MMKV.mmkvWithID("unitTest", MMKV.SINGLE_PROCESS_MODE, "UnitTestCryptKey"); } @AfterClass public static void tearDown() throws Exception { mmkv.clearAll(); } @Test public void testBool() { boolean ret = mmkv.encode("bool", true); assertEquals(ret, true); boolean value = mmkv.decodeBool("bool"); assertEquals(value, true); value = mmkv.decodeBool(KeyNotExist); assertEquals(value, false); value = mmkv.decodeBool(KeyNotExist, true); assertEquals(value, true); } @Test public void testInt() { boolean ret = mmkv.encode("int", Integer.MAX_VALUE); assertEquals(ret, true); int value = mmkv.decodeInt("int"); assertEquals(value, Integer.MAX_VALUE); value = mmkv.decodeInt(KeyNotExist); assertEquals(value, 0); value = mmkv.decodeInt(KeyNotExist, -1); assertEquals(value, -1); } @Test public void testLong() { boolean ret = mmkv.encode("long", Long.MAX_VALUE); assertEquals(ret, true); long value = mmkv.decodeLong("long"); assertEquals(value, Long.MAX_VALUE); value = mmkv.decodeLong(KeyNotExist); assertEquals(value, 0); value = mmkv.decodeLong(KeyNotExist, -1); assertEquals(value, -1); } @Test public void testFloat() { boolean ret = mmkv.encode("float", Float.MAX_VALUE); assertEquals(ret, true); float value = mmkv.decodeFloat("float"); assertEquals(value, Float.MAX_VALUE, Delta); value = mmkv.decodeFloat(KeyNotExist); assertEquals(value, 0, Delta); value = mmkv.decodeFloat(KeyNotExist, -1); assertEquals(value, -1, Delta); } @Test public void testDouble() { boolean ret = mmkv.encode("double", Double.MAX_VALUE); assertEquals(ret, true); double value = mmkv.decodeDouble("double"); assertEquals(value, Double.MAX_VALUE, Delta); value = mmkv.decodeDouble(KeyNotExist); assertEquals(value, 0, Delta); value = mmkv.decodeDouble(KeyNotExist, -1); assertEquals(value, -1, Delta); } @Test public void testString() { String str = "Hello 2018 world cup 世界杯"; boolean ret = mmkv.encode("string", str); assertEquals(ret, true); String value = mmkv.decodeString("string"); assertEquals(value, str); value = mmkv.decodeString(KeyNotExist); assertEquals(value, null); value = mmkv.decodeString(KeyNotExist, "Empty"); assertEquals(value, "Empty"); } @Test public void testStringSet() { HashSet<String> set = new HashSet<String>(); set.add("W"); set.add("e"); set.add("C"); set.add("h"); set.add("a"); set.add("t"); boolean ret = mmkv.encode("string_set", set); assertEquals(ret, true); HashSet<String> value = (HashSet<String>) mmkv.decodeStringSet("string_set"); assertEquals(value, set); value = (HashSet<String>) mmkv.decodeStringSet(KeyNotExist); assertEquals(value, null); set = new HashSet<String>(); set.add("W"); value = (HashSet<String>) mmkv.decodeStringSet(KeyNotExist, set); assertEquals(value, set); } @Test public void testBytes() { byte[] bytes = {'m', 'm', 'k', 'v'}; boolean ret = mmkv.encode("bytes", bytes); assertEquals(ret, true); byte[] value = mmkv.decodeBytes("bytes"); assertArrayEquals(value, bytes); } @Test public void testRemove() { boolean ret = mmkv.encode("bool_1", true); ret &= mmkv.encode("int_1", Integer.MIN_VALUE); ret &= mmkv.encode("long_1", Long.MIN_VALUE); ret &= mmkv.encode("float_1", Float.MIN_VALUE); ret &= mmkv.encode("double_1", Double.MIN_VALUE); ret &= mmkv.encode("string_1", "hello"); HashSet<String> set = new HashSet<String>(); set.add("W"); set.add("e"); set.add("C"); set.add("h"); set.add("a"); set.add("t"); ret &= mmkv.encode("string_set_1", set); byte[] bytes = {'m', 'm', 'k', 'v'}; ret &= mmkv.encode("bytes_1", bytes); assertEquals(ret, true); { long count = mmkv.count(); mmkv.removeValueForKey("bool_1"); mmkv.removeValuesForKeys(new String[] {"int_1", "long_1"}); long newCount = mmkv.count(); assertEquals(count, newCount + 3); } boolean bValue = mmkv.decodeBool("bool_1"); assertEquals(bValue, false); int iValue = mmkv.decodeInt("int_1"); assertEquals(iValue, 0); long lValue = mmkv.decodeLong("long_1"); assertEquals(lValue, 0); float fValue = mmkv.decodeFloat("float_1"); assertEquals(fValue, Float.MIN_VALUE, Delta); double dValue = mmkv.decodeDouble("double_1"); assertEquals(dValue, Double.MIN_VALUE, Delta); String sValue = mmkv.decodeString("string_1"); assertEquals(sValue, "hello"); HashSet<String> hashSet = (HashSet<String>) mmkv.decodeStringSet("string_set_1"); assertEquals(hashSet, set); byte[] byteValue = mmkv.decodeBytes("bytes_1"); assertArrayEquals(bytes, byteValue); } @Test public void testIPCUpdateInt() { MMKV mmkv = MMKV.mmkvWithID(MMKVTestService.SharedMMKVID, MMKV.MULTI_PROCESS_MODE); mmkv.encode(MMKVTestService.SharedMMKVKey, 1024); Context appContext = InstrumentationRegistry.getTargetContext(); Intent intent = new Intent(appContext, MMKVTestService.class); intent.putExtra(MMKVTestService.CMD_Key, MMKVTestService.CMD_Update); appContext.startService(intent); SystemClock.sleep(1000 * 3); int value = mmkv.decodeInt(MMKVTestService.SharedMMKVKey); assertEquals(value, 1024 + 1); } @Test public void testIPCLock() { Context appContext = InstrumentationRegistry.getTargetContext(); Intent intent = new Intent(appContext, MMKVTestService.class); intent.putExtra(MMKVTestService.CMD_Key, MMKVTestService.CMD_Lock); appContext.startService(intent); SystemClock.sleep(1000 * 3); MMKV mmkv = MMKV.mmkvWithID(MMKVTestService.SharedMMKVID, MMKV.MULTI_PROCESS_MODE); boolean ret = mmkv.tryLock(); assertEquals(ret, false); intent.putExtra(MMKVTestService.CMD_Key, MMKVTestService.CMD_Kill); appContext.startService(intent); SystemClock.sleep(1000 * 3); ret = mmkv.tryLock(); assertEquals(ret, true); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/androidTest/java/com/tencent/mmkv/MMKVTestService.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.Process; import androidx.annotation.Nullable; public class MMKVTestService extends Service { public static final String SharedMMKVID = "SharedMMKVID"; public static final String SharedMMKVKey = "SharedMMKVKey"; public static final String CMD_Key = "CMD_Key"; public static final String CMD_Update = "CMD_Update"; public static final String CMD_Lock = "CMD_Lock"; public static final String CMD_Kill = "CMD_Kill"; @Override public void onCreate() { super.onCreate(); MMKV.initialize(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { MMKV mmkv = MMKV.mmkvWithID(SharedMMKVID, MMKV.MULTI_PROCESS_MODE); String cmd = intent.getStringExtra(CMD_Key); switch (cmd) { case CMD_Update: int value = mmkv.decodeInt(SharedMMKVKey); value += 1; mmkv.encode(SharedMMKVKey, value); break; case CMD_Lock: mmkv.lock(); break; case CMD_Kill: stopSelf(); break; } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); Process.killProcess(Process.myPid()); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/cpp/flutter-bridge.cpp
C++
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2020 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MMKVPredef.h" #ifndef MMKV_DISABLE_FLUTTER # include "MMKV.h" # include "MMKVLog.h" # include <cstdint> # include <string> using namespace mmkv; using namespace std; namespace mmkv { extern int g_android_api; extern string g_android_tmpDir; } # define MMKV_EXPORT extern "C" __attribute__((visibility("default"))) __attribute__((used)) MMKV_EXPORT void mmkvInitialize_v1(const char *rootDir, const char *cacheDir, int32_t sdkInt, int32_t logLevel) { if (!rootDir) { return; } if (cacheDir) { g_android_tmpDir = string(cacheDir); } g_android_api = sdkInt; #ifdef MMKV_STL_SHARED MMKVInfo("current API level = %d, libc++_shared=%d", g_android_api, MMKV_STL_SHARED); #else MMKVInfo("current API level = %d, libc++_shared=?", g_android_api); #endif MMKV::initializeMMKV(rootDir, (MMKVLogLevel) logLevel); } MMKV_EXPORT void mmkvInitialize(const char *rootDir, int32_t logLevel) { mmkvInitialize_v1(rootDir, nullptr, 0, logLevel); } MMKV_EXPORT void *getMMKVWithID(const char *mmapID, int32_t mode, const char *cryptKey, const char *rootPath) { MMKV *kv = nullptr; if (!mmapID) { return kv; } string str = mmapID; bool done = false; if (cryptKey) { string crypt = cryptKey; if (crypt.length() > 0) { if (rootPath) { string path = rootPath; kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, &path); } else { kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, nullptr); } done = true; } } if (!done) { if (rootPath) { string path = rootPath; kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, nullptr, &path); } else { kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, nullptr, nullptr); } } return kv; } MMKV_EXPORT void *getDefaultMMKV(int32_t mode, const char *cryptKey) { MMKV *kv = nullptr; if (cryptKey) { string crypt = cryptKey; if (crypt.length() > 0) { kv = MMKV::defaultMMKV((MMKVMode) mode, &crypt); } } if (!kv) { kv = MMKV::defaultMMKV((MMKVMode) mode, nullptr); } return kv; } MMKV_EXPORT const char *mmapID(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->mmapID().c_str(); } return nullptr; } MMKV_EXPORT bool encodeBool(void *handle, const char *oKey, bool value) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((bool) value, key); } return false; } MMKV_EXPORT bool encodeBool_v2(void *handle, const char *oKey, bool value, uint32_t expiration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((bool) value, key, expiration); } return false; } MMKV_EXPORT bool decodeBool(void *handle, const char *oKey, bool defaultValue) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->getBool(key, defaultValue); } return defaultValue; } MMKV_EXPORT bool encodeInt32(void *handle, const char *oKey, int32_t value) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((int32_t) value, key); } return false; } MMKV_EXPORT bool encodeInt32_v2(void *handle, const char *oKey, int32_t value, uint32_t expiration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((int32_t) value, key, expiration); } return false; } MMKV_EXPORT int32_t decodeInt32(void *handle, const char *oKey, int32_t defaultValue) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->getInt32(key, defaultValue); } return defaultValue; } MMKV_EXPORT bool encodeInt64(void *handle, const char *oKey, int64_t value) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((int64_t) value, key); } return false; } MMKV_EXPORT bool encodeInt64_v2(void *handle, const char *oKey, int64_t value, uint32_t expiration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((int64_t) value, key, expiration); } return false; } MMKV_EXPORT int64_t decodeInt64(void *handle, const char *oKey, int64_t defaultValue) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->getInt64(key, defaultValue); } return defaultValue; } MMKV_EXPORT bool encodeDouble(void *handle, const char *oKey, double value) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((double) value, key); } return false; } MMKV_EXPORT bool encodeDouble_v2(void *handle, const char *oKey, double value, uint32_t expiration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->set((double) value, key, expiration); } return false; } MMKV_EXPORT double decodeDouble(void *handle, const char *oKey, double defaultValue) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); return kv->getDouble(key, defaultValue); } return defaultValue; } MMKV_EXPORT bool encodeBytes(void *handle, const char *oKey, void *oValue, uint64_t length) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); if (oValue) { auto value = MMBuffer(oValue, static_cast<size_t>(length), MMBufferNoCopy); return kv->set(value, key); } else { kv->removeValueForKey(key); return true; } } return false; } MMKV_EXPORT bool encodeBytes_v2(void *handle, const char *oKey, void *oValue, uint64_t length, uint32_t expiration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); if (oValue) { auto value = MMBuffer(oValue, static_cast<size_t>(length), MMBufferNoCopy); return kv->set(value, key, expiration); } else { kv->removeValueForKey(key); return true; } } return false; } MMKV_EXPORT void *decodeBytes(void *handle, const char *oKey, uint64_t *lengthPtr) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { auto key = string(oKey); mmkv::MMBuffer value; auto hasValue = kv->getBytes(key, value); if (hasValue) { if (value.length() > 0) { if (value.isStoredOnStack()) { auto result = malloc(value.length()); if (result) { memcpy(result, value.getPtr(), value.length()); *lengthPtr = value.length(); } return result; } void *result = value.getPtr(); *lengthPtr = value.length(); value.detach(); return result; } *lengthPtr = 0; // this ptr is intended for checking existence of the value // don't free this ptr return value.getPtr(); } } return nullptr; } # ifndef MMKV_DISABLE_CRYPT MMKV_EXPORT bool reKey(void *handle, char *oKey, uint64_t length) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { if (oKey && length > 0) { string key(oKey, length); return kv->reKey(key); } else { return kv->reKey(string()); } } return false; } MMKV_EXPORT void *cryptKey(void *handle, uint64_t *lengthPtr) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && lengthPtr) { auto cryptKey = kv->cryptKey(); if (cryptKey.length() > 0) { auto ptr = malloc(cryptKey.length()); if (ptr) { memcpy(ptr, cryptKey.data(), cryptKey.length()); *lengthPtr = cryptKey.length(); return ptr; } } } return nullptr; } MMKV_EXPORT void checkReSetCryptKey(void *handle, char *oKey, uint64_t length) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { if (oKey && length > 0) { string key(oKey, length); kv->checkReSetCryptKey(&key); } else { kv->checkReSetCryptKey(nullptr); } } } # endif // MMKV_DISABLE_CRYPT MMKV_EXPORT uint32_t valueSize(void *handle, char *oKey, bool actualSize) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { string key(oKey); auto ret = kv->getValueSize(key, actualSize); return static_cast<uint32_t>(ret); } return 0; } MMKV_EXPORT int32_t writeValueToNB(void *handle, char *oKey, void *pointer, uint32_t size) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { string key(oKey); return kv->writeValueToBuffer(key, pointer, size); } return -1; } MMKV_EXPORT uint64_t allKeys(void *handle, char ***keyArrayPtr, uint32_t **sizeArrayPtr, bool filterExpire) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { auto keys = kv->allKeys(filterExpire); if (!keys.empty()) { auto keyArray = (char **) malloc(keys.size() * sizeof(void *)); auto sizeArray = (uint32_t *) malloc(keys.size() * sizeof(uint32_t *)); if (!keyArray || !sizeArray) { free(keyArray); free(sizeArray); return 0; } *keyArrayPtr = keyArray; *sizeArrayPtr = sizeArray; for (size_t index = 0; index < keys.size(); index++) { auto &key = keys[index]; sizeArray[index] = static_cast<uint32_t>(key.length()); keyArray[index] = (char *) malloc(key.length()); if (keyArray[index]) { memcpy(keyArray[index], key.data(), key.length()); } } } return keys.size(); } return 0; } MMKV_EXPORT bool containsKey(void *handle, char *oKey) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { string key(oKey); return kv->containsKey(key); } return false; } MMKV_EXPORT uint64_t count(void *handle, bool filterExpire) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->count(filterExpire); } return 0; } MMKV_EXPORT uint64_t totalSize(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->totalSize(); } return 0; } MMKV_EXPORT uint64_t actualSize(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->actualSize(); } return 0; } MMKV_EXPORT void removeValueForKey(void *handle, char *oKey) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && oKey) { string key(oKey); kv->removeValueForKey(key); } } MMKV_EXPORT void removeValuesForKeys(void *handle, char **keyArray, uint32_t *sizeArray, uint64_t count) { MMKV *kv = static_cast<MMKV *>(handle); if (kv && keyArray && sizeArray && count > 0) { vector<string> arrKeys; arrKeys.reserve(count); for (uint64_t index = 0; index < count; index++) { if (sizeArray[index] > 0 && keyArray[index]) { arrKeys.emplace_back(keyArray[index], sizeArray[index]); } } if (!arrKeys.empty()) { kv->removeValuesForKeys(arrKeys); } } } MMKV_EXPORT void clearAll(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { kv->clearAll(); } } MMKV_EXPORT void mmkvSync(void *handle, bool sync) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { kv->sync((SyncFlag) sync); } } MMKV_EXPORT void clearMemoryCache(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { kv->clearMemoryCache(); } } MMKV_EXPORT int32_t pageSize() { return static_cast<int32_t>(DEFAULT_MMAP_SIZE); } MMKV_EXPORT const char *version() { return MMKV_VERSION; } MMKV_EXPORT void trim(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { kv->trim(); } } MMKV_EXPORT void mmkvClose(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { kv->close(); } } MMKV_EXPORT void mmkvMemcpy(void *dst, const void *src, uint64_t size) { memcpy(dst, src, size); } MMKV_EXPORT bool backupOne(const char *mmapID, const char *dstDir, const char *rootPath) { if (rootPath) { auto root = string(rootPath); if (root.length() > 0) { return MMKV::backupOneToDirectory(mmapID, dstDir, &root); } } return MMKV::backupOneToDirectory(mmapID, dstDir); } MMKV_EXPORT bool restoreOne(const char *mmapID, const char *srcDir, const char *rootPath) { if (rootPath) { auto root = string(rootPath); if (root.length() > 0) { return MMKV::restoreOneFromDirectory(mmapID, srcDir, &root); } } return MMKV::restoreOneFromDirectory(mmapID, srcDir); } MMKV_EXPORT uint64_t backupAll(const char *dstDir/*, const char *rootPath*/) { // historically Android mistakenly use mmapKey as mmapID // makes everything tricky with customize root /*if (rootPath) { auto root = string(rootPath); if (root.length() > 0) { return MMKV::backupAllToDirectory(dstDir, &root); } }*/ return MMKV::backupAllToDirectory(dstDir); } MMKV_EXPORT uint64_t restoreAll(const char *srcDir/*, const char *rootPath*/) { // historically Android mistakenly use mmapKey as mmapID // makes everything tricky with customize root /*if (rootPath) { auto root = string(rootPath); if (root.length() > 0) { return MMKV::restoreAllFromDirectory(srcDir, &root); } }*/ return MMKV::restoreAllFromDirectory(srcDir); } MMKV_EXPORT bool enableAutoExpire(void *handle, uint32_t expireDuration) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->enableAutoKeyExpire(expireDuration); } return false; } MMKV_EXPORT bool disableAutoExpire(void *handle) { MMKV *kv = static_cast<MMKV *>(handle); if (kv) { return kv->disableAutoKeyExpire(); } return false; } #endif // MMKV_DISABLE_FLUTTER
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/cpp/native-bridge.cpp
C++
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MMKVPredef.h" #ifdef MMKV_ANDROID # include "MMBuffer.h" # include "MMKV.h" # include "MMKVLog.h" # include "MemoryFile.h" # include <cstdint> # include <jni.h> # include <string> using namespace std; using namespace mmkv; static jclass g_cls = nullptr; static jfieldID g_fileID = nullptr; static jmethodID g_callbackOnCRCFailID = nullptr; static jmethodID g_callbackOnFileLengthErrorID = nullptr; static jmethodID g_mmkvLogID = nullptr; static jmethodID g_callbackOnContentChange = nullptr; static JavaVM *g_currentJVM = nullptr; static int registerNativeMethods(JNIEnv *env, jclass cls); extern "C" void internalLogWithLevel(MMKVLogLevel level, const char *filename, const char *func, int line, const char *format, ...); extern MMKVLogLevel g_currentLogLevel; namespace mmkv { static void mmkvLog(MMKVLogLevel level, const char *file, int line, const char *function, const std::string &message); } #define InternalLogError(format, ...) \ internalLogWithLevel(MMKV_NAMESPACE_PREFIX::MMKVLogError, __MMKV_FILE_NAME__, __func__, __LINE__, format, ##__VA_ARGS__) #define InternalLogInfo(format, ...) \ internalLogWithLevel(MMKV_NAMESPACE_PREFIX::MMKVLogInfo, __MMKV_FILE_NAME__, __func__, __LINE__, format, ##__VA_ARGS__) extern "C" JNIEXPORT JNICALL jint JNI_OnLoad(JavaVM *vm, void *reserved) { g_currentJVM = vm; JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } if (g_cls) { env->DeleteGlobalRef(g_cls); } static const char *clsName = "com/tencent/mmkv/MMKV"; jclass instance = env->FindClass(clsName); if (!instance) { MMKVError("fail to locate class: %s", clsName); return -2; } g_cls = reinterpret_cast<jclass>(env->NewGlobalRef(instance)); if (!g_cls) { MMKVError("fail to create global reference for %s", clsName); return -3; } g_mmkvLogID = env->GetStaticMethodID(g_cls, "mmkvLogImp", "(ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;)V"); if (!g_mmkvLogID) { MMKVError("fail to get method id for mmkvLogImp"); } // every code from now on can use InternalLogXXX() int ret = registerNativeMethods(env, g_cls); if (ret != 0) { InternalLogError("fail to register native methods for class %s, ret = %d", clsName, ret); return -4; } g_fileID = env->GetFieldID(g_cls, "nativeHandle", "J"); if (!g_fileID) { InternalLogError("fail to locate fileID"); return -5; } g_callbackOnCRCFailID = env->GetStaticMethodID(g_cls, "onMMKVCRCCheckFail", "(Ljava/lang/String;)I"); if (!g_callbackOnCRCFailID) { InternalLogError("fail to get method id for onMMKVCRCCheckFail"); } g_callbackOnFileLengthErrorID = env->GetStaticMethodID(g_cls, "onMMKVFileLengthError", "(Ljava/lang/String;)I"); if (!g_callbackOnFileLengthErrorID) { InternalLogError("fail to get method id for onMMKVFileLengthError"); } g_callbackOnContentChange = env->GetStaticMethodID(g_cls, "onContentChangedByOuterProcess", "(Ljava/lang/String;)V"); if (!g_callbackOnContentChange) { InternalLogError("fail to get method id for onContentChangedByOuterProcess()"); } // get current API level by accessing android.os.Build.VERSION.SDK_INT jclass versionClass = env->FindClass("android/os/Build$VERSION"); if (versionClass) { jfieldID sdkIntFieldID = env->GetStaticFieldID(versionClass, "SDK_INT", "I"); if (sdkIntFieldID) { g_android_api = env->GetStaticIntField(versionClass, sdkIntFieldID); #ifdef MMKV_STL_SHARED InternalLogInfo("current API level = %d, libc++_shared=%d", g_android_api, MMKV_STL_SHARED); #else InternalLogInfo("current API level = %d, libc++_shared=?", g_android_api); #endif } else { InternalLogError("fail to get field id android.os.Build.VERSION.SDK_INT"); } } else { InternalLogError("fail to get class android.os.Build.VERSION"); } return JNI_VERSION_1_6; } //#define MMKV_JNI extern "C" JNIEXPORT JNICALL # define MMKV_JNI static namespace mmkv { static string jstring2string(JNIEnv *env, jstring str); MMKV_JNI void jniInitialize(JNIEnv *env, jobject obj, jstring rootDir, jstring cacheDir, jint logLevel) { if (!rootDir) { return; } const char *kstr = env->GetStringUTFChars(rootDir, nullptr); if (kstr) { MMKV::initializeMMKV(kstr, (MMKVLogLevel) logLevel); env->ReleaseStringUTFChars(rootDir, kstr); g_android_tmpDir = jstring2string(env, cacheDir); } } MMKV_JNI void jniInitialize_2(JNIEnv *env, jobject obj, jstring rootDir, jstring cacheDir, jint logLevel, jboolean logReDirecting) { if (!rootDir) { return; } const char *kstr = env->GetStringUTFChars(rootDir, nullptr); if (kstr) { auto logHandler = logReDirecting ? mmkvLog : nullptr; MMKV::initializeMMKV(kstr, (MMKVLogLevel) logLevel, logHandler); env->ReleaseStringUTFChars(rootDir, kstr); g_android_tmpDir = jstring2string(env, cacheDir); } } MMKV_JNI void onExit(JNIEnv *env, jobject obj) { MMKV::onExit(); } static MMKV *getMMKV(JNIEnv *env, jobject obj) { jlong handle = env->GetLongField(obj, g_fileID); return reinterpret_cast<MMKV *>(handle); } static string jstring2string(JNIEnv *env, jstring str) { if (str) { const char *kstr = env->GetStringUTFChars(str, nullptr); if (kstr) { string result(kstr); env->ReleaseStringUTFChars(str, kstr); return result; } } return ""; } static jstring string2jstring(JNIEnv *env, const string &str) { return env->NewStringUTF(str.c_str()); } static vector<string> jarray2vector(JNIEnv *env, jobjectArray array) { vector<string> keys; if (array) { jsize size = env->GetArrayLength(array); keys.reserve(size); for (jsize i = 0; i < size; i++) { jstring str = (jstring) env->GetObjectArrayElement(array, i); if (str) { keys.push_back(jstring2string(env, str)); env->DeleteLocalRef(str); } } } return keys; } static jobjectArray vector2jarray(JNIEnv *env, const vector<string> &arr) { jobjectArray result = env->NewObjectArray(arr.size(), env->FindClass("java/lang/String"), nullptr); if (result) { for (size_t index = 0; index < arr.size(); index++) { jstring value = string2jstring(env, arr[index]); env->SetObjectArrayElement(result, index, value); env->DeleteLocalRef(value); } } return result; } static JNIEnv *getCurrentEnv() { if (g_currentJVM) { JNIEnv *currentEnv = nullptr; auto ret = g_currentJVM->GetEnv(reinterpret_cast<void **>(&currentEnv), JNI_VERSION_1_6); if (ret == JNI_OK) { return currentEnv; } else { MMKVError("fail to get current JNIEnv: %d", ret); } } return nullptr; } MMKVRecoverStrategic onMMKVError(const std::string &mmapID, MMKVErrorType errorType) { jmethodID methodID = nullptr; if (errorType == MMKVCRCCheckFail) { methodID = g_callbackOnCRCFailID; } else if (errorType == MMKVFileLength) { methodID = g_callbackOnFileLengthErrorID; } auto currentEnv = getCurrentEnv(); if (currentEnv && methodID) { jstring str = string2jstring(currentEnv, mmapID); auto strategic = currentEnv->CallStaticIntMethod(g_cls, methodID, str); return static_cast<MMKVRecoverStrategic>(strategic); } return OnErrorDiscard; } extern "C" void internalLogWithLevel(MMKVLogLevel level, const char *filename, const char *func, int line, const char *format, ...) { if (level >= g_currentLogLevel) { std::string message; char buffer[16]; va_list args; va_start(args, format); auto length = std::vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); if (length < 0) { // something wrong message = {}; } else if (length < sizeof(buffer)) { message = std::string(buffer, static_cast<unsigned long>(length)); } else { message.resize(static_cast<unsigned long>(length), '\0'); va_start(args, format); std::vsnprintf(const_cast<char *>(message.data()), static_cast<size_t>(length) + 1, format, args); va_end(args); } if (g_cls && g_mmkvLogID) { mmkvLog(level, filename, line, func, message); } else { _MMKVLogWithLevel(level, filename, func, line, message.c_str()); } } } static void mmkvLog(MMKVLogLevel level, const char *file, int line, const char *function, const std::string &message) { auto currentEnv = getCurrentEnv(); if (currentEnv && g_mmkvLogID) { jstring oFile = string2jstring(currentEnv, string(file)); jstring oFunction = string2jstring(currentEnv, string(function)); jstring oMessage = string2jstring(currentEnv, message); int readLevel = level; currentEnv->CallStaticVoidMethod(g_cls, g_mmkvLogID, readLevel, oFile, line, oFunction, oMessage); } } static void onContentChangedByOuterProcess(const std::string &mmapID) { auto currentEnv = getCurrentEnv(); if (currentEnv && g_callbackOnContentChange) { jstring str = string2jstring(currentEnv, mmapID); currentEnv->CallStaticVoidMethod(g_cls, g_callbackOnContentChange, str); } } MMKV_JNI jlong getMMKVWithID(JNIEnv *env, jobject, jstring mmapID, jint mode, jstring cryptKey, jstring rootPath) { MMKV *kv = nullptr; if (!mmapID) { return (jlong) kv; } string str = jstring2string(env, mmapID); bool done = false; if (cryptKey) { string crypt = jstring2string(env, cryptKey); if (crypt.length() > 0) { if (rootPath) { string path = jstring2string(env, rootPath); kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, &path); } else { kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, nullptr); } done = true; } } if (!done) { if (rootPath) { string path = jstring2string(env, rootPath); kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, nullptr, &path); } else { kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, nullptr, nullptr); } } return (jlong) kv; } MMKV_JNI jlong getMMKVWithIDAndSize(JNIEnv *env, jobject obj, jstring mmapID, jint size, jint mode, jstring cryptKey) { MMKV *kv = nullptr; if (!mmapID || size < 0) { return (jlong) kv; } string str = jstring2string(env, mmapID); if (cryptKey) { string crypt = jstring2string(env, cryptKey); if (crypt.length() > 0) { kv = MMKV::mmkvWithID(str, size, (MMKVMode) mode, &crypt); } } if (!kv) { kv = MMKV::mmkvWithID(str, size, (MMKVMode) mode, nullptr); } return (jlong) kv; } MMKV_JNI jlong getDefaultMMKV(JNIEnv *env, jobject obj, jint mode, jstring cryptKey) { MMKV *kv = nullptr; if (cryptKey) { string crypt = jstring2string(env, cryptKey); if (crypt.length() > 0) { kv = MMKV::defaultMMKV((MMKVMode) mode, &crypt); } } if (!kv) { kv = MMKV::defaultMMKV((MMKVMode) mode, nullptr); } return (jlong) kv; } MMKV_JNI jlong getMMKVWithAshmemFD(JNIEnv *env, jobject obj, jstring mmapID, jint fd, jint metaFD, jstring cryptKey) { MMKV *kv = nullptr; if (!mmapID || fd < 0 || metaFD < 0) { return (jlong) kv; } string id = jstring2string(env, mmapID); if (cryptKey) { string crypt = jstring2string(env, cryptKey); if (crypt.length() > 0) { kv = MMKV::mmkvWithAshmemFD(id, fd, metaFD, &crypt); } } if (!kv) { kv = MMKV::mmkvWithAshmemFD(id, fd, metaFD, nullptr); } return (jlong) kv; } MMKV_JNI jstring mmapID(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { return string2jstring(env, kv->mmapID()); } return nullptr; } MMKV_JNI jint ashmemFD(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { return kv->ashmemFD(); } return -1; } MMKV_JNI jint ashmemMetaFD(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { return kv->ashmemMetaFD(); } return -1; } MMKV_JNI jboolean checkProcessMode(JNIEnv *env, jobject, jlong handle) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv) { return kv->checkProcessMode(); } return false; } MMKV_JNI jboolean encodeBool(JNIEnv *env, jobject, jlong handle, jstring oKey, jboolean value) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((bool) value, key); } return (jboolean) false; } MMKV_JNI jboolean encodeBool_2(JNIEnv *env, jobject, jlong handle, jstring oKey, jboolean value, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((bool) value, key, (uint32_t) expiration); } return (jboolean) false; } MMKV_JNI jboolean decodeBool(JNIEnv *env, jobject, jlong handle, jstring oKey, jboolean defaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->getBool(key, defaultValue); } return defaultValue; } MMKV_JNI jboolean encodeInt(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jint value) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((int32_t) value, key); } return (jboolean) false; } MMKV_JNI jboolean encodeInt_2(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jint value, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((int32_t) value, key, (uint32_t) expiration); } return (jboolean) false; } MMKV_JNI jint decodeInt(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jint defaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jint) kv->getInt32(key, defaultValue); } return defaultValue; } MMKV_JNI jboolean encodeLong(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jlong value) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((int64_t) value, key); } return (jboolean) false; } MMKV_JNI jboolean encodeLong_2(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jlong value, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((int64_t) value, key, (uint32_t) expiration); } return (jboolean) false; } MMKV_JNI jlong decodeLong(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jlong defaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jlong) kv->getInt64(key, defaultValue); } return defaultValue; } MMKV_JNI jboolean encodeFloat(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jfloat value) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((float) value, key); } return (jboolean) false; } MMKV_JNI jboolean encodeFloat_2(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jfloat value, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((float) value, key, (uint32_t) expiration); } return (jboolean) false; } MMKV_JNI jfloat decodeFloat(JNIEnv *env, jobject, jlong handle, jstring oKey, jfloat defaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jfloat) kv->getFloat(key, defaultValue); } return defaultValue; } MMKV_JNI jboolean encodeDouble(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jdouble value) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((double) value, key); } return (jboolean) false; } MMKV_JNI jboolean encodeDouble_2(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jdouble value, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->set((double) value, key, (uint32_t) expiration); } return (jboolean) false; } MMKV_JNI jdouble decodeDouble(JNIEnv *env, jobject, jlong handle, jstring oKey, jdouble defaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jdouble) kv->getDouble(key, defaultValue); } return defaultValue; } MMKV_JNI jboolean encodeString(JNIEnv *env, jobject, jlong handle, jstring oKey, jstring oValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (oValue) { string value = jstring2string(env, oValue); return (jboolean) kv->set(value, key); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jboolean encodeString_2(JNIEnv *env, jobject, jlong handle, jstring oKey, jstring oValue, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (oValue) { string value = jstring2string(env, oValue); return (jboolean) kv->set(value, key, (uint32_t) expiration); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jstring decodeString(JNIEnv *env, jobject obj, jlong handle, jstring oKey, jstring oDefaultValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); string value; bool hasValue = kv->getString(key, value); if (hasValue) { return string2jstring(env, value); } } return oDefaultValue; } MMKV_JNI jboolean encodeBytes(JNIEnv *env, jobject, jlong handle, jstring oKey, jbyteArray oValue) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (oValue) { MMBuffer value(0); { jsize len = env->GetArrayLength(oValue); void *bufferPtr = env->GetPrimitiveArrayCritical(oValue, nullptr); if (bufferPtr) { value = MMBuffer(bufferPtr, len); env->ReleasePrimitiveArrayCritical(oValue, bufferPtr, JNI_ABORT); } else { MMKVError("fail to get array: %s=%p", key.c_str(), oValue); } } return (jboolean) kv->set(value, key); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jboolean encodeBytes_2(JNIEnv *env, jobject, jlong handle, jstring oKey, jbyteArray oValue, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (oValue) { MMBuffer value(0); { jsize len = env->GetArrayLength(oValue); void *bufferPtr = env->GetPrimitiveArrayCritical(oValue, nullptr); if (bufferPtr) { value = MMBuffer(bufferPtr, len); env->ReleasePrimitiveArrayCritical(oValue, bufferPtr, JNI_ABORT); } else { MMKVError("fail to get array: %s=%p", key.c_str(), oValue); } } return (jboolean) kv->set(value, key, (uint32_t) expiration); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jbyteArray decodeBytes(JNIEnv *env, jobject obj, jlong handle, jstring oKey) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); MMBuffer value = kv->getBytes(key); if (value.length() > 0) { jbyteArray result = env->NewByteArray(value.length()); env->SetByteArrayRegion(result, 0, value.length(), (const jbyte *) value.getPtr()); return result; } } return nullptr; } MMKV_JNI jobjectArray allKeys(JNIEnv *env, jobject instance, jlong handle, jboolean filterExpire) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv) { vector<string> keys = kv->allKeys((bool) filterExpire); return vector2jarray(env, keys); } return nullptr; } MMKV_JNI jboolean containsKey(JNIEnv *env, jobject instance, jlong handle, jstring oKey) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return (jboolean) kv->containsKey(key); } return (jboolean) false; } MMKV_JNI jlong count(JNIEnv *env, jobject instance, jlong handle, jboolean filterExpire) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv) { jlong size = kv->count((bool) filterExpire); return size; } return 0; } MMKV_JNI jlong totalSize(JNIEnv *env, jobject instance, jlong handle) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv) { jlong size = kv->totalSize(); return size; } return 0; } MMKV_JNI jlong actualSize(JNIEnv *env, jobject instance, jlong handle) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv) { jlong size = kv->actualSize(); return size; } return 0; } MMKV_JNI void removeValueForKey(JNIEnv *env, jobject instance, jlong handle, jstring oKey) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); kv->removeValueForKey(key); } } MMKV_JNI void removeValuesForKeys(JNIEnv *env, jobject instance, jobjectArray arrKeys) { MMKV *kv = getMMKV(env, instance); if (kv && arrKeys) { vector<string> keys = jarray2vector(env, arrKeys); if (!keys.empty()) { kv->removeValuesForKeys(keys); } } } MMKV_JNI void clearAll(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->clearAll(); } } MMKV_JNI void sync(JNIEnv *env, jobject instance, jboolean sync) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->sync((SyncFlag) sync); } } MMKV_JNI jboolean isFileValid(JNIEnv *env, jclass type, jstring oMmapID, jstring rootPath) { if (oMmapID) { string mmapID = jstring2string(env, oMmapID); if (!rootPath) { return (jboolean) MMKV::isFileValid(mmapID, nullptr); } else { auto root = jstring2string(env, rootPath); return (jboolean) MMKV::isFileValid(mmapID, &root); } } return (jboolean) false; } MMKV_JNI jboolean encodeSet(JNIEnv *env, jobject, jlong handle, jstring oKey, jobjectArray arrStr) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (arrStr) { vector<string> value = jarray2vector(env, arrStr); return (jboolean) kv->set(value, key); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jboolean encodeSet_2(JNIEnv *env, jobject, jlong handle, jstring oKey, jobjectArray arrStr, jint expiration) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); if (arrStr) { vector<string> value = jarray2vector(env, arrStr); return (jboolean) kv->set(value, key, (uint32_t) expiration); } else { kv->removeValueForKey(key); return (jboolean) true; } } return (jboolean) false; } MMKV_JNI jobjectArray decodeStringSet(JNIEnv *env, jobject, jlong handle, jstring oKey) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); vector<string> value; bool hasValue = kv->getVector(key, value); if (hasValue) { return vector2jarray(env, value); } } return nullptr; } MMKV_JNI void clearMemoryCache(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->clearMemoryCache(); } } MMKV_JNI void lock(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->lock(); } } MMKV_JNI void unlock(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->unlock(); } } MMKV_JNI jboolean tryLock(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { return (jboolean) kv->try_lock(); } return jboolean(false); } MMKV_JNI jint pageSize(JNIEnv *env, jclass type) { return DEFAULT_MMAP_SIZE; } MMKV_JNI jstring version(JNIEnv *env, jclass type) { return string2jstring(env, MMKV_VERSION); } # ifndef MMKV_DISABLE_CRYPT MMKV_JNI jstring cryptKey(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { string cryptKey = kv->cryptKey(); if (cryptKey.length() > 0) { return string2jstring(env, cryptKey); } } return nullptr; } MMKV_JNI jboolean reKey(JNIEnv *env, jobject instance, jstring cryptKey) { MMKV *kv = getMMKV(env, instance); if (kv) { string newKey; if (cryptKey) { newKey = jstring2string(env, cryptKey); } return (jboolean) kv->reKey(newKey); } return (jboolean) false; } MMKV_JNI void checkReSetCryptKey(JNIEnv *env, jobject instance, jstring cryptKey) { MMKV *kv = getMMKV(env, instance); if (kv) { string newKey; if (cryptKey) { newKey = jstring2string(env, cryptKey); } if (!cryptKey || newKey.empty()) { kv->checkReSetCryptKey(nullptr); } else { kv->checkReSetCryptKey(&newKey); } } } # else MMKV_JNI jstring cryptKey(JNIEnv *env, jobject instance) { return nullptr; } # endif // MMKV_DISABLE_CRYPT MMKV_JNI void trim(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->trim(); } } MMKV_JNI void close(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->close(); env->SetLongField(instance, g_fileID, 0); } } MMKV_JNI jint valueSize(JNIEnv *env, jobject, jlong handle, jstring oKey, jboolean actualSize) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return static_cast<jint>(kv->getValueSize(key, (bool) actualSize)); } return 0; } MMKV_JNI void setLogLevel(JNIEnv *env, jclass type, jint level) { MMKV::setLogLevel((MMKVLogLevel) level); } MMKV_JNI void setCallbackHandler(JNIEnv *env, jclass type, jboolean logReDirecting, jboolean hasCallback) { if (logReDirecting == JNI_TRUE) { MMKV::registerLogHandler(mmkvLog); } else { MMKV::unRegisterLogHandler(); } if (hasCallback == JNI_TRUE) { MMKV::registerErrorHandler(onMMKVError); } else { MMKV::unRegisterErrorHandler(); } } MMKV_JNI jlong createNB(JNIEnv *env, jobject instance, jint size) { auto ptr = malloc(static_cast<size_t>(size)); if (!ptr) { MMKVError("fail to create NativeBuffer:%s", strerror(errno)); return 0; } return reinterpret_cast<jlong>(ptr); } MMKV_JNI void destroyNB(JNIEnv *env, jobject instance, jlong pointer, jint size) { free(reinterpret_cast<void *>(pointer)); } MMKV_JNI jint writeValueToNB(JNIEnv *env, jobject instance, jlong handle, jstring oKey, jlong pointer, jint size) { MMKV *kv = reinterpret_cast<MMKV *>(handle); if (kv && oKey) { string key = jstring2string(env, oKey); return kv->writeValueToBuffer(key, reinterpret_cast<void *>(pointer), size); } return -1; } MMKV_JNI void setWantsContentChangeNotify(JNIEnv *env, jclass type, jboolean notify) { if (notify == JNI_TRUE) { MMKV::registerContentChangeHandler(onContentChangedByOuterProcess); } else { MMKV::unRegisterContentChangeHandler(); } } MMKV_JNI void checkContentChanged(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { kv->checkContentChanged(); } } MMKV_JNI jboolean backupOne(JNIEnv *env, jobject obj, jstring mmapID, jstring dstDir, jstring rootPath) { if (rootPath) { string root = jstring2string(env, rootPath); if (root.length() > 0) { return (jboolean) MMKV::backupOneToDirectory(jstring2string(env, mmapID), jstring2string(env, dstDir), &root); } } return (jboolean) MMKV::backupOneToDirectory(jstring2string(env, mmapID), jstring2string(env, dstDir)); } MMKV_JNI jboolean restoreOne(JNIEnv *env, jobject obj, jstring mmapID, jstring srcDir, jstring rootPath) { if (rootPath) { string root = jstring2string(env, rootPath); if (root.length() > 0) { return (jboolean) MMKV::restoreOneFromDirectory(jstring2string(env, mmapID), jstring2string(env, srcDir), &root); } } return (jboolean) MMKV::restoreOneFromDirectory(jstring2string(env, mmapID), jstring2string(env, srcDir)); } MMKV_JNI jlong backupAll(JNIEnv *env, jobject obj, jstring dstDir/*, jstring rootPath*/) { // historically Android mistakenly use mmapKey as mmapID // makes everything tricky with customize root /*if (rootPath) { string root = jstring2string(env, rootPath); if (root.length() > 0) { return (jlong) MMKV::backupAllToDirectory(jstring2string(env, dstDir), &root); } }*/ return (jlong) MMKV::backupAllToDirectory(jstring2string(env, dstDir)); } MMKV_JNI jlong restoreAll(JNIEnv *env, jobject obj, jstring srcDir/*, jstring rootPath*/) { // historically Android mistakenly use mmapKey as mmapID // makes everything tricky with customize root /*if (rootPath) { string root = jstring2string(env, rootPath); if (root.length() > 0) { return (jlong) MMKV::restoreAllFromDirectory(jstring2string(env, srcDir), &root); } }*/ return (jlong) MMKV::restoreAllFromDirectory(jstring2string(env, srcDir)); } MMKV_JNI jboolean enableAutoExpire(JNIEnv *env, jobject instance, jint expireDuration) { MMKV *kv = getMMKV(env, instance); if (kv) { return (jboolean) kv->enableAutoKeyExpire(expireDuration); } return (jboolean) false; } MMKV_JNI jboolean disableAutoExpire(JNIEnv *env, jobject instance) { MMKV *kv = getMMKV(env, instance); if (kv) { return (jboolean) kv->disableAutoKeyExpire(); } return (jboolean) false; } } // namespace mmkv static JNINativeMethod g_methods[] = { {"onExit", "()V", (void *) mmkv::onExit}, {"cryptKey", "()Ljava/lang/String;", (void *) mmkv::cryptKey}, # ifndef MMKV_DISABLE_CRYPT {"reKey", "(Ljava/lang/String;)Z", (void *) mmkv::reKey}, {"checkReSetCryptKey", "(Ljava/lang/String;)V", (void *) mmkv::checkReSetCryptKey}, # endif {"pageSize", "()I", (void *) mmkv::pageSize}, {"mmapID", "()Ljava/lang/String;", (void *) mmkv::mmapID}, {"version", "()Ljava/lang/String;", (void *) mmkv::version}, {"lock", "()V", (void *) mmkv::lock}, {"unlock", "()V", (void *) mmkv::unlock}, {"tryLock", "()Z", (void *) mmkv::tryLock}, {"allKeys", "(JZ)[Ljava/lang/String;", (void *) mmkv::allKeys}, {"removeValuesForKeys", "([Ljava/lang/String;)V", (void *) mmkv::removeValuesForKeys}, {"clearAll", "()V", (void *) mmkv::clearAll}, {"trim", "()V", (void *) mmkv::trim}, {"close", "()V", (void *) mmkv::close}, {"clearMemoryCache", "()V", (void *) mmkv::clearMemoryCache}, {"sync", "(Z)V", (void *) mmkv::sync}, {"isFileValid", "(Ljava/lang/String;Ljava/lang/String;)Z", (void *) mmkv::isFileValid}, {"ashmemFD", "()I", (void *) mmkv::ashmemFD}, {"ashmemMetaFD", "()I", (void *) mmkv::ashmemMetaFD}, //{"jniInitialize", "(Ljava/lang/String;Ljava/lang/String;I)V", (void *) mmkv::jniInitialize}, {"jniInitialize", "(Ljava/lang/String;Ljava/lang/String;IZ)V", (void *) mmkv::jniInitialize_2}, {"getMMKVWithID", "(Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;)J", (void *) mmkv::getMMKVWithID}, {"getMMKVWithIDAndSize", "(Ljava/lang/String;IILjava/lang/String;)J", (void *) mmkv::getMMKVWithIDAndSize}, {"getDefaultMMKV", "(ILjava/lang/String;)J", (void *) mmkv::getDefaultMMKV}, {"getMMKVWithAshmemFD", "(Ljava/lang/String;IILjava/lang/String;)J", (void *) mmkv::getMMKVWithAshmemFD}, {"encodeBool", "(JLjava/lang/String;Z)Z", (void *) mmkv::encodeBool}, {"encodeBool_2", "(JLjava/lang/String;ZI)Z", (void *) mmkv::encodeBool_2}, {"decodeBool", "(JLjava/lang/String;Z)Z", (void *) mmkv::decodeBool}, {"encodeInt", "(JLjava/lang/String;I)Z", (void *) mmkv::encodeInt}, {"encodeInt_2", "(JLjava/lang/String;II)Z", (void *) mmkv::encodeInt_2}, {"decodeInt", "(JLjava/lang/String;I)I", (void *) mmkv::decodeInt}, {"encodeLong", "(JLjava/lang/String;J)Z", (void *) mmkv::encodeLong}, {"encodeLong_2", "(JLjava/lang/String;JI)Z", (void *) mmkv::encodeLong_2}, {"decodeLong", "(JLjava/lang/String;J)J", (void *) mmkv::decodeLong}, {"encodeFloat", "(JLjava/lang/String;F)Z", (void *) mmkv::encodeFloat}, {"encodeFloat_2", "(JLjava/lang/String;FI)Z", (void *) mmkv::encodeFloat_2}, {"decodeFloat", "(JLjava/lang/String;F)F", (void *) mmkv::decodeFloat}, {"encodeDouble", "(JLjava/lang/String;D)Z", (void *) mmkv::encodeDouble}, {"encodeDouble_2", "(JLjava/lang/String;DI)Z", (void *) mmkv::encodeDouble_2}, {"decodeDouble", "(JLjava/lang/String;D)D", (void *) mmkv::decodeDouble}, {"encodeString", "(JLjava/lang/String;Ljava/lang/String;)Z", (void *) mmkv::encodeString}, {"encodeString_2", "(JLjava/lang/String;Ljava/lang/String;I)Z", (void *) mmkv::encodeString_2}, {"decodeString", "(JLjava/lang/String;Ljava/lang/String;)Ljava/lang/String;", (void *) mmkv::decodeString}, {"encodeSet", "(JLjava/lang/String;[Ljava/lang/String;)Z", (void *) mmkv::encodeSet}, {"encodeSet_2", "(JLjava/lang/String;[Ljava/lang/String;I)Z", (void *) mmkv::encodeSet_2}, {"decodeStringSet", "(JLjava/lang/String;)[Ljava/lang/String;", (void *) mmkv::decodeStringSet}, {"encodeBytes", "(JLjava/lang/String;[B)Z", (void *) mmkv::encodeBytes}, {"encodeBytes_2", "(JLjava/lang/String;[BI)Z", (void *) mmkv::encodeBytes_2}, {"decodeBytes", "(JLjava/lang/String;)[B", (void *) mmkv::decodeBytes}, {"containsKey", "(JLjava/lang/String;)Z", (void *) mmkv::containsKey}, {"count", "(JZ)J", (void *) mmkv::count}, {"totalSize", "(J)J", (void *) mmkv::totalSize}, {"actualSize", "(J)J", (void *) mmkv::actualSize}, {"removeValueForKey", "(JLjava/lang/String;)V", (void *) mmkv::removeValueForKey}, {"valueSize", "(JLjava/lang/String;Z)I", (void *) mmkv::valueSize}, {"setLogLevel", "(I)V", (void *) mmkv::setLogLevel}, {"setCallbackHandler", "(ZZ)V", (void *) mmkv::setCallbackHandler}, {"createNB", "(I)J", (void *) mmkv::createNB}, {"destroyNB", "(JI)V", (void *) mmkv::destroyNB}, {"writeValueToNB", "(JLjava/lang/String;JI)I", (void *) mmkv::writeValueToNB}, {"setWantsContentChangeNotify", "(Z)V", (void *) mmkv::setWantsContentChangeNotify}, {"checkContentChangedByOuterProcess", "()V", (void *) mmkv::checkContentChanged}, {"checkProcessMode", "(J)Z", (void *) mmkv::checkProcessMode}, {"backupOneToDirectory", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z", (void *) mmkv::backupOne}, {"restoreOneMMKVFromDirectory", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z", (void *) mmkv::restoreOne}, {"backupAllToDirectory", "(Ljava/lang/String;)J", (void *) mmkv::backupAll}, {"restoreAllFromDirectory", "(Ljava/lang/String;)J", (void *) mmkv::restoreAll}, {"enableAutoKeyExpire", "(I)Z", (void *) mmkv::enableAutoExpire}, {"disableAutoKeyExpire", "()Z", (void *) mmkv::disableAutoExpire}, }; static int registerNativeMethods(JNIEnv *env, jclass cls) { return env->RegisterNatives(cls, g_methods, sizeof(g_methods) / sizeof(g_methods[0])); } #endif // MMKV_ANDROID
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKV.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.net.Uri; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.reflect.Field; import java.util.Arrays; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An highly efficient, reliable, multi-process key-value storage framework. * THE PERFECT drop-in replacement for SharedPreferences and MultiProcessSharedPreferences. */ public class MMKV implements SharedPreferences, SharedPreferences.Editor { private static final EnumMap<MMKVRecoverStrategic, Integer> recoverIndex; private static final EnumMap<MMKVLogLevel, Integer> logLevel2Index; private static final MMKVLogLevel[] index2LogLevel; private static final Set<Long> checkedHandleSet; static { recoverIndex = new EnumMap<>(MMKVRecoverStrategic.class); recoverIndex.put(MMKVRecoverStrategic.OnErrorDiscard, 0); recoverIndex.put(MMKVRecoverStrategic.OnErrorRecover, 1); logLevel2Index = new EnumMap<>(MMKVLogLevel.class); logLevel2Index.put(MMKVLogLevel.LevelDebug, 0); logLevel2Index.put(MMKVLogLevel.LevelInfo, 1); logLevel2Index.put(MMKVLogLevel.LevelWarning, 2); logLevel2Index.put(MMKVLogLevel.LevelError, 3); logLevel2Index.put(MMKVLogLevel.LevelNone, 4); index2LogLevel = new MMKVLogLevel[]{MMKVLogLevel.LevelDebug, MMKVLogLevel.LevelInfo, MMKVLogLevel.LevelWarning, MMKVLogLevel.LevelError, MMKVLogLevel.LevelNone}; checkedHandleSet = new HashSet<Long>(); } /** * The interface for providing a 3rd library loader (the ReLinker https://github.com/KeepSafe/ReLinker, etc). */ public interface LibLoader { void loadLibrary(String libName); } /** * Initialize MMKV with default configuration. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @return The root folder of MMKV, defaults to $(FilesDir)/mmkv. */ public static String initialize(Context context) { String root = context.getFilesDir().getAbsolutePath() + "/mmkv"; MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return initialize(context, root, null, logLevel, null); } /** * Initialize MMKV with customize log level. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param logLevel The log level of MMKV, defaults to {@link MMKVLogLevel#LevelInfo}. * @return The root folder of MMKV, defaults to $(FilesDir)/mmkv. */ public static String initialize(Context context, MMKVLogLevel logLevel) { String root = context.getFilesDir().getAbsolutePath() + "/mmkv"; return initialize(context, root, null, logLevel, null); } /** * Initialize MMKV with a 3rd library loader. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param loader The 3rd library loader (for example, the <a href="https://github.com/KeepSafe/ReLinker">ReLinker</a> . * @return The root folder of MMKV, defaults to $(FilesDir)/mmkv. */ public static String initialize(Context context, LibLoader loader) { String root = context.getFilesDir().getAbsolutePath() + "/mmkv"; MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return initialize(context, root, loader, logLevel, null); } /** * Initialize MMKV with a 3rd library loader, and customize log level. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param loader The 3rd library loader (for example, the <a href="https://github.com/KeepSafe/ReLinker">ReLinker</a> . * @param logLevel The log level of MMKV, defaults to {@link MMKVLogLevel#LevelInfo}. * @return The root folder of MMKV, defaults to $(FilesDir)/mmkv. */ public static String initialize(Context context, LibLoader loader, MMKVLogLevel logLevel) { String root = context.getFilesDir().getAbsolutePath() + "/mmkv"; return initialize(context, root, loader, logLevel, null); } /** * Initialize MMKV with customize root folder. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param rootDir The root folder of MMKV, defaults to $(FilesDir)/mmkv. * @return The root folder of MMKV. */ public static String initialize(Context context, String rootDir) { MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return initialize(context, rootDir, null, logLevel, null); } /** * Initialize MMKV with customize root folder, and log level. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param rootDir The root folder of MMKV, defaults to $(FilesDir)/mmkv. * @param logLevel The log level of MMKV, defaults to {@link MMKVLogLevel#LevelInfo}. * @return The root folder of MMKV. */ public static String initialize(Context context, String rootDir, MMKVLogLevel logLevel) { return initialize(context, rootDir, null, logLevel, null); } /** * Initialize MMKV with customize root folder, and a 3rd library loader. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param rootDir The root folder of MMKV, defaults to $(FilesDir)/mmkv. * @param loader The 3rd library loader (for example, the <a href="https://github.com/KeepSafe/ReLinker">ReLinker</a> . * @return The root folder of MMKV. */ public static String initialize(Context context, String rootDir, LibLoader loader) { MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return initialize(context, rootDir, loader, logLevel, null); } /** * Initialize MMKV with customize settings. * You must call one of the initialize() methods on App startup process before using MMKV. * * @param context The context of Android App, usually from Application. * @param rootDir The root folder of MMKV, defaults to $(FilesDir)/mmkv. * @param loader The 3rd library loader (for example, the <a href="https://github.com/KeepSafe/ReLinker">ReLinker</a> . * @param logLevel The log level of MMKV, defaults to {@link MMKVLogLevel#LevelInfo}. * @return The root folder of MMKV. */ public static String initialize(Context context, String rootDir, LibLoader loader, MMKVLogLevel logLevel) { return initialize(context, rootDir, loader, logLevel, null); } public static String initialize(Context context, String rootDir, LibLoader loader, MMKVLogLevel logLevel, MMKVHandler handler) { // disable process mode in release build // FIXME: Find a better way to getApplicationInfo() without using context. // If any one knows how, you're welcome to make a contribution. if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { disableProcessModeChecker(); } else { enableProcessModeChecker(); } String cacheDir = context.getCacheDir().getAbsolutePath(); gCallbackHandler = handler; if (gCallbackHandler != null && gCallbackHandler.wantLogRedirecting()) { gWantLogReDirecting = true; } String ret = doInitialize(rootDir, cacheDir, loader, logLevel, gWantLogReDirecting); if (gCallbackHandler != null) { setCallbackHandler(gWantLogReDirecting, true); } return ret; } private static String doInitialize(String rootDir, String cacheDir, LibLoader loader, MMKVLogLevel logLevel, boolean wantLogReDirecting) { if (loader != null) { if (BuildConfig.FLAVOR.equals("SharedCpp")) { loader.loadLibrary("c++_shared"); } loader.loadLibrary("mmkv"); } else { if (BuildConfig.FLAVOR.equals("SharedCpp")) { System.loadLibrary("c++_shared"); } System.loadLibrary("mmkv"); } jniInitialize(rootDir, cacheDir, logLevel2Int(logLevel), wantLogReDirecting); MMKV.rootDir = rootDir; return MMKV.rootDir; } /** * @deprecated This method is deprecated due to failing to automatically disable checkProcessMode() without Context. * Use the {@link #initialize(Context, String)} method instead. */ @Deprecated public static String initialize(String rootDir) { MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return doInitialize(rootDir, rootDir + "/.tmp", null, logLevel, false); } /** * @deprecated This method is deprecated due to failing to automatically disable checkProcessMode() without Context. * Use the {@link #initialize(Context, String, MMKVLogLevel)} method instead. */ @Deprecated public static String initialize(String rootDir, MMKVLogLevel logLevel) { return doInitialize(rootDir, rootDir + "/.tmp", null, logLevel, false); } /** * @deprecated This method is deprecated due to failing to automatically disable checkProcessMode() without Context. * Use the {@link #initialize(Context, String, LibLoader)} method instead. */ @Deprecated public static String initialize(String rootDir, LibLoader loader) { MMKVLogLevel logLevel = BuildConfig.DEBUG ? MMKVLogLevel.LevelDebug : MMKVLogLevel.LevelInfo; return doInitialize(rootDir, rootDir + "/.tmp", loader, logLevel, false); } /** * @deprecated This method is deprecated due to failing to automatically disable checkProcessMode() without Context. * Use the {@link #initialize(Context, String, LibLoader, MMKVLogLevel)} method instead. */ @Deprecated public static String initialize(String rootDir, LibLoader loader, MMKVLogLevel logLevel) { return doInitialize(rootDir, rootDir + "/.tmp", loader, logLevel, false); } static private String rootDir = null; /** * @return The root folder of MMKV, defaults to $(FilesDir)/mmkv. */ public static String getRootDir() { return rootDir; } private static int logLevel2Int(MMKVLogLevel level) { int realLevel; switch (level) { case LevelDebug: realLevel = 0; break; case LevelWarning: realLevel = 2; break; case LevelError: realLevel = 3; break; case LevelNone: realLevel = 4; break; case LevelInfo: default: realLevel = 1; break; } return realLevel; } /** * Set the log level of MMKV. * * @param level Defaults to {@link MMKVLogLevel#LevelInfo}. */ public static void setLogLevel(MMKVLogLevel level) { int realLevel = logLevel2Int(level); setLogLevel(realLevel); } /** * Notify MMKV that App is about to exit. It's totally fine not calling it at all. */ public static native void onExit(); /** * Single-process mode. The default mode on an MMKV instance. */ static public final int SINGLE_PROCESS_MODE = 1 << 0; /** * Multi-process mode. * To enable multi-process accessing of an MMKV instance, you must set this mode whenever you getting that instance. */ static public final int MULTI_PROCESS_MODE = 1 << 1; // in case someone mistakenly pass Context.MODE_MULTI_PROCESS static private final int CONTEXT_MODE_MULTI_PROCESS = 1 << 2; static private final int ASHMEM_MODE = 1 << 3; static private final int BACKUP_MODE = 1 << 4; /** * Create an MMKV instance with an unique ID (in single-process mode). * * @param mmapID The unique ID of the MMKV instance. * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithID(String mmapID) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getMMKVWithID(mmapID, SINGLE_PROCESS_MODE, null, null); return checkProcessMode(handle, mmapID, SINGLE_PROCESS_MODE); } /** * Create an MMKV instance in single-process or multi-process mode. * * @param mmapID The unique ID of the MMKV instance. * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithID(String mmapID, int mode) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getMMKVWithID(mmapID, mode, null, null); return checkProcessMode(handle, mmapID, mode); } /** * Create an MMKV instance in customize process mode, with an encryption key. * * @param mmapID The unique ID of the MMKV instance. * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithID(String mmapID, int mode, @Nullable String cryptKey) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getMMKVWithID(mmapID, mode, cryptKey, null); return checkProcessMode(handle, mmapID, mode); } /** * Create an MMKV instance in customize folder. * * @param mmapID The unique ID of the MMKV instance. * @param rootPath The folder of the MMKV instance, defaults to $(FilesDir)/mmkv. * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithID(String mmapID, String rootPath) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getMMKVWithID(mmapID, SINGLE_PROCESS_MODE, null, rootPath); return checkProcessMode(handle, mmapID, SINGLE_PROCESS_MODE); } /** * Create an MMKV instance with customize settings all in one. * * @param mmapID The unique ID of the MMKV instance. * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @param rootPath The folder of the MMKV instance, defaults to $(FilesDir)/mmkv. * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithID(String mmapID, int mode, @Nullable String cryptKey, String rootPath) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getMMKVWithID(mmapID, mode, cryptKey, rootPath); return checkProcessMode(handle, mmapID, mode); } /** * Get an backed-up MMKV instance with customize settings all in one. * * @param mmapID The unique ID of the MMKV instance. * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @param rootPath The backup folder of the MMKV instance. * @throws RuntimeException if there's an runtime error. */ public static MMKV backedUpMMKVWithID(String mmapID, int mode, @Nullable String cryptKey, String rootPath) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } mode |= BACKUP_MODE; long handle = getMMKVWithID(mmapID, mode, cryptKey, rootPath); return checkProcessMode(handle, mmapID, mode); } /** * Create an MMKV instance base on Anonymous Shared Memory, aka not synced to any disk files. * * @param context The context of Android App, usually from Application. * @param mmapID The unique ID of the MMKV instance. * @param size The maximum size of the underlying Anonymous Shared Memory. * Anonymous Shared Memory on Android can't grow dynamically, must set an appropriate size on creation. * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @throws RuntimeException if there's an runtime error. */ public static MMKV mmkvWithAshmemID(Context context, String mmapID, int size, int mode, @Nullable String cryptKey) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } String processName = MMKVContentProvider.getProcessNameByPID(context, android.os.Process.myPid()); if (processName == null || processName.length() == 0) { String message = "process name detect fail, try again later"; simpleLog(MMKVLogLevel.LevelError, message); throw new IllegalStateException(message); } if (processName.contains(":")) { Uri uri = MMKVContentProvider.contentUri(context); if (uri == null) { String message = "MMKVContentProvider has invalid authority"; simpleLog(MMKVLogLevel.LevelError, message); throw new IllegalStateException(message); } simpleLog(MMKVLogLevel.LevelInfo, "getting parcelable mmkv in process, Uri = " + uri); Bundle extras = new Bundle(); extras.putInt(MMKVContentProvider.KEY_SIZE, size); extras.putInt(MMKVContentProvider.KEY_MODE, mode); if (cryptKey != null) { extras.putString(MMKVContentProvider.KEY_CRYPT, cryptKey); } ContentResolver resolver = context.getContentResolver(); Bundle result = resolver.call(uri, MMKVContentProvider.FUNCTION_NAME, mmapID, extras); if (result != null) { result.setClassLoader(ParcelableMMKV.class.getClassLoader()); ParcelableMMKV parcelableMMKV = result.getParcelable(MMKVContentProvider.KEY); if (parcelableMMKV != null) { MMKV mmkv = parcelableMMKV.toMMKV(); if (mmkv != null) { simpleLog(MMKVLogLevel.LevelInfo, mmkv.mmapID() + " fd = " + mmkv.ashmemFD() + ", meta fd = " + mmkv.ashmemMetaFD()); return mmkv; } } } } simpleLog(MMKVLogLevel.LevelInfo, "getting mmkv in main process"); mode = mode | ASHMEM_MODE; long handle = getMMKVWithIDAndSize(mmapID, size, mode, cryptKey); if (handle != 0) { return new MMKV(handle); } throw new IllegalStateException("Fail to create an Ashmem MMKV instance [" + mmapID + "]"); } /** * Create the default MMKV instance in single-process mode. * * @throws RuntimeException if there's an runtime error. */ public static MMKV defaultMMKV() throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getDefaultMMKV(SINGLE_PROCESS_MODE, null); return checkProcessMode(handle, "DefaultMMKV", SINGLE_PROCESS_MODE); } /** * Create the default MMKV instance in customize process mode, with an encryption key. * * @param mode The process mode of the MMKV instance, defaults to {@link #SINGLE_PROCESS_MODE}. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @throws RuntimeException if there's an runtime error. */ public static MMKV defaultMMKV(int mode, @Nullable String cryptKey) throws RuntimeException { if (rootDir == null) { throw new IllegalStateException("You should Call MMKV.initialize() first."); } long handle = getDefaultMMKV(mode, cryptKey); return checkProcessMode(handle, "DefaultMMKV", mode); } private static MMKV checkProcessMode(long handle, String mmapID, int mode) throws RuntimeException { if (handle == 0) { throw new RuntimeException("Fail to create an MMKV instance [" + mmapID + "] in JNI"); } if (!isProcessModeCheckerEnabled) { return new MMKV(handle); } synchronized (checkedHandleSet) { if (!checkedHandleSet.contains(handle)) { if (!checkProcessMode(handle)) { String message; if (mode == SINGLE_PROCESS_MODE) { message = "Opening a multi-process MMKV instance [" + mmapID + "] with SINGLE_PROCESS_MODE!"; } else { message = "Opening an MMKV instance [" + mmapID + "] with MULTI_PROCESS_MODE, "; message += "while it's already been opened with SINGLE_PROCESS_MODE by someone somewhere else!"; } throw new IllegalArgumentException(message); } checkedHandleSet.add(handle); } } return new MMKV(handle); } // Enable checkProcessMode() when initializing an MMKV instance, it's automatically enabled on debug build. private static boolean isProcessModeCheckerEnabled = true; /** * Manually enable the process mode checker. * By default, it's automatically enabled in DEBUG build, and disabled in RELEASE build. * If it's enabled, MMKV will throw exceptions when an MMKV instance is created with mismatch process mode. */ public static void enableProcessModeChecker() { synchronized (checkedHandleSet) { isProcessModeCheckerEnabled = true; } Log.i("MMKV", "Enable checkProcessMode()"); } /** * Manually disable the process mode checker. * By default, it's automatically enabled in DEBUG build, and disabled in RELEASE build. * If it's enabled, MMKV will throw exceptions when an MMKV instance is created with mismatch process mode. */ public static void disableProcessModeChecker() { synchronized (checkedHandleSet) { isProcessModeCheckerEnabled = false; } Log.i("MMKV", "Disable checkProcessMode()"); } /** * @return The encryption key (no more than 16 bytes). */ @Nullable public native String cryptKey(); /** * Transform plain text into encrypted text, or vice versa by passing a null encryption key. * You can also change existing crypt key with a different cryptKey. * * @param cryptKey The new encryption key (no more than 16 bytes). * @return True if success, otherwise False. */ public native boolean reKey(@Nullable String cryptKey); /** * Just reset the encryption key (will not encrypt or decrypt anything). * Usually you should call this method after another process has {@link #reKey(String)} the multi-process MMKV instance. * * @param cryptKey The new encryption key (no more than 16 bytes). */ public native void checkReSetCryptKey(@Nullable String cryptKey); /** * @return The device's memory page size. */ public static native int pageSize(); /** * @return The version of MMKV. */ public static native String version(); /** * @return The unique ID of the MMKV instance. */ public native String mmapID(); /** * Exclusively inter-process lock the MMKV instance. * It will block and wait until it successfully locks the file. * It will make no effect if the MMKV instance is created with {@link #SINGLE_PROCESS_MODE}. */ public native void lock(); /** * Exclusively inter-process unlock the MMKV instance. * It will make no effect if the MMKV instance is created with {@link #SINGLE_PROCESS_MODE}. */ public native void unlock(); /** * Try exclusively inter-process lock the MMKV instance. * It will not block if the file has already been locked by another process. * It will make no effect if the MMKV instance is created with {@link #SINGLE_PROCESS_MODE}. * * @return True if successfully locked, otherwise return immediately with False. */ public native boolean tryLock(); public boolean encode(String key, boolean value) { return encodeBool(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, boolean value, int expireDurationInSecond) { return encodeBool_2(nativeHandle, key, value, expireDurationInSecond); } public boolean decodeBool(String key) { return decodeBool(nativeHandle, key, false); } public boolean decodeBool(String key, boolean defaultValue) { return decodeBool(nativeHandle, key, defaultValue); } public boolean encode(String key, int value) { return encodeInt(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, int value, int expireDurationInSecond) { return encodeInt_2(nativeHandle, key, value, expireDurationInSecond); } public int decodeInt(String key) { return decodeInt(nativeHandle, key, 0); } public int decodeInt(String key, int defaultValue) { return decodeInt(nativeHandle, key, defaultValue); } public boolean encode(String key, long value) { return encodeLong(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, long value, int expireDurationInSecond) { return encodeLong_2(nativeHandle, key, value, expireDurationInSecond); } public long decodeLong(String key) { return decodeLong(nativeHandle, key, 0); } public long decodeLong(String key, long defaultValue) { return decodeLong(nativeHandle, key, defaultValue); } public boolean encode(String key, float value) { return encodeFloat(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, float value, int expireDurationInSecond) { return encodeFloat_2(nativeHandle, key, value, expireDurationInSecond); } public float decodeFloat(String key) { return decodeFloat(nativeHandle, key, 0); } public float decodeFloat(String key, float defaultValue) { return decodeFloat(nativeHandle, key, defaultValue); } public boolean encode(String key, double value) { return encodeDouble(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, double value, int expireDurationInSecond) { return encodeDouble_2(nativeHandle, key, value, expireDurationInSecond); } public double decodeDouble(String key) { return decodeDouble(nativeHandle, key, 0); } public double decodeDouble(String key, double defaultValue) { return decodeDouble(nativeHandle, key, defaultValue); } public boolean encode(String key, @Nullable String value) { return encodeString(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, @Nullable String value, int expireDurationInSecond) { return encodeString_2(nativeHandle, key, value, expireDurationInSecond); } @Nullable public String decodeString(String key) { return decodeString(nativeHandle, key, null); } @Nullable public String decodeString(String key, @Nullable String defaultValue) { return decodeString(nativeHandle, key, defaultValue); } public boolean encode(String key, @Nullable Set<String> value) { return encodeSet(nativeHandle, key, (value == null) ? null : value.toArray(new String[0])); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, @Nullable Set<String> value, int expireDurationInSecond) { return encodeSet_2(nativeHandle, key, (value == null) ? null : value.toArray(new String[0]), expireDurationInSecond); } @Nullable public Set<String> decodeStringSet(String key) { return decodeStringSet(key, null); } @Nullable public Set<String> decodeStringSet(String key, @Nullable Set<String> defaultValue) { return decodeStringSet(key, defaultValue, HashSet.class); } @SuppressWarnings("unchecked") @Nullable public Set<String> decodeStringSet(String key, @Nullable Set<String> defaultValue, Class<? extends Set> cls) { String[] result = decodeStringSet(nativeHandle, key); if (result == null) { return defaultValue; } Set<String> a; try { a = cls.newInstance(); } catch (IllegalAccessException e) { return defaultValue; } catch (InstantiationException e) { return defaultValue; } a.addAll(Arrays.asList(result)); return a; } public boolean encode(String key, @Nullable byte[] value) { return encodeBytes(nativeHandle, key, value); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, @Nullable byte[] value, int expireDurationInSecond) { return encodeBytes_2(nativeHandle, key, value, expireDurationInSecond); } @Nullable public byte[] decodeBytes(String key) { return decodeBytes(key, null); } @Nullable public byte[] decodeBytes(String key, @Nullable byte[] defaultValue) { byte[] ret = decodeBytes(nativeHandle, key); return (ret != null) ? ret : defaultValue; } private static final HashMap<String, Parcelable.Creator<?>> mCreators = new HashMap<>(); private byte[] getParcelableByte(@NonNull Parcelable value) { Parcel source = Parcel.obtain(); value.writeToParcel(source, 0); byte[] bytes = source.marshall(); source.recycle(); return bytes; } public boolean encode(String key, @Nullable Parcelable value) { if (value == null) { return encodeBytes(nativeHandle, key, null); } byte[] bytes = getParcelableByte(value); return encodeBytes(nativeHandle, key, bytes); } /** * Set value with customize expiration in sections. * * @param expireDurationInSecond override the default duration, {@link #ExpireNever} (0) means never expire. */ public boolean encode(String key, @Nullable Parcelable value, int expireDurationInSecond) { if (value == null) { return encodeBytes_2(nativeHandle, key, null, expireDurationInSecond); } byte[] bytes = getParcelableByte(value); return encodeBytes_2(nativeHandle, key, bytes, expireDurationInSecond); } @SuppressWarnings("unchecked") @Nullable public <T extends Parcelable> T decodeParcelable(String key, Class<T> tClass) { return decodeParcelable(key, tClass, null); } @SuppressWarnings("unchecked") @Nullable public <T extends Parcelable> T decodeParcelable(String key, Class<T> tClass, @Nullable T defaultValue) { if (tClass == null) { return defaultValue; } byte[] bytes = decodeBytes(nativeHandle, key); if (bytes == null) { return defaultValue; } Parcel source = Parcel.obtain(); source.unmarshall(bytes, 0, bytes.length); source.setDataPosition(0); try { String name = tClass.toString(); Parcelable.Creator<T> creator; synchronized (mCreators) { creator = (Parcelable.Creator<T>) mCreators.get(name); if (creator == null) { Field f = tClass.getField("CREATOR"); creator = (Parcelable.Creator<T>) f.get(null); if (creator != null) { mCreators.put(name, creator); } } } if (creator != null) { return creator.createFromParcel(source); } else { throw new Exception("Parcelable protocol requires a " + "non-null static Parcelable.Creator object called " + "CREATOR on class " + name); } } catch (Exception e) { simpleLog(MMKVLogLevel.LevelError, e.toString()); } finally { source.recycle(); } return defaultValue; } /** * Get the actual size consumption of the key's value. * Note: might be a little bigger than value's length. * * @param key The key of the value. */ public int getValueSize(String key) { return valueSize(nativeHandle, key, false); } /** * Get the actual size of the key's value. String's length or byte[]'s length, etc. * * @param key The key of the value. */ public int getValueActualSize(String key) { return valueSize(nativeHandle, key, true); } /** * Check whether or not MMKV contains the key. * * @param key The key of the value. */ public boolean containsKey(String key) { return containsKey(nativeHandle, key); } /** * @return All the keys. */ @Nullable public String[] allKeys() { return allKeys(nativeHandle, false); } /** * @return All non-expired keys. Note that this call has costs. */ @Nullable public String[] allNonExpireKeys() { return allKeys(nativeHandle, true); } /** * @return The total count of all the keys. */ public long count() { return count(nativeHandle, false); } /** * @return The total count of all non-expired keys. Note that this call has costs. */ public long countNonExpiredKeys() { return count(nativeHandle, true); } /** * Get the size of the underlying file. Align to the disk block size, typically 4K for an Android device. */ public long totalSize() { return totalSize(nativeHandle); } /** * Get the actual used size of the MMKV instance. * This size might increase and decrease as MMKV doing insertion and full write back. */ public long actualSize() { return actualSize(nativeHandle); } public void removeValueForKey(String key) { removeValueForKey(nativeHandle, key); } /** * Batch remove some keys from the MMKV instance. * * @param arrKeys The keys to be removed. */ public native void removeValuesForKeys(String[] arrKeys); /** * Clear all the key-values inside the MMKV instance. */ public native void clearAll(); /** * The {@link #totalSize()} of an MMKV instance won't reduce after deleting key-values, * call this method after lots of deleting if you care about disk usage. * Note that {@link #clearAll()} has a similar effect. */ public native void trim(); /** * Call this method if the MMKV instance is no longer needed in the near future. * Any subsequent call to any MMKV instances with the same ID is undefined behavior. */ public native void close(); /** * Clear memory cache of the MMKV instance. * You can call it on memory warning. * Any subsequent call to the MMKV instance will trigger all key-values loading from the file again. */ public native void clearMemoryCache(); /** * Save all mmap memory to file synchronously. * You don't need to call this, really, I mean it. * Unless you worry about the device running out of battery. */ public void sync() { sync(true); } /** * Save all mmap memory to file asynchronously. * No need to call this unless you worry about the device running out of battery. */ public void async() { sync(false); } private native void sync(boolean sync); /** * Check whether the MMKV file is valid or not. * Note: Don't use this to check the existence of the instance, the result is undefined on nonexistent files. */ public static boolean isFileValid(String mmapID) { return isFileValid(mmapID, null); } /** * Check whether the MMKV file is valid or not on customize folder. * * @param mmapID The unique ID of the MMKV instance. * @param rootPath The folder of the MMKV instance, defaults to $(FilesDir)/mmkv. */ public static native boolean isFileValid(String mmapID, @Nullable String rootPath); /** * Atomically migrate all key-values from an existent SharedPreferences to the MMKV instance. * * @param preferences The SharedPreferences to import from. * @return The total count of key-values imported. */ @SuppressWarnings("unchecked") public int importFromSharedPreferences(SharedPreferences preferences) { Map<String, ?> kvs = preferences.getAll(); if (kvs == null || kvs.size() <= 0) { return 0; } for (Map.Entry<String, ?> entry : kvs.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } if (value instanceof Boolean) { encodeBool(nativeHandle, key, (boolean) value); } else if (value instanceof Integer) { encodeInt(nativeHandle, key, (int) value); } else if (value instanceof Long) { encodeLong(nativeHandle, key, (long) value); } else if (value instanceof Float) { encodeFloat(nativeHandle, key, (float) value); } else if (value instanceof Double) { encodeDouble(nativeHandle, key, (double) value); } else if (value instanceof String) { encodeString(nativeHandle, key, (String) value); } else if (value instanceof Set) { encode(key, (Set<String>) value); } else { simpleLog(MMKVLogLevel.LevelError, "unknown type: " + value.getClass()); } } return kvs.size(); } /** * backup one MMKV instance to dstDir * * @param mmapID the MMKV ID to backup * @param rootPath the customize root path of the MMKV, if null then backup from the root dir of MMKV * @param dstDir the backup destination directory */ public static native boolean backupOneToDirectory(String mmapID, String dstDir, @Nullable String rootPath); /** * restore one MMKV instance from srcDir * * @param mmapID the MMKV ID to restore * @param srcDir the restore source directory * @param rootPath the customize root path of the MMKV, if null then restore to the root dir of MMKV */ public static native boolean restoreOneMMKVFromDirectory(String mmapID, String srcDir, @Nullable String rootPath); /** * backup all MMKV instance to dstDir * * @param dstDir the backup destination directory * @return count of MMKV successfully backuped */ public static native long backupAllToDirectory(String dstDir); /** * restore all MMKV instance from srcDir * * @param srcDir the restore source directory * @return count of MMKV successfully restored */ public static native long restoreAllFromDirectory(String srcDir); public static final int ExpireNever = 0; public static final int ExpireInMinute = 60; public static final int ExpireInHour = 60 * 60; public static final int ExpireInDay = 24 * 60 * 60; public static final int ExpireInMonth = 30 * 24 * 60 * 60; public static final int ExpireInYear = 365 * 30 * 24 * 60 * 60; /** * Enable auto key expiration. This is a upgrade operation, the file format will change. * And the file won't be accessed correctly by older version (v1.2.16) of MMKV. * * @param expireDurationInSecond the expire duration for all keys, {@link #ExpireNever} (0) means no default duration (aka each key will have it's own expire date) */ public native boolean enableAutoKeyExpire(int expireDurationInSecond); /** * Disable auto key expiration. This is a downgrade operation. */ public native boolean disableAutoKeyExpire(); /** * Intentionally Not Supported. Because MMKV does type-eraser inside to get better performance. */ @Override public Map<String, ?> getAll() { throw new java.lang.UnsupportedOperationException( "Intentionally Not Supported. Use allKeys() instead, getAll() not implement because type-erasure inside mmkv"); } @Nullable @Override public String getString(String key, @Nullable String defValue) { return decodeString(nativeHandle, key, defValue); } @Override public Editor putString(String key, @Nullable String value) { encodeString(nativeHandle, key, value); return this; } public Editor putString(String key, @Nullable String value, int expireDurationInSecond) { encodeString_2(nativeHandle, key, value, expireDurationInSecond); return this; } @Nullable @Override public Set<String> getStringSet(String key, @Nullable Set<String> defValues) { return decodeStringSet(key, defValues); } @Override public Editor putStringSet(String key, @Nullable Set<String> values) { encode(key, values); return this; } public Editor putStringSet(String key, @Nullable Set<String> values, int expireDurationInSecond) { encode(key, values, expireDurationInSecond); return this; } public Editor putBytes(String key, @Nullable byte[] bytes) { encode(key, bytes); return this; } public Editor putBytes(String key, @Nullable byte[] bytes, int expireDurationInSecond) { encode(key, bytes, expireDurationInSecond); return this; } public byte[] getBytes(String key, @Nullable byte[] defValue) { return decodeBytes(key, defValue); } @Override public int getInt(String key, int defValue) { return decodeInt(nativeHandle, key, defValue); } @Override public Editor putInt(String key, int value) { encodeInt(nativeHandle, key, value); return this; } public Editor putInt(String key, int value, int expireDurationInSecond) { encodeInt_2(nativeHandle, key, value, expireDurationInSecond); return this; } @Override public long getLong(String key, long defValue) { return decodeLong(nativeHandle, key, defValue); } @Override public Editor putLong(String key, long value) { encodeLong(nativeHandle, key, value); return this; } public Editor putLong(String key, long value, int expireDurationInSecond) { encodeLong_2(nativeHandle, key, value, expireDurationInSecond); return this; } @Override public float getFloat(String key, float defValue) { return decodeFloat(nativeHandle, key, defValue); } @Override public Editor putFloat(String key, float value) { encodeFloat(nativeHandle, key, value); return this; } public Editor putFloat(String key, float value, int expireDurationInSecond) { encodeFloat_2(nativeHandle, key, value, expireDurationInSecond); return this; } @Override public boolean getBoolean(String key, boolean defValue) { return decodeBool(nativeHandle, key, defValue); } @Override public Editor putBoolean(String key, boolean value) { encodeBool(nativeHandle, key, value); return this; } public Editor putBoolean(String key, boolean value, int expireDurationInSecond) { encodeBool_2(nativeHandle, key, value, expireDurationInSecond); return this; } @Override public Editor remove(String key) { removeValueForKey(key); return this; } /** * {@link #clearAll()} */ @Override public Editor clear() { clearAll(); return this; } /** * @deprecated This method is only for compatibility purpose. You should remove all the calls after migration to MMKV. * MMKV doesn't rely on commit() to save data to file. * If you really worry about losing battery and data corruption, call {@link #async()} or {@link #sync()} instead. */ @Override @Deprecated public boolean commit() { sync(true); return true; } /** * @deprecated This method is only for compatibility purpose. You should remove all the calls after migration to MMKV. * MMKV doesn't rely on apply() to save data to file. * If you really worry about losing battery and data corruption, call {@link #async()} instead. */ @Override @Deprecated public void apply() { sync(false); } @Override public boolean contains(String key) { return containsKey(key); } @Override public Editor edit() { return this; } /** * Intentionally Not Supported by MMKV. We believe it's better not for a storage framework to notify the change of data. * Check {@link #registerContentChangeNotify} for a potential replacement on inter-process scene. */ @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { throw new java.lang.UnsupportedOperationException("Intentionally Not implement in MMKV"); } /** * Intentionally Not Supported by MMKV. We believe it's better not for a storage framework to notify the change of data. */ @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { throw new java.lang.UnsupportedOperationException("Intentionally Not implement in MMKV"); } /** * Get an ashmem MMKV instance that has been initiated by another process. * Normally you should just call {@link #mmkvWithAshmemID(Context, String, int, int, String)} instead. * * @param mmapID The unique ID of the MMKV instance. * @param fd The file descriptor of the ashmem of the MMKV file, transferred from another process by binder. * @param metaFD The file descriptor of the ashmem of the MMKV crc file, transferred from another process by binder. * @param cryptKey The encryption key of the MMKV instance (no more than 16 bytes). * @throws RuntimeException If any failure in JNI or runtime. */ // Parcelable public static MMKV mmkvWithAshmemFD(String mmapID, int fd, int metaFD, String cryptKey) throws RuntimeException { long handle = getMMKVWithAshmemFD(mmapID, fd, metaFD, cryptKey); if (handle == 0) { throw new RuntimeException("Fail to create an ashmem MMKV instance [" + mmapID + "] in JNI"); } return new MMKV(handle); } /** * @return The file descriptor of the ashmem of the MMKV file. */ public native int ashmemFD(); /** * @return The file descriptor of the ashmem of the MMKV crc file. */ public native int ashmemMetaFD(); /** * Create an native buffer, whose underlying memory can be directly transferred to another JNI method. * Avoiding unnecessary JNI boxing and unboxing. * An NativeBuffer must be manually {@link #destroyNativeBuffer} to avoid memory leak. * * @param size The size of the underlying memory. */ @Nullable public static NativeBuffer createNativeBuffer(int size) { long pointer = createNB(size); if (pointer <= 0) { return null; } return new NativeBuffer(pointer, size); } /** * Destroy the native buffer. An NativeBuffer must be manually destroy to avoid memory leak. */ public static void destroyNativeBuffer(NativeBuffer buffer) { destroyNB(buffer.pointer, buffer.size); } /** * Write the value of the key to the native buffer. * * @return The size written. Return -1 on any error. */ public int writeValueToNativeBuffer(String key, NativeBuffer buffer) { return writeValueToNB(nativeHandle, key, buffer.pointer, buffer.size); } // callback handler private static MMKVHandler gCallbackHandler; private static boolean gWantLogReDirecting = false; /** * Register a handler for MMKV log redirecting, and error handling. * * @deprecated This method is deprecated. * Use the {@link #initialize(Context, String, LibLoader, MMKVLogLevel, MMKVHandler)} method instead. */ public static void registerHandler(MMKVHandler handler) { gCallbackHandler = handler; gWantLogReDirecting = gCallbackHandler.wantLogRedirecting(); setCallbackHandler(gWantLogReDirecting, true); } /** * Unregister the handler for MMKV. */ public static void unregisterHandler() { gCallbackHandler = null; setCallbackHandler(false, false); gWantLogReDirecting = false; } private static int onMMKVCRCCheckFail(String mmapID) { MMKVRecoverStrategic strategic = MMKVRecoverStrategic.OnErrorDiscard; if (gCallbackHandler != null) { strategic = gCallbackHandler.onMMKVCRCCheckFail(mmapID); } simpleLog(MMKVLogLevel.LevelInfo, "Recover strategic for " + mmapID + " is " + strategic); Integer value = recoverIndex.get(strategic); return (value == null) ? 0 : value; } private static int onMMKVFileLengthError(String mmapID) { MMKVRecoverStrategic strategic = MMKVRecoverStrategic.OnErrorDiscard; if (gCallbackHandler != null) { strategic = gCallbackHandler.onMMKVFileLengthError(mmapID); } simpleLog(MMKVLogLevel.LevelInfo, "Recover strategic for " + mmapID + " is " + strategic); Integer value = recoverIndex.get(strategic); return (value == null) ? 0 : value; } private static void mmkvLogImp(int level, String file, int line, String function, String message) { if (gCallbackHandler != null && gWantLogReDirecting) { gCallbackHandler.mmkvLog(index2LogLevel[level], file, line, function, message); } else { switch (index2LogLevel[level]) { case LevelDebug: Log.d("MMKV", message); break; case LevelInfo: Log.i("MMKV", message); break; case LevelWarning: Log.w("MMKV", message); break; case LevelError: Log.e("MMKV", message); break; case LevelNone: break; } } } private static void simpleLog(MMKVLogLevel level, String message) { StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[stacktrace.length - 1]; Integer i = logLevel2Index.get(level); int intLevel = (i == null) ? 0 : i; mmkvLogImp(intLevel, e.getFileName(), e.getLineNumber(), e.getMethodName(), message); } // content change notification of other process // trigger by getXXX() or setXXX() or checkContentChangedByOuterProcess() private static MMKVContentChangeNotification gContentChangeNotify; /** * Register for MMKV inter-process content change notification. * The notification will trigger only when any method is manually called on the MMKV instance. * For example {@link #checkContentChangedByOuterProcess()}. * * @param notify The notification handler. */ public static void registerContentChangeNotify(MMKVContentChangeNotification notify) { gContentChangeNotify = notify; setWantsContentChangeNotify(gContentChangeNotify != null); } /** * Unregister for MMKV inter-process content change notification. */ public static void unregisterContentChangeNotify() { gContentChangeNotify = null; setWantsContentChangeNotify(false); } private static void onContentChangedByOuterProcess(String mmapID) { if (gContentChangeNotify != null) { gContentChangeNotify.onContentChangedByOuterProcess(mmapID); } } private static native void setWantsContentChangeNotify(boolean needsNotify); /** * Check inter-process content change manually. */ public native void checkContentChangedByOuterProcess(); // jni private final long nativeHandle; private MMKV(long handle) { nativeHandle = handle; } private static native void jniInitialize(String rootDir, String cacheDir, int level, boolean wantLogReDirecting); private native static long getMMKVWithID(String mmapID, int mode, @Nullable String cryptKey, @Nullable String rootPath); private native static long getMMKVWithIDAndSize(String mmapID, int size, int mode, @Nullable String cryptKey); private native static long getDefaultMMKV(int mode, @Nullable String cryptKey); private native static long getMMKVWithAshmemFD(String mmapID, int fd, int metaFD, @Nullable String cryptKey); private native boolean encodeBool(long handle, String key, boolean value); private native boolean encodeBool_2(long handle, String key, boolean value, int expireDurationInSecond); private native boolean decodeBool(long handle, String key, boolean defaultValue); private native boolean encodeInt(long handle, String key, int value); private native boolean encodeInt_2(long handle, String key, int value, int expireDurationInSecond); private native int decodeInt(long handle, String key, int defaultValue); private native boolean encodeLong(long handle, String key, long value); private native boolean encodeLong_2(long handle, String key, long value, int expireDurationInSecond); private native long decodeLong(long handle, String key, long defaultValue); private native boolean encodeFloat(long handle, String key, float value); private native boolean encodeFloat_2(long handle, String key, float value, int expireDurationInSecond); private native float decodeFloat(long handle, String key, float defaultValue); private native boolean encodeDouble(long handle, String key, double value); private native boolean encodeDouble_2(long handle, String key, double value, int expireDurationInSecond); private native double decodeDouble(long handle, String key, double defaultValue); private native boolean encodeString(long handle, String key, @Nullable String value); private native boolean encodeString_2(long handle, String key, @Nullable String value, int expireDurationInSecond); @Nullable private native String decodeString(long handle, String key, @Nullable String defaultValue); private native boolean encodeSet(long handle, String key, @Nullable String[] value); private native boolean encodeSet_2(long handle, String key, @Nullable String[] value, int expireDurationInSecond); @Nullable private native String[] decodeStringSet(long handle, String key); private native boolean encodeBytes(long handle, String key, @Nullable byte[] value); private native boolean encodeBytes_2(long handle, String key, @Nullable byte[] value, int expireDurationInSecond); @Nullable private native byte[] decodeBytes(long handle, String key); private native boolean containsKey(long handle, String key); private native String[] allKeys(long handle, boolean filterExpire); private native long count(long handle, boolean filterExpire); private native long totalSize(long handle); private native long actualSize(long handle); private native void removeValueForKey(long handle, String key); private native int valueSize(long handle, String key, boolean actualSize); private static native void setLogLevel(int level); private static native void setCallbackHandler(boolean logReDirecting, boolean hasCallback); private static native long createNB(int size); private static native void destroyNB(long pointer, int size); private native int writeValueToNB(long handle, String key, long pointer, int size); private static native boolean checkProcessMode(long handle); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKVContentChangeNotification.java
Java
package com.tencent.mmkv; /** * Inter-process content change notification. * Triggered by any method call, such as getXXX() or setXXX() or {@link MMKV#checkContentChangedByOuterProcess()}. */ public interface MMKVContentChangeNotification { /** * Inter-process content change notification. * Triggered by any method call, such as getXXX() or setXXX() or {@link MMKV#checkContentChangedByOuterProcess()}. * @param mmapID The unique ID of the changed MMKV instance. */ void onContentChangedByOuterProcess(String mmapID); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKVContentProvider.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; import android.app.ActivityManager; import android.content.ComponentName; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * A helper class for MMKV based on Anonymous Shared Memory. {@link MMKV#mmkvWithAshmemID} */ public class MMKVContentProvider extends ContentProvider { static protected final String KEY = "KEY"; static protected final String KEY_SIZE = "KEY_SIZE"; static protected final String KEY_MODE = "KEY_MODE"; static protected final String KEY_CRYPT = "KEY_CRYPT"; static protected final String FUNCTION_NAME = "mmkvFromAshmemID"; static private Uri gUri; @Nullable static protected Uri contentUri(Context context) { if (MMKVContentProvider.gUri != null) { return MMKVContentProvider.gUri; } if (context == null) { return null; } String authority = queryAuthority(context); if (authority == null) { return null; } MMKVContentProvider.gUri = Uri.parse(ContentResolver.SCHEME_CONTENT + "://" + authority); return MMKVContentProvider.gUri; } private Bundle mmkvFromAshmemID(String ashmemID, int size, int mode, String cryptKey) throws RuntimeException { MMKV mmkv = MMKV.mmkvWithAshmemID(getContext(), ashmemID, size, mode, cryptKey); ParcelableMMKV parcelableMMKV = new ParcelableMMKV(mmkv); Log.i("MMKV", ashmemID + " fd = " + mmkv.ashmemFD() + ", meta fd = " + mmkv.ashmemMetaFD()); Bundle result = new Bundle(); result.putParcelable(MMKVContentProvider.KEY, parcelableMMKV); return result; } private static String queryAuthority(Context context) { try { ComponentName componentName = new ComponentName(context, MMKVContentProvider.class.getName()); PackageManager mgr = context.getPackageManager(); if (mgr != null) { ProviderInfo providerInfo = mgr.getProviderInfo(componentName, 0); if (providerInfo != null) { return providerInfo.authority; } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override public boolean onCreate() { Context context = getContext(); if (context == null) { return false; } return true; } protected static String getProcessNameByPID(Context context, int pid) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (manager != null) { // clang-format off for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) { if (processInfo.pid == pid) { return processInfo.processName; } } // clang-format on } return ""; } @Nullable @Override public Bundle call(@NonNull String method, @Nullable String mmapID, @Nullable Bundle extras) { if (method.equals(MMKVContentProvider.FUNCTION_NAME)) { if (extras != null) { int size = extras.getInt(MMKVContentProvider.KEY_SIZE); int mode = extras.getInt(MMKVContentProvider.KEY_MODE); String cryptKey = extras.getString(MMKVContentProvider.KEY_CRYPT); try { return mmkvFromAshmemID(mmapID, size, mode, cryptKey); } catch (Exception e) { Log.e("MMKV", e.getMessage()); return null; } } } return null; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { throw new java.lang.UnsupportedOperationException("Not implement in MMKV"); } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { throw new java.lang.UnsupportedOperationException("Not implement in MMKV"); } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { throw new java.lang.UnsupportedOperationException("Not implement in MMKV"); } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { throw new java.lang.UnsupportedOperationException("Not implement in MMKV"); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKVHandler.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; /** * Callback handler for MMKV. * Callback is called on the operating thread of the MMKV instance. */ public interface MMKVHandler { /** * By default MMKV will discard all data on crc32-check failure. {@link MMKVRecoverStrategic#OnErrorDiscard} * @param mmapID The unique ID of the MMKV instance. * @return Return {@link MMKVRecoverStrategic#OnErrorRecover} to recover any data on the file. */ MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID); /** * By default MMKV will discard all data on file length mismatch. {@link MMKVRecoverStrategic#OnErrorDiscard} * @param mmapID The unique ID of the MMKV instance. * @return Return {@link MMKVRecoverStrategic#OnErrorRecover} to recover any data on the file. */ MMKVRecoverStrategic onMMKVFileLengthError(String mmapID); /** * @return Return False if you don't want log redirecting. */ boolean wantLogRedirecting(); /** * Log Redirecting. * @param level The level of this log. * @param file The file name of this log. * @param line The line of code of this log. * @param function The function name of this log. * @param message The content of this log. */ void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKVLogLevel.java
Java
package com.tencent.mmkv; /** * The levels of MMKV log. */ public enum MMKVLogLevel { /** * Debug level. Not available for release/production build. */ LevelDebug, /** * Info level. The default level. */ LevelInfo, /** * Warning level. */ LevelWarning, /** * Error level. */ LevelError, /** * Special level for disabling all logging. * It's highly NOT suggested to turn off logging. Makes it hard to diagnose online/production bugs. */ LevelNone }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/MMKVRecoverStrategic.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; /** * The recover strategic of MMKV on errors. {@link MMKV#registerHandler} */ public enum MMKVRecoverStrategic { /** * The default strategic is to discard everything on errors. */ OnErrorDiscard, /** * The recover strategic will try to recover as much data as possible. */ OnErrorRecover, }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/NativeBuffer.java
Java
package com.tencent.mmkv; /** * A native memory wrapper, whose underlying memory can be passed to another JNI method directly. * Avoiding unnecessary JNI boxing and unboxing. * Must be destroy manually {@link MMKV#destroyNativeBuffer}. */ public final class NativeBuffer { public long pointer; public int size; public NativeBuffer(long ptr, int length) { pointer = ptr; size = length; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
MmkvLib/src/main/java/com/tencent/mmkv/ParcelableMMKV.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkv; import android.os.Parcel; import android.os.ParcelFileDescriptor; import android.os.Parcelable; import java.io.IOException; /** * A helper class for MMKV based on Anonymous Shared Memory. {@link MMKV#mmkvWithAshmemID} */ public final class ParcelableMMKV implements Parcelable { private final String mmapID; private int ashmemFD = -1; private int ashmemMetaFD = -1; private String cryptKey = null; public ParcelableMMKV(MMKV mmkv) { mmapID = mmkv.mmapID(); ashmemFD = mmkv.ashmemFD(); ashmemMetaFD = mmkv.ashmemMetaFD(); cryptKey = mmkv.cryptKey(); } private ParcelableMMKV(String id, int fd, int metaFD, String key) { mmapID = id; ashmemFD = fd; ashmemMetaFD = metaFD; cryptKey = key; } public MMKV toMMKV() { if (ashmemFD >= 0 && ashmemMetaFD >= 0) { return MMKV.mmkvWithAshmemFD(mmapID, ashmemFD, ashmemMetaFD, cryptKey); } return null; } @Override public int describeContents() { return CONTENTS_FILE_DESCRIPTOR; } @Override public void writeToParcel(Parcel dest, int flags) { try { dest.writeString(mmapID); ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(ashmemFD); ParcelFileDescriptor metaFD = ParcelFileDescriptor.fromFd(ashmemMetaFD); flags = flags | Parcelable.PARCELABLE_WRITE_RETURN_VALUE; fd.writeToParcel(dest, flags); metaFD.writeToParcel(dest, flags); if (cryptKey != null) { dest.writeString(cryptKey); } } catch (IOException e) { e.printStackTrace(); } } public static final Parcelable.Creator<ParcelableMMKV> CREATOR = new Parcelable.Creator<ParcelableMMKV>() { @Override public ParcelableMMKV createFromParcel(Parcel source) { String mmapID = source.readString(); ParcelFileDescriptor fd = ParcelFileDescriptor.CREATOR.createFromParcel(source); ParcelFileDescriptor metaFD = ParcelFileDescriptor.CREATOR.createFromParcel(source); String cryptKey = source.readString(); if (fd != null && metaFD != null) { return new ParcelableMMKV(mmapID, fd.detachFd(), metaFD.detachFd(), cryptKey); } return null; } @Override public ParcelableMMKV[] newArray(int size) { return new ParcelableMMKV[size]; } }; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/build.gradle
Gradle
apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.0" defaultConfig { applicationId "com.tencent.mmkvdemo" minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation project(':MmkvLib') implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'com.getkeepsafe.relinker:relinker:1.4.3' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/Baseline.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import static android.content.Context.MODE_PRIVATE; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.tencent.mmkv.MMKV; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Random; public final class Baseline { private String[] m_arrStrings; private String[] m_arrKeys; private String[] m_arrIntKeys; private int m_loops = 1000; private Context m_context; private static final String MMKV_ID = "baseline3"; private static final String CryptKey = null; //private static final String CryptKey = "baseline_key3"; private static final String TAG = "MMKV"; private DecimalFormat m_formatter; Baseline(Context context, int loops) { m_context = context; m_loops = loops; m_arrStrings = new String[loops]; m_arrKeys = new String[loops]; m_arrIntKeys = new String[loops]; Random r = new Random(); final String filename = "mmkv/Android/MMKV/mmkvdemo/src/main/java/com/tencent/mmkvdemo/Baseline.java_"; for (int index = 0; index < loops; index++) { //String str = "[MMKV] [Info]<MemoryFile_OSX.cpp:36>: protection on [/var/mobile/Containers/Data/Application/B93F2BD3-E0DB-49B3-9BB0-C662E2FC11D9/Documents/mmkv/cips_commoncache] is NSFileProtectionCompleteUntilFirstUserAuthentication_"; //m_arrStrings[index] = str + r.nextInt(); m_arrStrings[index] = filename + r.nextInt(); m_arrKeys[index] = "str_" + index; m_arrIntKeys[index] = "int_" + index; } m_formatter = new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); m_formatter.setRoundingMode(RoundingMode.DOWN); } public void mmkvBaselineTest() { mmkvBatchWriteInt(); mmkvBatchReadInt(); mmkvBatchWriteString(); mmkvBatchReadString(); //mmkvBatchDeleteString(); MMKV mmkv = mmkvForTest(); //mmkv.trim(); mmkv.clearMemoryCache(); mmkv.totalSize(); } private MMKV mmkvForTest() { return MMKV.mmkvWithID(MMKV_ID, MMKV.SINGLE_PROCESS_MODE, CryptKey); //return MMKV.mmkvWithAshmemID(m_context, MMKV_ID, 65536, MMKV.SINGLE_PROCESS_MODE, CryptKey); } private void mmkvBatchWriteInt() { Random r = new Random(); long startTime = System.nanoTime(); MMKV mmkv = mmkvForTest(); for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; mmkv.encode(key, tmp); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "MMKV write int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void mmkvBatchReadInt() { long startTime = System.nanoTime(); MMKV mmkv = mmkvForTest(); for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = mmkv.decodeInt(key); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "MMKV read int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void mmkvBatchWriteString() { long startTime = System.nanoTime(); MMKV mmkv = mmkvForTest(); for (int index = 0; index < m_loops; index++) { final String valueStr = m_arrStrings[index]; final String strKey = m_arrKeys[index]; mmkv.encode(strKey, valueStr); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "MMKV write String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void mmkvBatchReadString() { long startTime = System.nanoTime(); MMKV mmkv = mmkvForTest(); for (int index = 0; index < m_loops; index++) { String strKey = m_arrKeys[index]; String tmpStr = mmkv.decodeString(strKey); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "MMKV read String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void mmkvBatchDeleteString() { long startTime = System.nanoTime(); MMKV mmkv = mmkvForTest(); for (int index = 0; index < m_loops; index++) { String strKey = m_arrKeys[index]; mmkv.removeValueForKey(strKey); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "MMKV delete String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } public void sharedPreferencesBaselineTest() { spBatchWriteInt(); spBatchReadInt(); spBatchWriteString(); spBatchReadString(); } private void spBatchWriteInt() { Random r = new Random(); long startTime = System.nanoTime(); SharedPreferences preferences = m_context.getSharedPreferences(MMKV_ID, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; editor.putInt(key, tmp); // editor.commit(); editor.apply(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "SharedPreferences write int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void spBatchReadInt() { long startTime = System.nanoTime(); SharedPreferences preferences = m_context.getSharedPreferences(MMKV_ID, MODE_PRIVATE); for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = preferences.getInt(key, 0); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "SharedPreferences read int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void spBatchWriteString() { long startTime = System.nanoTime(); SharedPreferences preferences = m_context.getSharedPreferences(MMKV_ID, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); for (int index = 0; index < m_loops; index++) { final String str = m_arrStrings[index]; final String key = m_arrKeys[index]; editor.putString(key, str); // editor.commit(); editor.apply(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "SharedPreferences write String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void spBatchReadString() { long startTime = System.nanoTime(); SharedPreferences preferences = m_context.getSharedPreferences(MMKV_ID, MODE_PRIVATE); for (int index = 0; index < m_loops; index++) { final String key = m_arrKeys[index]; final String tmp = preferences.getString(key, null); } double endTime = (System.nanoTime() - startTime) / 1000000.0; Log.i(TAG, "SharedPreferences read String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } public void sqliteBaselineTest(boolean useTransaction) { sqliteWriteInt(useTransaction); sqliteReadInt(useTransaction); sqliteWriteString(useTransaction); sqliteReadString(useTransaction); } private void sqliteWriteInt(boolean useTransaction) { Random r = new Random(); long startTime = System.nanoTime(); SQLiteKV sqliteKV = new SQLiteKV(m_context); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; sqliteKV.putInt(key, tmp); } if (useTransaction) { sqliteKV.endTransaction(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; final String msg = useTransaction ? "sqlite transaction" : "sqlite"; Log.i(TAG, msg + " write int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void sqliteReadInt(boolean useTransaction) { long startTime = System.nanoTime(); SQLiteKV sqliteKV = new SQLiteKV(m_context); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = sqliteKV.getInt(key); } if (useTransaction) { sqliteKV.endTransaction(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; final String msg = useTransaction ? "sqlite transaction" : "sqlite"; Log.i(TAG, msg + " read int: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void sqliteWriteString(boolean useTransaction) { long startTime = System.nanoTime(); SQLiteKV sqliteKV = new SQLiteKV(m_context); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { final String value = m_arrStrings[index]; final String key = m_arrKeys[index]; sqliteKV.putString(key, value); } if (useTransaction) { sqliteKV.endTransaction(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; final String msg = useTransaction ? "sqlite transaction" : "sqlite"; Log.i(TAG, msg + " write String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } private void sqliteReadString(boolean useTransaction) { long startTime = System.nanoTime(); SQLiteKV sqliteKV = new SQLiteKV(m_context); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { final String key = m_arrKeys[index]; final String tmp = sqliteKV.getString(key); } if (useTransaction) { sqliteKV.endTransaction(); } double endTime = (System.nanoTime() - startTime) / 1000000.0; final String msg = useTransaction ? "sqlite transaction" : "sqlite"; Log.i(TAG, msg + " read String: loop[" + m_loops + "]: " + m_formatter.format(endTime) + " ms"); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/BenchMarkBaseService.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.util.Log; import androidx.annotation.Nullable; import com.tencent.mmkv.MMKV; import com.tencent.mmkv.ParcelableMMKV; import java.util.Random; public abstract class BenchMarkBaseService extends Service { public static final String CMD_ID = "cmd_id"; public static final String CMD_READ_INT = "cmd_read_int"; public static final String CMD_WRITE_INT = "cmd_write_int"; public static final String CMD_READ_STRING = "cmd_read_string"; public static final String CMD_WRITE_STRING = "cmd_write_string"; public static final String CMD_PREPARE_ASHMEM_BY_CP = "cmd_prepare_ashmem_by_ContentProvider"; public static final String CMD_PREPARE_ASHMEM_KEY = "cmd_prepare_ashmem_key"; // 1M, ashmem cannot change size after opened public static final int AshmemMMKV_Size = 1024 * 1024; public static final String AshmemMMKV_ID = "testAshmemMMKVByCP"; private String[] m_arrStrings; private String[] m_arrKeys; private String[] m_arrIntKeys; private static final int m_loops = 1000; public static final String MMKV_ID = "benchmark_interprocess"; //public static final String MMKV_ID = "benchmark_interprocess_crypt1"; private static final String SP_ID = "benchmark_interprocess_sp"; public static final String CryptKey = null; //public static final String CryptKey = "Tencent MMKV"; private static final boolean SQLite_Use_Transaction = false; private static final String TAG = "MMKV"; @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate BenchMarkBaseService"); MMKV.initialize(this); MMKV.unregisterHandler(); MMKV.unregisterContentChangeNotify(); { long startTime = System.currentTimeMillis(); MMKV mmkv = MMKV.mmkvWithID(MMKV_ID, MMKV.MULTI_PROCESS_MODE, CryptKey); long endTime = System.currentTimeMillis(); Log.i(TAG, "load [" + MMKV_ID + "]: " + (endTime - startTime) + " ms"); } m_arrStrings = new String[m_loops]; m_arrKeys = new String[m_loops]; m_arrIntKeys = new String[m_loops]; Random r = new Random(); final String filename = "mmkv/Android/MMKV/mmkvdemo/src/main/java/com/tencent/mmkvdemo/BenchMarkBaseService.java_"; for (int index = 0; index < m_loops; index++) { //String str = "[MMKV] [Info]<MemoryFile_OSX.cpp:36>: protection on [/var/mobile/Containers/Data/Application/B93F2BD3-E0DB-49B3-9BB0-C662E2FC11D9/Documents/mmkv/cips_commoncache] is NSFileProtectionCompleteUntilFirstUserAuthentication_"; //m_arrStrings[index] = str + r.nextInt(); m_arrStrings[index] = filename + r.nextInt(); m_arrKeys[index] = "testStr_" + index; m_arrIntKeys[index] = "int_" + index; } } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy BenchMarkBaseService"); MMKV.onExit(); } protected void batchWriteInt(String caller) { mmkvBatchWriteInt(caller); sqliteWriteInt(caller, SQLite_Use_Transaction); spBatchWriteInt(caller); } private void mmkvBatchWriteInt(String caller) { Random r = new Random(); Log.i(TAG, caller + " mmkv write int: loop[" + m_loops + "] star."); long startTime = System.currentTimeMillis(); MMKV mmkv = GetMMKV(); for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; mmkv.encode(key, tmp); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " mmkv write int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void sqliteWriteInt(String caller, boolean useTransaction) { Random r = new Random(); long startTime = System.currentTimeMillis(); SQLiteKV sqliteKV = new SQLiteKV(this); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; sqliteKV.putInt(key, tmp); } if (useTransaction) { sqliteKV.endTransaction(); } long endTime = System.currentTimeMillis(); final String msg = useTransaction ? " sqlite transaction " : " sqlite "; Log.i(TAG, caller + msg + "write int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void spBatchWriteInt(String caller) { Random r = new Random(); long startTime = System.currentTimeMillis(); SharedPreferences preferences = MultiProcessSharedPreferences.getSharedPreferences(this, SP_ID, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); for (int index = 0; index < m_loops; index++) { int tmp = r.nextInt(); String key = m_arrIntKeys[index]; editor.putInt(key, tmp); //editor.commit(); editor.apply(); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " MultiProcessSharedPreferences write int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } protected void batchReadInt(String caller) { mmkvBatchReadInt(caller); sqliteReadInt(caller, SQLite_Use_Transaction); spBatchReadInt(caller); } private void mmkvBatchReadInt(String caller) { Log.i(TAG, caller + " mmkv read int: loop[" + m_loops + "] star."); long startTime = System.currentTimeMillis(); MMKV mmkv = GetMMKV(); for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = mmkv.decodeInt(key); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " mmkv read int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void sqliteReadInt(String caller, boolean useTransaction) { long startTime = System.currentTimeMillis(); SQLiteKV sqliteKV = new SQLiteKV(this); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = sqliteKV.getInt(key); } if (useTransaction) { sqliteKV.endTransaction(); } long endTime = System.currentTimeMillis(); final String msg = useTransaction ? " sqlite transaction " : " sqlite "; Log.i(TAG, caller + msg + "read int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void spBatchReadInt(String caller) { long startTime = System.currentTimeMillis(); SharedPreferences preferences = MultiProcessSharedPreferences.getSharedPreferences(this, SP_ID, MODE_PRIVATE); for (int index = 0; index < m_loops; index++) { String key = m_arrIntKeys[index]; int tmp = preferences.getInt(key, 0); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " MultiProcessSharedPreferences read int: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } protected void batchWriteString(String caller) { mmkvBatchWriteString(caller); sqliteWriteString(caller, SQLite_Use_Transaction); spBatchWrieString(caller); } private void mmkvBatchWriteString(String caller) { Log.i(TAG, caller + " mmkv write String: loop[" + m_loops + "] star."); long startTime = System.currentTimeMillis(); MMKV mmkv = GetMMKV(); for (int index = 0; index < m_loops; index++) { final String valueStr = m_arrStrings[index]; final String strKey = m_arrKeys[index]; mmkv.encode(strKey, valueStr); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " mmkv write String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void sqliteWriteString(String caller, boolean useTransaction) { long startTime = System.currentTimeMillis(); SQLiteKV sqliteKV = new SQLiteKV(this); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { final String value = m_arrStrings[index]; final String key = m_arrKeys[index]; sqliteKV.putString(key, value); } if (useTransaction) { sqliteKV.endTransaction(); } long endTime = System.currentTimeMillis(); final String msg = useTransaction ? " sqlite transaction " : " sqlite "; Log.i(TAG, caller + msg + "write String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void spBatchWrieString(String caller) { long startTime = System.currentTimeMillis(); SharedPreferences preferences = MultiProcessSharedPreferences.getSharedPreferences(this, SP_ID, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); for (int index = 0; index < m_loops; index++) { final String str = m_arrStrings[index]; final String key = m_arrKeys[index]; editor.putString(key, str); //editor.commit(); editor.apply(); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " MultiProcessSharedPreferences write String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } protected void batchReadString(String caller) { mmkvBatchReadString(caller); sqliteReadString(caller, SQLite_Use_Transaction); spBatchReadStrinfg(caller); } private void mmkvBatchReadString(String caller) { Log.i(TAG, caller + " mmkv read String: loop[" + m_loops + "] star."); long startTime = System.currentTimeMillis(); MMKV mmkv = GetMMKV(); for (int index = 0; index < m_loops; index++) { final String strKey = m_arrKeys[index]; final String tmpStr = mmkv.decodeString(strKey); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " mmkv read String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void sqliteReadString(String caller, boolean useTransaction) { long startTime = System.currentTimeMillis(); SQLiteKV sqliteKV = new SQLiteKV(this); if (useTransaction) { sqliteKV.beginTransaction(); } for (int index = 0; index < m_loops; index++) { final String key = m_arrKeys[index]; final String tmp = sqliteKV.getString(key); } if (useTransaction) { sqliteKV.endTransaction(); } long endTime = System.currentTimeMillis(); final String msg = useTransaction ? " sqlite transaction " : " sqlite "; Log.i(TAG, caller + msg + "read String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } private void spBatchReadStrinfg(String caller) { long startTime = System.currentTimeMillis(); SharedPreferences preferences = MultiProcessSharedPreferences.getSharedPreferences(this, SP_ID, MODE_PRIVATE); for (int index = 0; index < m_loops; index++) { final String key = m_arrKeys[index]; final String tmp = preferences.getString(key, null); } long endTime = System.currentTimeMillis(); Log.i(TAG, caller + " MultiProcessSharedPreferences read String: loop[" + m_loops + "]: " + (endTime - startTime) + " ms"); } MMKV m_ashmemMMKV; protected MMKV GetMMKV() { if (m_ashmemMMKV != null) { return m_ashmemMMKV; } else { return MMKV.mmkvWithID(MMKV_ID, MMKV.MULTI_PROCESS_MODE, CryptKey); } } public class AshmemMMKVGetter extends IAshmemMMKV.Stub { private AshmemMMKVGetter() { // 1M, ashmem cannot change size after opened final String id = "tetAshmemMMKV"; try { m_ashmemMMKV = MMKV.mmkvWithAshmemID(BenchMarkBaseService.this, id, AshmemMMKV_Size, MMKV.MULTI_PROCESS_MODE, CryptKey); m_ashmemMMKV.encode("bool", true); } catch (Exception e) { Log.e("MMKV", e.getMessage()); } } public ParcelableMMKV GetAshmemMMKV() { return new ParcelableMMKV(m_ashmemMMKV); } } @Nullable @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind, intent=" + intent); return new AshmemMMKVGetter(); } protected void prepareAshmemMMKVByCP() { // it's ok for other process not knowing cryptKey final String cryptKey = null; try { m_ashmemMMKV = MMKV.mmkvWithAshmemID(this, AshmemMMKV_ID, AshmemMMKV_Size, MMKV.MULTI_PROCESS_MODE, cryptKey); } catch (Exception e) { Log.e("MMKV", e.getMessage()); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/FakeInfo.java
Java
package com.tencent.mmkvdemo; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; public class FakeInfo implements Parcelable { public String channelId; public int position; public FakeInfo() { } @NonNull @Override public String toString() { return "fake channelID = " + channelId + ", position = " + position; } protected FakeInfo(Parcel in) { channelId = in.readString(); position = in.readInt(); } public static final Creator<FakeInfo> CREATOR = new Creator<FakeInfo>() { @Override public FakeInfo createFromParcel(Parcel in) { return new FakeInfo(in); } @Override public FakeInfo[] newArray(int size) { return new FakeInfo[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(channelId); dest.writeInt(position); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/Info.java
Java
package com.tencent.mmkvdemo; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; class Info implements Parcelable { public String channelId; public int position; public Info(String id, int pos) { channelId = id; position = pos; } @NonNull @Override public String toString() { return "channelID = " + channelId + ", position = " + position; } protected Info(Parcel in) { channelId = in.readString(); position = in.readInt(); } public static final Creator<Info> CREATOR = new Creator<Info>() { @Override public Info createFromParcel(Parcel in) { return new Info(in); } @Override public Info[] newArray(int size) { return new Info[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(channelId); dest.writeInt(position); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/MainActivity.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import static com.tencent.mmkvdemo.BenchMarkBaseService.AshmemMMKV_ID; import static com.tencent.mmkvdemo.BenchMarkBaseService.AshmemMMKV_Size; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.tencent.mmkv.MMKV; import com.tencent.mmkv.NativeBuffer; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import org.jetbrains.annotations.Nullable; public class MainActivity extends AppCompatActivity { static private final String KEY_1 = "Ashmem_Key_1"; static private final String KEY_2 = "Ashmem_Key_2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.sample_text); String rootDir = MMKV.getRootDir(); tv.setText(rootDir); final Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { final Baseline baseline = new Baseline(getApplicationContext(), 1000); public void onClick(View v) { baseline.mmkvBaselineTest(); baseline.sharedPreferencesBaselineTest(); baseline.sqliteBaselineTest(false); //testInterProcessReKey(); //testInterProcessLockPhase2(); } }); //testHolderForMultiThread(); //prepareInterProcessAshmem(); //prepareInterProcessAshmemByContentProvider(KEY_1); final Button button_read_int = findViewById(R.id.button_read_int); button_read_int.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { interProcessBaselineTest(BenchMarkBaseService.CMD_READ_INT); } }); final Button button_write_int = findViewById(R.id.button_write_int); button_write_int.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { interProcessBaselineTest(BenchMarkBaseService.CMD_WRITE_INT); } }); final Button button_read_string = findViewById(R.id.button_read_string); button_read_string.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { interProcessBaselineTest(BenchMarkBaseService.CMD_READ_STRING); } }); final Button button_write_string = findViewById(R.id.button_write_string); button_write_string.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { interProcessBaselineTest(BenchMarkBaseService.CMD_WRITE_STRING); } }); String otherDir = getFilesDir().getAbsolutePath() + "/mmkv_3"; MMKV kv = testMMKV("test/AES", "Tencent MMKV", false, otherDir); kv.checkContentChangedByOuterProcess(); kv.close(); testAshmem(); testReKey(); KotlinUsecaseKt.kotlinFunctionalTest(); testInterProcessLogic(); testImportSharedPreferences(); //testInterProcessLockPhase1(); //testCornerSize(); //testFastRemoveCornerSize(); //testTrimNonEmptyInterProcess(); //testItemSizeHolderOverride(); testBackup(); testRestore(); testAutoExpire(); } private void testInterProcessLogic() { MMKV mmkv = MMKV.mmkvWithID(MyService.MMKV_ID, MMKV.MULTI_PROCESS_MODE, MyService.CryptKey); mmkv.putInt(MyService.CMD_ID, 1024); Log.d("mmkv in main", "" + mmkv.decodeInt(MyService.CMD_ID)); Intent intent = new Intent(this, MyService.class); intent.putExtra(BenchMarkBaseService.CMD_ID, MyService.CMD_REMOVE); startService(intent); SystemClock.sleep(1000 * 3); int value = mmkv.decodeInt(MyService.CMD_ID); Log.d("mmkv", "" + value); } private MMKV testMMKV(String mmapID, String cryptKey, boolean decodeOnly, String rootPath) { //MMKV kv = MMKV.defaultMMKV(); MMKV kv = MMKV.mmkvWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, cryptKey, rootPath); if (!decodeOnly) { kv.encode("bool", true); } Log.i("MMKV", "bool: " + kv.decodeBool("bool")); if (!decodeOnly) { kv.encode("int", Integer.MIN_VALUE); } Log.i("MMKV", "int: " + kv.decodeInt("int")); if (!decodeOnly) { kv.encode("long", Long.MAX_VALUE); } Log.i("MMKV", "long: " + kv.decodeLong("long")); if (!decodeOnly) { kv.encode("float", -3.14f); } Log.i("MMKV", "float: " + kv.decodeFloat("float")); if (!decodeOnly) { kv.encode("double", Double.MIN_VALUE); } Log.i("MMKV", "double: " + kv.decodeDouble("double")); if (!decodeOnly) { kv.encode("string", "Hello from mmkv"); } Log.i("MMKV", "string: " + kv.decodeString("string")); if (!decodeOnly) { byte[] bytes = {'m', 'm', 'k', 'v'}; kv.encode("bytes", bytes); } byte[] bytes = kv.decodeBytes("bytes"); Log.i("MMKV", "bytes: " + new String(bytes)); Log.i("MMKV", "bytes length = " + bytes.length + ", value size consumption = " + kv.getValueSize("bytes") + ", value size = " + kv.getValueActualSize("bytes")); int sizeNeeded = kv.getValueActualSize("bytes"); NativeBuffer nativeBuffer = MMKV.createNativeBuffer(sizeNeeded); if (nativeBuffer != null) { int size = kv.writeValueToNativeBuffer("bytes", nativeBuffer); Log.i("MMKV", "size Needed = " + sizeNeeded + " written size = " + size); MMKV.destroyNativeBuffer(nativeBuffer); } if (!decodeOnly) { TestParcelable testParcelable = new TestParcelable(1024, "Hi Parcelable"); kv.encode("parcel", testParcelable); } TestParcelable result = kv.decodeParcelable("parcel", TestParcelable.class); if (result != null) { Log.d("MMKV", "parcel: " + result.iValue + ", " + result.sValue + ", " + result.list); } else { Log.e("MMKV", "fail to decodeParcelable of key:parcel"); } kv.encode("null string", "some string"); Log.i("MMKV", "string before set null: " + kv.decodeString("null string")); kv.encode("null string", (String) null); Log.i("MMKV", "string after set null: " + kv.decodeString("null string") + ", containsKey:" + kv.contains("null string")); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allKeys())); Log.i("MMKV", "count = " + kv.count() + ", totalSize = " + kv.totalSize() + ", actualSize = " + kv.actualSize()); Log.i("MMKV", "containsKey[string]: " + kv.containsKey("string")); kv.removeValueForKey("bool"); Log.i("MMKV", "bool: " + kv.decodeBool("bool")); kv.removeValuesForKeys(new String[] {"int", "long"}); //kv.sync(); //kv.async(); //kv.clearAll(); kv.clearMemoryCache(); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allKeys())); Log.i("MMKV", "isFileValid[" + kv.mmapID() + "]: " + MMKV.isFileValid(kv.mmapID(), rootPath)); return kv; } private void testImportSharedPreferences() { SharedPreferences preferences = getSharedPreferences("imported", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("bool", true); editor.putInt("int", Integer.MIN_VALUE); editor.putLong("long", Long.MAX_VALUE); editor.putFloat("float", -3.14f); editor.putString("string", "hello, imported"); HashSet<String> set = new HashSet<String>(); set.add("W"); set.add("e"); set.add("C"); set.add("h"); set.add("a"); set.add("t"); editor.putStringSet("string-set", set); editor.commit(); MMKV kv = MMKV.mmkvWithID("imported"); kv.clearAll(); kv.importFromSharedPreferences(preferences); editor.clear().commit(); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allKeys())); Log.i("MMKV", "bool: " + kv.getBoolean("bool", false)); Log.i("MMKV", "int: " + kv.getInt("int", 0)); Log.i("MMKV", "long: " + kv.getLong("long", 0)); Log.i("MMKV", "float: " + kv.getFloat("float", 0)); Log.i("MMKV", "double: " + kv.decodeDouble("double")); Log.i("MMKV", "string: " + kv.getString("string", null)); Log.i("MMKV", "string-set: " + kv.getStringSet("string-set", null)); Log.i("MMKV", "linked-string-set: " + kv.decodeStringSet("string-set", null, LinkedHashSet.class)); // test @Nullable kv.putStringSet("string-set", null); Log.i("MMKV", "after set null, string-set: " + kv.getStringSet("string-set", null)); } private void testReKey() { final String mmapID = "test/AES_reKey1"; MMKV kv = testMMKV(mmapID, null, false, null); kv.reKey("Key_seq_1"); kv.clearMemoryCache(); testMMKV(mmapID, "Key_seq_1", true, null); kv.reKey("Key_seq_2"); kv.clearMemoryCache(); testMMKV(mmapID, "Key_seq_2", true, null); kv.reKey(null); kv.clearMemoryCache(); testMMKV(mmapID, null, true, null); } private void interProcessBaselineTest(String cmd) { Intent intent = new Intent(this, MyService.class); intent.putExtra(BenchMarkBaseService.CMD_ID, cmd); startService(intent); intent = new Intent(this, MyService_1.class); intent.putExtra(BenchMarkBaseService.CMD_ID, cmd); startService(intent); } private void testAshmem() { String cryptKey = "Tencent MMKV"; MMKV kv = MMKV.mmkvWithAshmemID(this, "testAshmem", MMKV.pageSize(), MMKV.SINGLE_PROCESS_MODE, cryptKey); kv.encode("bool", true); Log.i("MMKV", "bool: " + kv.decodeBool("bool")); kv.encode("int", Integer.MIN_VALUE); Log.i("MMKV", "int: " + kv.decodeInt("int")); kv.encode("long", Long.MAX_VALUE); Log.i("MMKV", "long: " + kv.decodeLong("long")); kv.encode("float", -3.14f); Log.i("MMKV", "float: " + kv.decodeFloat("float")); kv.encode("double", Double.MIN_VALUE); Log.i("MMKV", "double: " + kv.decodeDouble("double")); kv.encode("string", "Hello from mmkv"); Log.i("MMKV", "string: " + kv.decodeString("string")); byte[] bytes = {'m', 'm', 'k', 'v'}; kv.encode("bytes", bytes); Log.i("MMKV", "bytes: " + new String(kv.decodeBytes("bytes"))); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allKeys())); Log.i("MMKV", "count = " + kv.count() + ", totalSize = " + kv.totalSize() + ", actualSize = " + kv.actualSize()); Log.i("MMKV", "containsKey[string]: " + kv.containsKey("string")); kv.removeValueForKey("bool"); Log.i("MMKV", "bool: " + kv.decodeBool("bool")); kv.removeValueForKey("int"); kv.removeValueForKey("long"); //kv.removeValuesForKeys(new String[] {"int", "long"}); //kv.clearAll(); kv.clearMemoryCache(); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allKeys())); Log.i("MMKV", "isFileValid[" + kv.mmapID() + "]: " + MMKV.isFileValid(kv.mmapID())); } private void prepareInterProcessAshmem() { Intent intent = new Intent(this, MyService_1.class); intent.putExtra(BenchMarkBaseService.CMD_ID, MyService_1.CMD_PREPARE_ASHMEM); startService(intent); } private void prepareInterProcessAshmemByContentProvider(String cryptKey) { // first of all, init ashmem mmkv in main process MMKV.mmkvWithAshmemID(this, AshmemMMKV_ID, AshmemMMKV_Size, MMKV.MULTI_PROCESS_MODE, cryptKey); // then other process can get by ContentProvider Intent intent = new Intent(this, MyService.class); intent.putExtra(BenchMarkBaseService.CMD_ID, BenchMarkBaseService.CMD_PREPARE_ASHMEM_BY_CP); startService(intent); intent = new Intent(this, MyService_1.class); intent.putExtra(BenchMarkBaseService.CMD_ID, BenchMarkBaseService.CMD_PREPARE_ASHMEM_BY_CP); startService(intent); } private void testInterProcessReKey() { MMKV mmkv = MMKV.mmkvWithAshmemID(this, AshmemMMKV_ID, AshmemMMKV_Size, MMKV.MULTI_PROCESS_MODE, KEY_1); mmkv.reKey(KEY_2); prepareInterProcessAshmemByContentProvider(KEY_2); } private void testHolderForMultiThread() { final int COUNT = 1; final int THREAD_COUNT = 1; final String ID = "Hotel"; final String KEY = "California"; final String VALUE = "You can checkout any time you like, but you can never leave."; final MMKV mmkv = MMKV.mmkvWithID(ID); Runnable task = new Runnable() { public void run() { for (int i = 0; i < COUNT; ++i) { mmkv.putString(KEY, VALUE); mmkv.getString(KEY, null); mmkv.remove(KEY); } } }; for (int i = 0; i < THREAD_COUNT; ++i) { new Thread(task, "MMKV-" + i).start(); } } private void testInterProcessLockPhase1() { MMKV mmkv1 = MMKV.mmkvWithID(MyService.LOCK_PHASE_1, MMKV.MULTI_PROCESS_MODE); mmkv1.lock(); Log.d("locked in main", MyService.LOCK_PHASE_1); Intent intent = new Intent(this, MyService.class); intent.putExtra(BenchMarkBaseService.CMD_ID, MyService.CMD_LOCK); startService(intent); } private void testInterProcessLockPhase2() { MMKV mmkv2 = MMKV.mmkvWithID(MyService.LOCK_PHASE_2, MMKV.MULTI_PROCESS_MODE); mmkv2.lock(); Log.d("locked in main", MyService.LOCK_PHASE_2); } private void testCornerSize() { MMKV mmkv = MMKV.mmkvWithID("cornerSize", MMKV.MULTI_PROCESS_MODE, "aes"); mmkv.clearAll(); int size = MMKV.pageSize() - 2; size -= 4; String key = "key"; int keySize = 3 + 1; size -= keySize; int valueSize = 3; size -= valueSize; byte[] value = new byte[size]; mmkv.encode(key, value); } private void testFastRemoveCornerSize() { MMKV mmkv = MMKV.mmkvWithID("fastRemoveCornerSize"); mmkv.clearAll(); int size = MMKV.pageSize() - 4; size -= 4; // place holder size String key = "key"; int keySize = 3 + 1; size -= keySize; int valueSize = 3; size -= valueSize; size -= (keySize + 1); // total size of fast remove size /= 16; byte[] value = new byte[size]; for (int i = 0; i < value.length; i++) { value[i] = 'A'; } for (int i = 0; i < 16; i++) { mmkv.encode(key, value); // when a full write back is occur, here's corruption happens mmkv.removeValueForKey(key); } } private void testTrimNonEmptyInterProcess() { MMKV mmkv = MMKV.mmkvWithID("trimNonEmptyInterProcess", MMKV.MULTI_PROCESS_MODE); mmkv.clearAll(); mmkv.encode("NonEmptyKey", "Hello, world!"); byte[] value = new byte[MMKV.pageSize()]; mmkv.encode("largeKV", value); mmkv.removeValueForKey("largeKV"); mmkv.trim(); Intent intent = new Intent(this, MyService.class); intent.putExtra(BenchMarkBaseService.CMD_ID, MyService.CMD_TRIM_FINISH); startService(intent); SystemClock.sleep(1000 * 3); Log.i("MMKV", "NonEmptyKey: " + mmkv.decodeString("NonEmptyKey")); } private void testItemSizeHolderOverride() { // final String mmapID = "testItemSizeHolderOverride_crypted"; // final String encryptKey = "encrypeKey"; final String mmapID = "testItemSizeHolderOverride_plaintext"; final String encryptKey = null; MMKV mmkv = MMKV.mmkvWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, encryptKey); /* do this in v1.1.2 { // mmkv.encode("b", true); byte[] value = new byte[512]; mmkv.encode("data", value); Log.i("MMKV", "allKeys: " + Arrays.toString(mmkv.allKeys())); }*/ // do this in v1.2.0 { long totalSize = mmkv.totalSize(); long bufferSize = totalSize - 512; byte[] value = new byte[(int) bufferSize]; // force a fullwriteback() mmkv.encode("bigData", value); mmkv.clearMemoryCache(); Log.i("MMKV", "allKeys: " + Arrays.toString(mmkv.allKeys())); } } private void testBackup() { File f = new File(MMKV.getRootDir()); String backupRootDir = f.getParent() + "/mmkv_backup_3"; String mmapID = "test/AES"; String otherDir = getFilesDir().getAbsolutePath() + "/mmkv_3"; boolean ret = MMKV.backupOneToDirectory(mmapID, backupRootDir, otherDir); Log.i("MMKV", "backup one [" + mmapID + "] ret = " + ret); if (ret) { MMKV mmkv = MMKV.backedUpMMKVWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, "Tencent MMKV", backupRootDir); Log.i("MMKV", "check on backup file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); } /*{ MMKV mmkv = MMKV.mmkvWithID("imported"); mmkv.close(); mmkv = MMKV.mmkvWithID("test/AES_reKey1"); mmkv.close(); }*/ backupRootDir = f.getParent() + "/mmkv_backup"; long count = MMKV.backupAllToDirectory(backupRootDir); Log.i("MMKV", "backup all count " + count); if (count > 0) { MMKV mmkv = MMKV.backedUpMMKVWithID("imported", MMKV.SINGLE_PROCESS_MODE, null, backupRootDir); Log.i("MMKV", "check on backup file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.backedUpMMKVWithID("testKotlin", MMKV.SINGLE_PROCESS_MODE, null, backupRootDir); Log.i("MMKV", "check on backup file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.backedUpMMKVWithID("test/AES_reKey1", MMKV.SINGLE_PROCESS_MODE, null, backupRootDir); Log.i("MMKV", "check on backup file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.backedUpMMKVWithID("benchmark_interprocess", MMKV.MULTI_PROCESS_MODE, null, backupRootDir); Log.i("MMKV", "check on backup file[" + mmkv.mmapID() + "] allKeys count: " + mmkv.count()); } } private void testRestore() { File f = new File(MMKV.getRootDir()); String backupRootDir = f.getParent() + "/mmkv_backup_3"; String mmapID = "test/AES"; String otherDir = getFilesDir().getAbsolutePath() + "/mmkv_3"; MMKV mmkv = MMKV.mmkvWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, "Tencent MMKV", otherDir); mmkv.encode("test_restore", true); Log.i("MMKV", "before restore [" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); boolean ret = MMKV.restoreOneMMKVFromDirectory(mmapID, backupRootDir, otherDir); Log.i("MMKV", "restore one [" + mmapID + "] ret = " + ret); if (ret) { Log.i("MMKV", "after restore [" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); } /*{ mmkv = MMKV.mmkvWithID("imported"); mmkv.close(); mmkv = MMKV.mmkvWithID("test/AES_reKey1"); mmkv.close(); }*/ backupRootDir = f.getParent() + "/mmkv_backup"; long count = MMKV.restoreAllFromDirectory(backupRootDir); Log.i("MMKV", "restore all count " + count); if (count > 0) { mmkv = MMKV.mmkvWithID("imported"); Log.i("MMKV", "check on restore file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.mmkvWithID("testKotlin"); Log.i("MMKV", "check on restore file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.mmkvWithID("test/AES_reKey1"); Log.i("MMKV", "check on restore file[" + mmkv.mmapID() + "] allKeys: " + Arrays.toString(mmkv.allKeys())); mmkv = MMKV.mmkvWithID("benchmark_interprocess", MMKV.MULTI_PROCESS_MODE); Log.i("MMKV", "check on restore file[" + mmkv.mmapID() + "] allKeys count: " + mmkv.count()); } } private void testAutoExpire(MMKV kv, boolean decodeOnly, int expiration) { if (!decodeOnly) { kv.encode("bool", true, expiration); } Log.i("MMKV", "bool: " + kv.decodeBool("bool")); if (!decodeOnly) { kv.encode("int", Integer.MIN_VALUE, expiration); } Log.i("MMKV", "int: " + kv.decodeInt("int")); if (!decodeOnly) { kv.encode("long", Long.MAX_VALUE, expiration); } Log.i("MMKV", "long: " + kv.decodeLong("long")); if (!decodeOnly) { kv.encode("float", -3.14f, expiration); } Log.i("MMKV", "float: " + kv.decodeFloat("float")); if (!decodeOnly) { kv.encode("double", Double.MIN_VALUE, expiration); } Log.i("MMKV", "double: " + kv.decodeDouble("double")); if (!decodeOnly) { kv.encode("string", "Hello from mmkv", expiration); } Log.i("MMKV", "string: " + kv.decodeString("string")); if (!decodeOnly) { byte[] bytes = {'m', 'm', 'k', 'v'}; kv.encode("bytes", bytes, expiration); } byte[] bytes = kv.decodeBytes("bytes"); if (bytes != null) { Log.i("MMKV", "bytes: " + new String(bytes)); Log.i("MMKV", "bytes length = " + bytes.length + ", value size consumption = " + kv.getValueSize("bytes") + ", value size = " + kv.getValueActualSize("bytes")); int sizeNeeded = kv.getValueActualSize("bytes"); NativeBuffer nativeBuffer = MMKV.createNativeBuffer(sizeNeeded); if (nativeBuffer != null) { int size = kv.writeValueToNativeBuffer("bytes", nativeBuffer); Log.i("MMKV", "size Needed = " + sizeNeeded + " written size = " + size); MMKV.destroyNativeBuffer(nativeBuffer); } } if (!decodeOnly) { TestParcelable testParcelable = new TestParcelable(1024, "Hi Parcelable"); kv.encode("parcel", testParcelable, expiration); } TestParcelable result = kv.decodeParcelable("parcel", TestParcelable.class); if (result != null) { Log.i("MMKV", "parcel: " + result.iValue + ", " + result.sValue + ", " + result.list); } if (!decodeOnly) { kv.encode("null string", "some string", expiration); } Log.i("MMKV", "string before set null: " + kv.decodeString("null string")); if (!decodeOnly) { kv.encode("null string", (String) null, expiration); } Log.i("MMKV", "string after set null: " + kv.decodeString("null string") + ", containsKey:" + kv.contains("null string")); Log.i("MMKV", "allKeys: " + Arrays.toString(kv.allNonExpireKeys())); Log.i("MMKV", "count = " + kv.countNonExpiredKeys() + ", totalSize = " + kv.totalSize() + ", actualSize = " + kv.actualSize()); Log.i("MMKV", "containsKey[string]: " + kv.containsKey("string")); } private void testAutoExpire() { MMKV mmkv = MMKV.mmkvWithID("test_auto_expire"); mmkv.clearAll(); mmkv.disableAutoKeyExpire(); mmkv.enableAutoKeyExpire(1); mmkv.encode("auto_expire_key_1", true); mmkv.encode("never_expire_key_1", true, MMKV.ExpireNever); testAutoExpire(mmkv, false, 1); SystemClock.sleep(1000 * 2); testAutoExpire(mmkv, true, 1); // mmkv.encode("string", "Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJFbHFTUjB"); // mmkv.clearMemoryCache(); // Log.i("MMKV", "space string = " + mmkv.decodeString("string", "")); if (mmkv.contains("auto_expire_key_1")) { Log.e("MMKV", "auto key expiration auto_expire_key_1"); } else { Log.i("MMKV", "auto key expiration auto_expire_key_1"); } if (mmkv.contains("never_expire_key_1")) { Log.i("MMKV", "auto key expiration never_expire_key_1"); } else { Log.e("MMKV", "auto key expiration never_expire_key_1"); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/MultiProcessSharedPreferences.java
Java
package com.tencent.mmkvdemo; import android.content.BroadcastReceiver; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ProviderInfo; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Bundle; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * 使用ContentProvider实现多进程SharedPreferences读写;<br> * 1、ContentProvider天生支持多进程访问;<br> * 2、使用内部私有BroadcastReceiver实现多进程OnSharedPreferenceChangeListener监听;<br> * * 使用方法:AndroidManifest.xml中添加provider申明:<br> * <pre> * &lt;provider android:name="com.tencent.mm.sdk.patformtools.MultiProcessSharedPreferences" * android:authorities="com.tencent.mm.sdk.patformtools.MultiProcessSharedPreferences" * android:exported="false" /&gt; * &lt;!-- authorities属性里面最好使用包名做前缀,apk在安装时authorities同名的provider需要校验签名,否则无法安装;--!/&gt;<br> * </pre> * * ContentProvider方式实现要注意:<br> * 1、当ContentProvider所在进程android.os.Process.killProcess(pid)时,会导致整个应用程序完全意外退出或者ContentProvider所在进程重启;<br> * 重启报错信息:Acquiring provider <processName> for user 0: existing object's process dead;<br> * 2、如果设备处在“安全模式”下,只有系统自带的ContentProvider才能被正常解析使用,因此put值时默认返回false,get值时默认返回null;<br> * * 其他方式实现SharedPreferences的问题:<br> * 使用FileLock和FileObserver也可以实现多进程SharedPreferences读写,但是会有兼容性问题:<br> * 1、某些设备上卸载程序时锁文件无法删除导致卸载残留,进而导致无法重新安装该程序(报INSTALL_FAILED_UID_CHANGED错误);<br> * 2、某些设备上FileLock会导致僵尸进程出现进而导致耗电;<br> * 3、僵尸进程出现后,正常进程的FileLock会一直阻塞等待僵尸进程中的FileLock释放,导致进程一直阻塞;<br> * * @author seven456@gmail.com * @version 1.0 * @since JDK1.6 * */ public class MultiProcessSharedPreferences extends ContentProvider implements SharedPreferences { private static final String TAG = "MicroMsg.MultiProcessSharedPreferences"; public static final boolean DEBUG = BuildConfig.DEBUG; private Context mContext; private String mName; private int mMode; private boolean mIsSafeMode; private List<SoftReference<OnSharedPreferenceChangeListener>> mListeners; private BroadcastReceiver mReceiver; private static String AUTHORITY; private static volatile Uri AUTHORITY_URI; private UriMatcher mUriMatcher; private static final String KEY = "value"; private static final String KEY_NAME = "name"; private static final String PATH_WILDCARD = "*/"; private static final String PATH_GET_ALL = "getAll"; private static final String PATH_GET_STRING = "getString"; private static final String PATH_GET_INT = "getInt"; private static final String PATH_GET_LONG = "getLong"; private static final String PATH_GET_FLOAT = "getFloat"; private static final String PATH_GET_BOOLEAN = "getBoolean"; private static final String PATH_CONTAINS = "contains"; private static final String PATH_APPLY = "apply"; private static final String PATH_COMMIT = "commit"; private static final String PATH_REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER = "registerOnSharedPreferenceChangeListener"; private static final String PATH_UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER = "unregisterOnSharedPreferenceChangeListener"; private static final int GET_ALL = 1; private static final int GET_STRING = 2; private static final int GET_INT = 3; private static final int GET_LONG = 4; private static final int GET_FLOAT = 5; private static final int GET_BOOLEAN = 6; private static final int CONTAINS = 7; private static final int APPLY = 8; private static final int COMMIT = 9; private static final int REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER = 10; private static final int UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER = 11; private Map<String, Integer> mListenersCount; private static class ReflectionUtil { public static ContentValues contentValuesNewInstance(HashMap<String, Object> values) { try { Constructor<ContentValues> c = ContentValues.class.getDeclaredConstructor(new Class[] {HashMap.class}); // hide c.setAccessible(true); return c.newInstance(values); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } public static Editor editorPutStringSet(Editor editor, String key, Set<String> values) { try { Method method = editor.getClass().getDeclaredMethod( "putStringSet", new Class[] {String.class, Set.class}); // Android 3.0 return (Editor) method.invoke(editor, key, values); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static void editorApply(Editor editor) { try { Method method = editor.getClass().getDeclaredMethod("apply"); // Android 2.3 method.invoke(editor); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } private void checkInitAuthority(Context context) { if (AUTHORITY_URI == null) { String AUTHORITY = null; Uri AUTHORITY_URI = MultiProcessSharedPreferences.AUTHORITY_URI; synchronized (MultiProcessSharedPreferences.this) { if (AUTHORITY_URI == null) { AUTHORITY = queryAuthority(context); AUTHORITY_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + "://" + AUTHORITY); if (DEBUG) { // Log.d(TAG, "checkInitAuthority.AUTHORITY = " + AUTHORITY); } } if (AUTHORITY == null) { throw new IllegalArgumentException("'AUTHORITY' initialize failed."); } } MultiProcessSharedPreferences.AUTHORITY = AUTHORITY; MultiProcessSharedPreferences.AUTHORITY_URI = AUTHORITY_URI; } } private static String queryAuthority(Context context) { PackageInfo packageInfos = null; try { PackageManager mgr = context.getPackageManager(); if (mgr != null) { packageInfos = mgr.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS); } } catch (NameNotFoundException e) { if (DEBUG) { // Log.printErrStackTrace(TAG, e, ""); } } if (packageInfos != null && packageInfos.providers != null) { for (ProviderInfo providerInfo : packageInfos.providers) { if (providerInfo.name.equals(MultiProcessSharedPreferences.class.getName())) { return providerInfo.authority; } } } return null; } /** * mode不使用{@link Context#MODE_MULTI_PROCESS}特可以支持多进程了; * * @param mode * * @see Context#MODE_PRIVATE * @see Context#MODE_WORLD_READABLE * @see Context#MODE_WORLD_WRITEABLE */ public static SharedPreferences getSharedPreferences(Context context, String name, int mode) { return new MultiProcessSharedPreferences(context, name, mode); } public MultiProcessSharedPreferences() { } private MultiProcessSharedPreferences(Context context, String name, int mode) { mContext = context; mName = name; mMode = mode; PackageManager mgr = context.getPackageManager(); if (mgr != null) { mIsSafeMode = mgr.isSafeMode(); // 如果设备处在“安全模式”下,只有系统自带的ContentProvider才能被正常解析使用; } } @SuppressWarnings("unchecked") @Override public Map<String, ?> getAll() { return (Map<String, ?>) getValue(PATH_GET_ALL, null, null); } @Override public String getString(String key, String defValue) { String v = (String) getValue(PATH_GET_STRING, key, defValue); return v != null ? v : defValue; } // @Override // Android 3.0 public Set<String> getStringSet(String key, Set<String> defValues) { synchronized (this) { @SuppressWarnings("unchecked") Set<String> v = (Set<String>) getValue(PATH_GET_STRING, key, defValues); return v != null ? v : defValues; } } @Override public int getInt(String key, int defValue) { Integer v = (Integer) getValue(PATH_GET_INT, key, defValue); return v != null ? v : defValue; } @Override public long getLong(String key, long defValue) { Long v = (Long) getValue(PATH_GET_LONG, key, defValue); return v != null ? v : defValue; } @Override public float getFloat(String key, float defValue) { Float v = (Float) getValue(PATH_GET_FLOAT, key, defValue); return v != null ? v : defValue; } @Override public boolean getBoolean(String key, boolean defValue) { Boolean v = (Boolean) getValue(PATH_GET_BOOLEAN, key, defValue); return v != null ? v : defValue; } @Override public boolean contains(String key) { Boolean v = (Boolean) getValue(PATH_CONTAINS, key, null); return v != null ? v : false; } @Override public Editor edit() { return new EditorImpl(); } @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized (this) { if (mListeners == null) { mListeners = new ArrayList<SoftReference<OnSharedPreferenceChangeListener>>(); } Boolean result = (Boolean) getValue(PATH_REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER, null, false); if (result != null && result) { mListeners.add(new SoftReference<OnSharedPreferenceChangeListener>(listener)); if (mReceiver == null) { mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String name = intent.getStringExtra(KEY_NAME); @SuppressWarnings("unchecked") List<String> keysModified = (List<String>) intent.getSerializableExtra(KEY); if (mName.equals(name) && keysModified != null) { List arrayListeners; synchronized (MultiProcessSharedPreferences.this) { arrayListeners = mListeners; } List<SoftReference<OnSharedPreferenceChangeListener>> listeners = new ArrayList<SoftReference<OnSharedPreferenceChangeListener>>(arrayListeners); for (int i = keysModified.size() - 1; i >= 0; i--) { final String key = keysModified.get(i); for (SoftReference<OnSharedPreferenceChangeListener> srlistener : listeners) { OnSharedPreferenceChangeListener listener = srlistener.get(); if (listener != null) { listener.onSharedPreferenceChanged(MultiProcessSharedPreferences.this, key); } } } } } }; mContext.registerReceiver(mReceiver, new IntentFilter(makeAction(mName))); } } } } @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized (this) { getValue(PATH_UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER, null, false); if (mListeners != null) { List<SoftReference<OnSharedPreferenceChangeListener>> removing = new ArrayList<>(); for (SoftReference<OnSharedPreferenceChangeListener> srlistener : mListeners) { OnSharedPreferenceChangeListener listenerFromSR = srlistener.get(); if (listenerFromSR != null && listenerFromSR.equals(listener)) { removing.add(srlistener); } } for (SoftReference<OnSharedPreferenceChangeListener> srlistener : removing) { mListeners.remove(srlistener); } if (mListeners.isEmpty() && mReceiver != null) { mContext.unregisterReceiver(mReceiver); mReceiver = null; mListeners = null; } } } } public final class EditorImpl implements Editor { private final Map<String, Object> mModified = new HashMap<String, Object>(); private boolean mClear = false; @Override public Editor putString(String key, String value) { synchronized (this) { mModified.put(key, value); return this; } } // @Override // Android 3.0 public Editor putStringSet(String key, Set<String> values) { synchronized (this) { mModified.put(key, (values == null) ? null : new HashSet<String>(values)); return this; } } @Override public Editor putInt(String key, int value) { synchronized (this) { mModified.put(key, value); return this; } } @Override public Editor putLong(String key, long value) { synchronized (this) { mModified.put(key, value); return this; } } @Override public Editor putFloat(String key, float value) { synchronized (this) { mModified.put(key, value); return this; } } @Override public Editor putBoolean(String key, boolean value) { synchronized (this) { mModified.put(key, value); return this; } } @Override public Editor remove(String key) { synchronized (this) { mModified.put(key, null); return this; } } @Override public Editor clear() { synchronized (this) { mClear = true; return this; } } @Override public void apply() { setValue(PATH_APPLY); } @Override public boolean commit() { return setValue(PATH_COMMIT); } private boolean setValue(String pathSegment) { if (mIsSafeMode) { // 如果设备处在“安全模式”,返回false; return false; } else { synchronized (MultiProcessSharedPreferences.this) { checkInitAuthority(mContext); String[] selectionArgs = new String[] {String.valueOf(mMode), String.valueOf(mClear)}; synchronized (this) { Uri uri = Uri.withAppendedPath(Uri.withAppendedPath(AUTHORITY_URI, mName), pathSegment); ContentValues values = ReflectionUtil.contentValuesNewInstance((HashMap<String, Object>) mModified); return mContext.getContentResolver().update(uri, values, null, selectionArgs) > 0; } } } } } private Object getValue(String pathSegment, String key, Object defValue) { if (mIsSafeMode) { // 如果设备处在“安全模式”,返回null; return null; } else { checkInitAuthority(mContext); Object v = null; Uri uri = Uri.withAppendedPath(Uri.withAppendedPath(AUTHORITY_URI, mName), pathSegment); String[] selectionArgs = new String[] {String.valueOf(mMode), key, defValue == null ? null : String.valueOf(defValue)}; Cursor cursor = mContext.getContentResolver().query(uri, null, null, selectionArgs, null); if (cursor != null) { try { Bundle bundle = cursor.getExtras(); if (bundle != null) { v = bundle.get(KEY); bundle.clear(); } } catch (Exception e) { } cursor.close(); } return v != null ? v : defValue; } } private String makeAction(String name) { return String.format("%1$s_%2$s", MultiProcessSharedPreferences.class.getName(), name); } @Override public boolean onCreate() { checkInitAuthority(getContext()); mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_ALL, GET_ALL); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_STRING, GET_STRING); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_INT, GET_INT); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_LONG, GET_LONG); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_FLOAT, GET_FLOAT); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_GET_BOOLEAN, GET_BOOLEAN); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_CONTAINS, CONTAINS); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_APPLY, APPLY); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_COMMIT, COMMIT); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER, REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER); mUriMatcher.addURI(AUTHORITY, PATH_WILDCARD + PATH_UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER, UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String name = uri.getPathSegments().get(0); int mode = Integer.parseInt(selectionArgs[0]); String key = selectionArgs[1]; String defValue = selectionArgs[2]; Bundle bundle = new Bundle(); switch (mUriMatcher.match(uri)) { case GET_ALL: bundle.putSerializable(KEY, (HashMap<String, ?>) getContext().getSharedPreferences(name, mode).getAll()); break; case GET_STRING: bundle.putString(KEY, getContext().getSharedPreferences(name, mode).getString(key, defValue)); break; case GET_INT: bundle.putInt(KEY, getContext().getSharedPreferences(name, mode).getInt(key, Integer.parseInt(defValue))); break; case GET_LONG: bundle.putLong(KEY, getContext().getSharedPreferences(name, mode).getLong(key, Long.parseLong(defValue))); break; case GET_FLOAT: bundle.putFloat( KEY, getContext().getSharedPreferences(name, mode).getFloat(key, Float.parseFloat(defValue))); break; case GET_BOOLEAN: bundle.putBoolean( KEY, getContext().getSharedPreferences(name, mode).getBoolean(key, Boolean.parseBoolean(defValue))); break; case CONTAINS: bundle.putBoolean(KEY, getContext().getSharedPreferences(name, mode).contains(key)); break; case REGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER: { checkInitListenersCount(); Integer countInteger = mListenersCount.get(name); int count = (countInteger == null ? 0 : countInteger) + 1; mListenersCount.put(name, count); countInteger = mListenersCount.get(name); bundle.putBoolean(KEY, count == (countInteger == null ? 0 : countInteger)); } break; case UNREGISTER_ON_SHARED_PREFERENCE_CHANGE_LISTENER: { checkInitListenersCount(); Integer countInteger = mListenersCount.get(name); int count = (countInteger == null ? 0 : countInteger) - 1; if (count <= 0) { mListenersCount.remove(name); bundle.putBoolean(KEY, !mListenersCount.containsKey(name)); } else { mListenersCount.put(name, count); countInteger = mListenersCount.get(name); bundle.putBoolean(KEY, count == (countInteger == null ? 0 : countInteger)); } } break; default: throw new IllegalArgumentException("This is Unknown Uri:" + uri); } return new BundleCursor(bundle); } @Override public String getType(Uri uri) { throw new UnsupportedOperationException("No external call"); } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException("No external insert"); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("No external delete"); } @SuppressWarnings("unchecked") @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int result = 0; String name = uri.getPathSegments().get(0); int mode = Integer.parseInt(selectionArgs[0]); SharedPreferences preferences = getContext().getSharedPreferences(name, mode); int match = mUriMatcher.match(uri); switch (match) { case APPLY: case COMMIT: boolean hasListeners = mListenersCount != null && mListenersCount.get(name) != null && mListenersCount.get(name) > 0; ArrayList<String> keysModified = null; Map<String, Object> map = new HashMap(); if (hasListeners) { keysModified = new ArrayList<String>(); map = (Map<String, Object>) preferences.getAll(); } Editor editor = preferences.edit(); boolean clear = Boolean.parseBoolean(selectionArgs[1]); if (clear) { if (hasListeners && map != null && !map.isEmpty()) { for (Map.Entry<String, Object> entry : map.entrySet()) { keysModified.add(entry.getKey()); } } editor.clear(); } for (Map.Entry<String, Object> entry : values.valueSet()) { String k = entry.getKey(); Object v = entry.getValue(); // Android 5.L_preview : "this" is the magic value for a removal mutation. In addition, // setting a value to "null" for a given key is specified to be // equivalent to calling remove on that key. if (v instanceof EditorImpl || v == null) { editor.remove(k); if (hasListeners && map != null && map.containsKey(k)) { keysModified.add(k); } } else { if (hasListeners && map != null && (!map.containsKey(k) || (map.containsKey(k) && !v.equals(map.get(k))))) { keysModified.add(k); } } if (v instanceof String) { editor.putString(k, (String) v); } else if (v instanceof Set) { ReflectionUtil.editorPutStringSet(editor, k, (Set<String>) v); // Android 3.0 } else if (v instanceof Integer) { editor.putInt(k, (Integer) v); } else if (v instanceof Long) { editor.putLong(k, (Long) v); } else if (v instanceof Float) { editor.putFloat(k, (Float) v); } else if (v instanceof Boolean) { editor.putBoolean(k, (Boolean) v); } } if (hasListeners && keysModified.isEmpty()) { result = 1; } else { switch (match) { case APPLY: ReflectionUtil.editorApply(editor); // Android 2.3 result = 1; // Okay to notify the listeners before it's hit disk // because the listeners should always get the same // SharedPreferences instance back, which has the // changes reflected in memory. notifyListeners(name, keysModified); break; case COMMIT: if (editor.commit()) { result = 1; notifyListeners(name, keysModified); } break; } } values.clear(); break; default: throw new IllegalArgumentException("This is Unknown Uri:" + uri); } return result; } @Override public void onLowMemory() { if (mListenersCount != null) { mListenersCount.clear(); } super.onLowMemory(); } @Override public void onTrimMemory(int level) { if (mListenersCount != null) { mListenersCount.clear(); } super.onTrimMemory(level); } private void checkInitListenersCount() { if (mListenersCount == null) { mListenersCount = new HashMap<String, Integer>(); } } private void notifyListeners(String name, ArrayList<String> keysModified) { if (keysModified != null && !keysModified.isEmpty()) { Intent intent = new Intent(); intent.setAction(makeAction(name)); intent.setPackage(getContext().getPackageName()); intent.putExtra(KEY_NAME, name); intent.putExtra(KEY, keysModified); getContext().sendBroadcast(intent); } } private static final class BundleCursor extends MatrixCursor { private Bundle mBundle; public BundleCursor(Bundle extras) { super(new String[] {}, 0); mBundle = extras; } @Override public Bundle getExtras() { return mBundle; } @Override public Bundle respond(Bundle extras) { mBundle = extras; return mBundle; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/MyApplication.java
Java
package com.tencent.mmkvdemo; import android.app.Application; import android.util.Log; import com.getkeepsafe.relinker.ReLinker; import com.tencent.mmkv.MMKV; import com.tencent.mmkv.MMKVContentChangeNotification; import com.tencent.mmkv.MMKVHandler; import com.tencent.mmkv.MMKVLogLevel; import com.tencent.mmkv.MMKVRecoverStrategic; public class MyApplication extends Application implements MMKVHandler, MMKVContentChangeNotification { @Override public void onCreate() { super.onCreate(); // set root dir //String rootDir = MMKV.initialize(this); String dir = getFilesDir().getAbsolutePath() + "/mmkv"; String rootDir = MMKV.initialize(this, dir, new MMKV.LibLoader() { @Override public void loadLibrary(String libName) { ReLinker.loadLibrary(MyApplication.this, libName); } }, MMKVLogLevel.LevelInfo,this); Log.i("MMKV", "mmkv root: " + rootDir); // set log level // MMKV.setLogLevel(MMKVLogLevel.LevelInfo); // you can turn off logging //MMKV.setLogLevel(MMKVLogLevel.LevelNone); // register log redirecting & recover handler is moved into MMKV.initialize() // MMKV.registerHandler(this); // content change notification MMKV.registerContentChangeNotify(this); } @Override public void onTerminate() { MMKV.onExit(); super.onTerminate(); } @Override public MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID) { return MMKVRecoverStrategic.OnErrorRecover; } @Override public MMKVRecoverStrategic onMMKVFileLengthError(String mmapID) { return MMKVRecoverStrategic.OnErrorRecover; } @Override public boolean wantLogRedirecting() { return true; } @Override public void mmkvLog(MMKVLogLevel level, String file, int line, String func, String message) { String log = "<" + file + ":" + line + "::" + func + "> " + message; switch (level) { case LevelDebug: Log.d("redirect logging MMKV", log); break; case LevelNone: case LevelInfo: Log.i("redirect logging MMKV", log); break; case LevelWarning: Log.w("redirect logging MMKV", log); break; case LevelError: Log.e("redirect logging MMKV", log); break; } } @Override public void onContentChangedByOuterProcess(String mmapID) { Log.i("MMKV", "other process has changed content of : " + mmapID); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/MyService.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import android.content.Intent; import android.util.Log; import com.tencent.mmkv.MMKV; public class MyService extends BenchMarkBaseService { private static final String CALLER = "MyService"; public static final String CMD_REMOVE = "cmd_remove"; public static final String CMD_LOCK = "cmd_lock"; public static final String LOCK_PHASE_1 = "lock_phase_1"; public static final String LOCK_PHASE_2 = "lock_phase_2"; public static final String CMD_TRIM_FINISH = "trim_finish"; @Override public void onCreate() { super.onCreate(); Log.i("MMKV", "onCreate MyService"); } @Override public void onDestroy() { super.onDestroy(); Log.i("MMKV", "onDestroy MyService"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("MMKV", "MyService onStartCommand"); if (intent != null) { String cmd = intent.getStringExtra(CMD_ID); if (cmd != null) { if (cmd.equals(CMD_READ_INT)) { super.batchReadInt(CALLER); } else if (cmd.equals(CMD_READ_STRING)) { super.batchReadString(CALLER); } else if (cmd.equals(CMD_WRITE_INT)) { super.batchWriteInt(CALLER); } else if (cmd.equals(CMD_WRITE_STRING)) { super.batchWriteString(CALLER); } else if (cmd.equals(CMD_PREPARE_ASHMEM_BY_CP)) { super.prepareAshmemMMKVByCP(); } else if (cmd.equals(CMD_REMOVE)) { testRemove(); } else if (cmd.equals(CMD_LOCK)) { testLock(); } else if (cmd.equals(CMD_TRIM_FINISH)) { testTrimNonEmpty(); } } } return super.onStartCommand(intent, flags, startId); } private void testRemove() { MMKV mmkv = GetMMKV(); Log.d("mmkv in child", "" + mmkv.decodeInt(CMD_ID)); mmkv.remove(CMD_ID); } private void testLock() { // get the lock immediately MMKV mmkv2 = MMKV.mmkvWithID(LOCK_PHASE_2, MMKV.MULTI_PROCESS_MODE); mmkv2.lock(); Log.d("locked in child", LOCK_PHASE_2); Runnable waiter = new Runnable() { @Override public void run() { MMKV mmkv1 = MMKV.mmkvWithID(LOCK_PHASE_1, MMKV.MULTI_PROCESS_MODE); mmkv1.lock(); Log.d("locked in child", LOCK_PHASE_1); } }; // wait infinitely new Thread(waiter).start(); } private void testTrimNonEmpty() { MMKV mmkv = MMKV.mmkvWithID("trimNonEmptyInterProcess", MMKV.MULTI_PROCESS_MODE); byte[] value = new byte[64]; mmkv.encode("SomeKey", value); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/MyService_1.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.tencent.mmkv.ParcelableMMKV; public class MyService_1 extends BenchMarkBaseService implements ServiceConnection { public static final String CMD_PREPARE_ASHMEM = "cmd_prepare_ashmem"; private static final String CALLER = "MyService_1"; @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("MMKV", "MyService_1 onStartCommand:"); if (intent != null) { String cmd = intent.getStringExtra(CMD_ID); Log.i("MMKV", "----MyService_1 onStartCommand:" + cmd); if (cmd != null) { if (cmd.equals(CMD_READ_INT)) { super.batchReadInt(CALLER); } else if (cmd.equals(CMD_READ_STRING)) { super.batchReadString(CALLER); } else if (cmd.equals(CMD_WRITE_INT)) { super.batchWriteInt(CALLER); } else if (cmd.equals(CMD_WRITE_STRING)) { super.batchWriteString(CALLER); } else if (cmd.equals(CMD_PREPARE_ASHMEM)) { Intent i = new Intent("com.tencent.mmkvdemo.MyService").setPackage("com.tencent.mmkvdemo"); bindService(i, this, BIND_AUTO_CREATE); } else if (cmd.equals(CMD_PREPARE_ASHMEM_BY_CP)) { super.prepareAshmemMMKVByCP(); } } } return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); Log.i("MMKV", "onCreate MyService_1"); } @Override public void onDestroy() { super.onDestroy(); Log.i("MMKV", "onDestroy MyService_1"); } @Override public void onServiceConnected(ComponentName name, IBinder service) { IAshmemMMKV ashmemMMKV = IAshmemMMKV.Stub.asInterface(service); try { ParcelableMMKV parcelableMMKV = ashmemMMKV.GetAshmemMMKV(); if (parcelableMMKV != null) { m_ashmemMMKV = parcelableMMKV.toMMKV(); if (m_ashmemMMKV != null) { Log.i("MMKV", "ashmem bool: " + m_ashmemMMKV.decodeBool("bool")); } } } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/SQLiteKV.java
Java
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mmkvdemo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public final class SQLiteKV { private static class SQLiteKVDBHelper extends SQLiteOpenHelper { private static final int DB_VERSION = 1; private static final String DB_NAME = "kv.db"; public static final String TABLE_NAME_STR = "kv_str"; public static final String TABLE_NAME_INT = "kv_int"; public SQLiteKVDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String sql = "create table if not exists " + TABLE_NAME_STR + " (k text UNIQUE on conflict replace, v text)"; sqLiteDatabase.execSQL(sql); sql = "create table if not exists " + TABLE_NAME_INT + " (k text UNIQUE on conflict replace, v integer)"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME_STR; sqLiteDatabase.execSQL(sql); sql = "DROP TABLE IF EXISTS " + TABLE_NAME_INT; sqLiteDatabase.execSQL(sql); onCreate(sqLiteDatabase); } } private SQLiteKVDBHelper m_dbHelper; private SQLiteDatabase m_writetableDB; private SQLiteDatabase m_readableDB; public SQLiteKV(Context context) { m_dbHelper = new SQLiteKVDBHelper(context); m_dbHelper.setWriteAheadLoggingEnabled(true); } public void beginTransaction() { getWritetableDB().beginTransaction(); } public void endTransaction() { if (m_writetableDB != null) { try { m_writetableDB.setTransactionSuccessful(); } finally { m_writetableDB.endTransaction(); } } } private SQLiteDatabase getWritetableDB() { if (m_writetableDB == null) { m_writetableDB = m_dbHelper.getWritableDatabase(); } return m_writetableDB; } private SQLiteDatabase getReadableDatabase() { if (m_readableDB == null) { m_readableDB = m_dbHelper.getReadableDatabase(); } return m_readableDB; } @Override protected void finalize() throws Throwable { if (m_readableDB != null) { m_readableDB.close(); } if (m_writetableDB != null) { m_writetableDB.close(); } super.finalize(); } public boolean putInt(String key, int value) { ContentValues contentValues = new ContentValues(); contentValues.put("k", key); contentValues.put("v", value); long rowID = getWritetableDB().insert(SQLiteKVDBHelper.TABLE_NAME_INT, null, contentValues); return rowID != -1; } public int getInt(String key) { int value = 0; Cursor cursor = getReadableDatabase().rawQuery( "select v from " + SQLiteKVDBHelper.TABLE_NAME_INT + " where k=?", new String[] {key}); if (cursor.moveToFirst()) { value = cursor.getInt(cursor.getColumnIndex("v")); } cursor.close(); return value; } public boolean putString(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put("k", key); contentValues.put("v", value); long rowID = getWritetableDB().insert(SQLiteKVDBHelper.TABLE_NAME_STR, null, contentValues); return rowID != -1; } public String getString(String key) { String value = null; Cursor cursor = getReadableDatabase().rawQuery( "select v from " + SQLiteKVDBHelper.TABLE_NAME_STR + " where k=?", new String[] {key}); if (cursor.moveToFirst()) { value = cursor.getString(cursor.getColumnIndex("v")); } cursor.close(); return value; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
Mmkvdemo/src/main/java/com/tencent/mmkvdemo/TestParcelable.java
Java
package com.tencent.mmkvdemo; import android.os.Parcel; import android.os.Parcelable; import java.util.LinkedList; import java.util.List; class TestParcelable implements Parcelable { int iValue; String sValue; List<FakeInfo> list; @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(iValue); parcel.writeString(sValue); // parcel.writeTypedList(list); } @Override public int describeContents() { return 0; } TestParcelable(int i, String s) { iValue = i; sValue = s; // list = new LinkedList<>(); // list.add(new Info("channel", 1)); // list.add(new Info("oppo", 2)); } private TestParcelable(Parcel in) { iValue = in.readInt(); sValue = in.readString(); list = in.createTypedArrayList(FakeInfo.CREATOR); } public static final Creator<TestParcelable> CREATOR = new Creator<TestParcelable>() { @Override public TestParcelable createFromParcel(Parcel parcel) { return new TestParcelable(parcel); } @Override public TestParcelable[] newArray(int i) { return new TestParcelable[i]; } }; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { //noinspection MinSdkTooLow minSdkVersion 9 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/ApkLibraryInstaller.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ApplicationInfo; import android.os.Build; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ApkLibraryInstaller implements ReLinker.LibraryInstaller { private static final int MAX_TRIES = 5; private static final int COPY_BUFFER_SIZE = 4096; private String[] sourceDirectories(final Context context) { final ApplicationInfo appInfo = context.getApplicationInfo(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && appInfo.splitSourceDirs != null && appInfo.splitSourceDirs.length != 0) { String[] apks = new String[appInfo.splitSourceDirs.length + 1]; apks[0] = appInfo.sourceDir; System.arraycopy(appInfo.splitSourceDirs, 0, apks, 1, appInfo.splitSourceDirs.length); return apks; } else { return new String[] { appInfo.sourceDir }; } } private static class ZipFileInZipEntry { public ZipFile zipFile; public ZipEntry zipEntry; public ZipFileInZipEntry(ZipFile zipFile, ZipEntry zipEntry) { this.zipFile = zipFile; this.zipEntry = zipEntry; } } private ZipFileInZipEntry findAPKWithLibrary(final Context context, final String[] abis, final String mappedLibraryName, final ReLinkerInstance instance) { for (String sourceDir : sourceDirectories(context)) { ZipFile zipFile = null; int tries = 0; while (tries++ < MAX_TRIES) { try { zipFile = new ZipFile(new File(sourceDir), ZipFile.OPEN_READ); break; } catch (IOException ignored) { } } if (zipFile == null) { continue; } tries = 0; while (tries++ < MAX_TRIES) { String jniNameInApk = null; ZipEntry libraryEntry = null; for (final String abi : abis) { jniNameInApk = "lib" + File.separatorChar + abi + File.separatorChar + mappedLibraryName; instance.log("Looking for %s in APK %s...", jniNameInApk, sourceDir); libraryEntry = zipFile.getEntry(jniNameInApk); if (libraryEntry != null) { return new ZipFileInZipEntry(zipFile, libraryEntry); } } } try { zipFile.close(); } catch (IOException ignored) { } } return null; } // Loop over all APK's again in order to detect which ABI's are actually supported. // This second loop is more expensive than trying to find a specific ABI, so it should // only be ran when no matching libraries are found. This should keep the overhead of // the happy path to a minimum. private String[] getSupportedABIs(Context context, String mappedLibraryName) { String p = "lib" + File.separatorChar + "([^\\" + File.separatorChar + "]*)" + File.separatorChar + mappedLibraryName; Pattern pattern = Pattern.compile(p); ZipFile zipFile; Set<String> supportedABIs = new HashSet<String>(); for (String sourceDir : sourceDirectories(context)) { try { zipFile = new ZipFile(new File(sourceDir), ZipFile.OPEN_READ); } catch (IOException ignored) { continue; } Enumeration<? extends ZipEntry> elements = zipFile.entries(); while (elements.hasMoreElements()) { ZipEntry el = elements.nextElement(); Matcher match = pattern.matcher(el.getName()); if (match.matches()) { supportedABIs.add(match.group(1)); } } } String[] result = new String[supportedABIs.size()]; return supportedABIs.toArray(result); } /** * Attempts to unpack the given library to the given destination. Implements retry logic for * IO operations to ensure they succeed. * * @param context {@link Context} to describe the location of the installed APK file * @param mappedLibraryName The mapped name of the library file to load */ @SuppressLint ("SetWorldReadable") @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void installLibrary(final Context context, final String[] abis, final String mappedLibraryName, final File destination, final ReLinkerInstance instance) { ZipFileInZipEntry found = null; try { found = findAPKWithLibrary(context, abis, mappedLibraryName, instance); if (found == null) { // Does not exist in any APK. Report exactly what ReLinker is looking for and // what is actually supported by the APK. String[] supportedABIs; try { supportedABIs = getSupportedABIs(context, mappedLibraryName); } catch (Exception e) { // Should never happen as this indicates a bug in ReLinker code, but just to be safe. // User code should only ever crash with a MissingLibraryException if getting this far. supportedABIs = new String[1]; supportedABIs[0] = e.toString(); } throw new MissingLibraryException(mappedLibraryName, abis, supportedABIs); } int tries = 0; while (tries++ < MAX_TRIES) { instance.log("Found %s! Extracting...", mappedLibraryName); try { if (!destination.exists() && !destination.createNewFile()) { continue; } } catch (IOException ignored) { // Try again continue; } InputStream inputStream = null; FileOutputStream fileOut = null; try { inputStream = found.zipFile.getInputStream(found.zipEntry); fileOut = new FileOutputStream(destination); final long written = copy(inputStream, fileOut); fileOut.getFD().sync(); if (written != destination.length()) { // File was not written entirely... Try again continue; } } catch (FileNotFoundException e) { // Try again continue; } catch (IOException e) { // Try again continue; } finally { closeSilently(inputStream); closeSilently(fileOut); } // Change permission to rwxr-xr-x destination.setReadable(true, false); destination.setExecutable(true, false); destination.setWritable(true); return; } instance.log("FATAL! Couldn't extract the library from the APK!"); } finally { try { if (found != null && found.zipFile != null) { found.zipFile.close(); } } catch (IOException ignored) {} } } /** * Copies all data from an {@link InputStream} to an {@link OutputStream}. * * @param in The stream to read from. * @param out The stream to write to. * @throws IOException when a stream operation fails. * @return The actual number of bytes copied */ private long copy(InputStream in, OutputStream out) throws IOException { long copied = 0; byte[] buf = new byte[COPY_BUFFER_SIZE]; while (true) { int read = in.read(buf); if (read == -1) { break; } out.write(buf, 0, read); copied += read; } out.flush(); return copied; } /** * Closes a {@link Closeable} silently (without throwing or handling any exceptions) * @param closeable {@link Closeable} to close */ private void closeSilently(final Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignored) {} } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/MissingLibraryException.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; import java.util.Arrays; public class MissingLibraryException extends RuntimeException { public MissingLibraryException(final String library, final String[] wantedABIs, final String[] supportedABIs) { super("Could not find '" + library + "'. " + "Looked for: " + Arrays.toString(wantedABIs) + ", " + "but only found: " + Arrays.toString(supportedABIs) + "."); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/ReLinker.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; import android.content.Context; import java.io.File; /** * ReLinker is a small library to help alleviate {@link UnsatisfiedLinkError} exceptions thrown due * to Android's inability to properly install / load native libraries for Android versions before * API 23. */ public class ReLinker { public interface LoadListener { void success(); void failure(Throwable t); } public interface Logger { void log(String message); } public interface LibraryLoader { void loadLibrary(String libraryName); void loadPath(String libraryPath); String mapLibraryName(String libraryName); String unmapLibraryName(String mappedLibraryName); String[] supportedAbis(); } public interface LibraryInstaller { void installLibrary(Context context, String[] abis, String mappedLibraryName, File destination, ReLinkerInstance logger); } public static void loadLibrary(final Context context, final String library) { loadLibrary(context, library, null, null); } public static void loadLibrary(final Context context, final String library, final String version) { loadLibrary(context, library, version, null); } public static void loadLibrary(final Context context, final String library, final LoadListener listener) { loadLibrary(context, library, null, listener); } public static void loadLibrary(final Context context, final String library, final String version, final ReLinker.LoadListener listener) { new ReLinkerInstance().loadLibrary(context, library, version, listener); } public static ReLinkerInstance force() { return new ReLinkerInstance().force(); } public static ReLinkerInstance log(final Logger logger) { return new ReLinkerInstance().log(logger); } public static ReLinkerInstance recursively() { return new ReLinkerInstance().recursively(); } private ReLinker() {} }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/ReLinkerInstance.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; import android.content.Context; import android.util.Log; import com.getkeepsafe.relinker.elf.ElfParser; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; public class ReLinkerInstance { private static final String LIB_DIR = "lib"; protected final Set<String> loadedLibraries = new HashSet<String>(); protected final ReLinker.LibraryLoader libraryLoader; protected final ReLinker.LibraryInstaller libraryInstaller; protected boolean force; protected boolean recursive; protected ReLinker.Logger logger; protected ReLinkerInstance() { this(new SystemLibraryLoader(), new ApkLibraryInstaller()); } protected ReLinkerInstance(final ReLinker.LibraryLoader libraryLoader, final ReLinker.LibraryInstaller libraryInstaller) { if (libraryLoader == null) { throw new IllegalArgumentException("Cannot pass null library loader"); } if (libraryInstaller == null) { throw new IllegalArgumentException("Cannot pass null library installer"); } this.libraryLoader = libraryLoader; this.libraryInstaller = libraryInstaller; } /** * Logs debugging related information to the {@link ReLinker.Logger} instance given */ public ReLinkerInstance log(final ReLinker.Logger logger) { this.logger = logger; return this; } /** * Forces any previously extracted / re-linked libraries to be cleaned up before loading */ public ReLinkerInstance force() { this.force = true; return this; } /** * Enables recursive library loading to resolve and load shared object -&gt; shared object * defined dependencies */ public ReLinkerInstance recursively() { this.recursive = true; return this; } /** * Utilizes the regular system call to attempt to load a native library. If a failure occurs, * then the function extracts native .so library out of the app's APK and attempts to load it. * <p> * <strong>Note: This is a synchronous operation</strong> */ public void loadLibrary(final Context context, final String library) { loadLibrary(context, library, null, null); } /** * The same call as {@link #loadLibrary(Context, String)}, however if a {@code version} is * provided, then that specific version of the given library is loaded. */ public void loadLibrary(final Context context, final String library, final String version) { loadLibrary(context, library, version, null); } /** * The same call as {@link #loadLibrary(Context, String)}, however if a * {@link ReLinker.LoadListener} is provided, the function is executed asynchronously. */ public void loadLibrary(final Context context, final String library, final ReLinker.LoadListener listener) { loadLibrary(context, library, null, listener); } /** * Attemps to load the given library normally. If that fails, it loads the library utilizing * a workaround. * * @param context The {@link Context} to get a workaround directory from * @param library The library you wish to load * @param version The version of the library you wish to load, or {@code null} * @param listener {@link ReLinker.LoadListener} to listen for async execution, or {@code null} */ public void loadLibrary(final Context context, final String library, final String version, final ReLinker.LoadListener listener) { if (context == null) { throw new IllegalArgumentException("Given context is null"); } if (TextUtils.isEmpty(library)) { throw new IllegalArgumentException("Given library is either null or empty"); } log("Beginning load of %s...", library); if (listener == null) { loadLibraryInternal(context, library, version); } else { new Thread(new Runnable() { @Override public void run() { try { loadLibraryInternal(context, library, version); listener.success(); } catch (UnsatisfiedLinkError e) { listener.failure(e); } catch (MissingLibraryException e) { listener.failure(e); } } }).start(); } } private void loadLibraryInternal(final Context context, final String library, final String version) { if (loadedLibraries.contains(library) && !force) { log("%s already loaded previously!", library); return; } try { libraryLoader.loadLibrary(library); loadedLibraries.add(library); log("%s (%s) was loaded normally!", library, version); return; } catch (final UnsatisfiedLinkError e) { // :-( log("Loading the library normally failed: %s", Log.getStackTraceString(e)); } log("%s (%s) was not loaded normally, re-linking...", library, version); final File workaroundFile = getWorkaroundLibFile(context, library, version); if (!workaroundFile.exists() || force) { if (force) { log("Forcing a re-link of %s (%s)...", library, version); } cleanupOldLibFiles(context, library, version); libraryInstaller.installLibrary(context, libraryLoader.supportedAbis(), libraryLoader.mapLibraryName(library), workaroundFile, this); } try { if (recursive) { ElfParser parser = null; final List<String> dependencies; try { parser = new ElfParser(workaroundFile); dependencies = parser.parseNeededDependencies(); } finally { if (parser != null) { parser.close(); } } for (final String dependency : dependencies) { loadLibrary(context, libraryLoader.unmapLibraryName(dependency)); } } } catch (IOException ignored) { // This a redundant step of the process, if our library resolving fails, it will likely // be picked up by the system's resolver, if not, an exception will be thrown by the // next statement, so its better to try twice. } libraryLoader.loadPath(workaroundFile.getAbsolutePath()); loadedLibraries.add(library); log("%s (%s) was re-linked!", library, version); } /** * @param context {@link Context} to describe the location of it's private directories * @return A {@link File} locating the directory that can store extracted libraries * for later use */ protected File getWorkaroundLibDir(final Context context) { return context.getDir(LIB_DIR, Context.MODE_PRIVATE); } /** * @param context {@link Context} to retrieve the workaround directory from * @param library The name of the library to load * @param version The version of the library to load or {@code null} * @return A {@link File} locating the workaround library file to load */ protected File getWorkaroundLibFile(final Context context, final String library, final String version) { final String libName = libraryLoader.mapLibraryName(library); if (TextUtils.isEmpty(version)) { return new File(getWorkaroundLibDir(context), libName); } return new File(getWorkaroundLibDir(context), libName + "." + version); } /** * Cleans up any <em>other</em> versions of the {@code library}. If {@code force} is used, all * versions of the {@code library} are deleted * * @param context {@link Context} to retrieve the workaround directory from * @param library The name of the library to load * @param currentVersion The version of the library to keep, all other versions will be deleted. * This parameter is ignored if {@code force} is used. */ protected void cleanupOldLibFiles(final Context context, final String library, final String currentVersion) { final File workaroundDir = getWorkaroundLibDir(context); final File workaroundFile = getWorkaroundLibFile(context, library, currentVersion); final String mappedLibraryName = libraryLoader.mapLibraryName(library); final File[] existingFiles = workaroundDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return filename.startsWith(mappedLibraryName); } }); if (existingFiles == null) return; for (final File file : existingFiles) { if (force || !file.getAbsolutePath().equals(workaroundFile.getAbsolutePath())) { file.delete(); } } } public void log(final String format, final Object... args) { log(String.format(Locale.US, format, args)); } public void log(final String message) { if (logger != null) { logger.log(message); } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/SystemLibraryLoader.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; import android.annotation.SuppressLint; import android.os.Build; @SuppressWarnings("deprecation") final class SystemLibraryLoader implements ReLinker.LibraryLoader { @Override public void loadLibrary(final String libraryName) { System.loadLibrary(libraryName); } @SuppressLint ("UnsafeDynamicallyLoadedCode") @Override public void loadPath(final String libraryPath) { System.load(libraryPath); } @Override public String mapLibraryName(final String libraryName) { if (libraryName.startsWith("lib") && libraryName.endsWith(".so")) { // Already mapped return libraryName; } return System.mapLibraryName(libraryName); } @Override public String unmapLibraryName(String mappedLibraryName) { // Assuming libname.so return mappedLibraryName.substring(3, mappedLibraryName.length() - 3); } @Override public String[] supportedAbis() { if (Build.VERSION.SDK_INT >= 21 && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else if (!TextUtils.isEmpty(Build.CPU_ABI2)) { return new String[] {Build.CPU_ABI, Build.CPU_ABI2}; } else { return new String[] {Build.CPU_ABI}; } } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/TextUtils.java
Java
/* * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker; /** * Slimmed down version of https://developer.android.com/reference/android/text/TextUtils.html to * avoid depending on android.text.TextUtils. */ final class TextUtils { private TextUtils() { } /** * Returns true if the string is null or 0-length. * * @param str the string to be examined * @return true if str is null or zero length */ public static boolean isEmpty(CharSequence str) { return str == null || str.length() == 0; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Dynamic32Structure.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Dynamic32Structure extends Elf.DynamicStructure { public Dynamic32Structure(final ElfParser parser, final Elf.Header header, long baseOffset, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); baseOffset = baseOffset + (index * 8); tag = parser.readWord(buffer, baseOffset); val = parser.readWord(buffer, baseOffset + 0x4); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Dynamic64Structure.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Dynamic64Structure extends Elf.DynamicStructure { public Dynamic64Structure(final ElfParser parser, final Elf.Header header, long baseOffset, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); baseOffset = baseOffset + (index * 16); tag = parser.readLong(buffer, baseOffset); val = parser.readLong(buffer, baseOffset + 0x8); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Elf.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; public interface Elf { abstract class Header { public static final int ELFCLASS32 = 1; // 32 Bit ELF public static final int ELFCLASS64 = 2; // 64 Bit ELF public static final int ELFDATA2MSB = 2; // Big Endian, 2s complement public boolean bigEndian; public int type; public long phoff; public long shoff; public int phentsize; public int phnum; public int shentsize; public int shnum; public int shstrndx; abstract public Elf.SectionHeader getSectionHeader(int index) throws IOException; abstract public Elf.ProgramHeader getProgramHeader(long index) throws IOException; abstract public Elf.DynamicStructure getDynamicStructure(long baseOffset, int index) throws IOException; } abstract class ProgramHeader { public static final int PT_LOAD = 1; // Loadable segment public static final int PT_DYNAMIC = 2; // Dynamic linking information public long type; public long offset; public long vaddr; public long memsz; } abstract class SectionHeader { public long info; } abstract class DynamicStructure { public static final int DT_NULL = 0; // Marks end of structure list public static final int DT_NEEDED = 1; // Needed library public static final int DT_STRTAB = 5; // String table public long tag; public long val; // Union with d_ptr } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Elf32Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf32Header extends Elf.Header { private final ElfParser parser; public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readWord(buffer, 0x1C); shoff = parser.readWord(buffer, 0x20); phentsize = parser.readHalf(buffer, 0x2A); phnum = parser.readHalf(buffer, 0x2C); shentsize = parser.readHalf(buffer, 0x2E); shnum = parser.readHalf(buffer, 0x30); shstrndx = parser.readHalf(buffer, 0x32); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section32Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program32Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic32Structure(parser, this, baseOffset, index); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Elf64Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf64Header extends Elf.Header { private final ElfParser parser; public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readLong(buffer, 0x20); shoff = parser.readLong(buffer, 0x28); phentsize = parser.readHalf(buffer, 0x36); phnum = parser.readHalf(buffer, 0x38); shentsize = parser.readHalf(buffer, 0x3A); shnum = parser.readHalf(buffer, 0x3C); shstrndx = parser.readHalf(buffer, 0x3E); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section64Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program64Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic64Structure(parser, this, baseOffset, index); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/ElfParser.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ElfParser implements Closeable, Elf { private final int MAGIC = 0x464C457F; private final FileChannel channel; public ElfParser(final File file) throws FileNotFoundException { if (file == null || !file.exists()) { throw new IllegalArgumentException("File is null or does not exist"); } final FileInputStream inputStream = new FileInputStream(file); this.channel = inputStream.getChannel(); } public Elf.Header parseHeader() throws IOException { channel.position(0L); // Read in ELF identification to determine file class and endianness final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); if (readWord(buffer, 0) != MAGIC) { throw new IllegalArgumentException("Invalid ELF Magic!"); } final short fileClass = readByte(buffer, 0x4); final boolean bigEndian = (readByte(buffer, 0x5) == Header.ELFDATA2MSB); if (fileClass == Header.ELFCLASS32) { return new Elf32Header(bigEndian, this); } else if (fileClass == Header.ELFCLASS64) { return new Elf64Header(bigEndian, this); } throw new IllegalStateException("Invalid class type!"); } public List<String> parseNeededDependencies() throws IOException { channel.position(0); final List<String> dependencies = new ArrayList<String>(); final Elf.Header header = parseHeader(); final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); long numProgramHeaderEntries = header.phnum; if (numProgramHeaderEntries == 0xFFFF) { /** * Extended Numbering * * If the real number of program header table entries is larger than * or equal to PN_XNUM(0xffff), it is set to sh_info field of the * section header at index 0, and PN_XNUM is set to e_phnum * field. Otherwise, the section header at index 0 is zero * initialized, if it exists. **/ final Elf.SectionHeader sectionHeader = header.getSectionHeader(0); numProgramHeaderEntries = sectionHeader.info; } long dynamicSectionOff = 0; for (long i = 0; i < numProgramHeaderEntries; ++i) { final Elf.ProgramHeader programHeader = header.getProgramHeader(i); if (programHeader.type == ProgramHeader.PT_DYNAMIC) { dynamicSectionOff = programHeader.offset; break; } } if (dynamicSectionOff == 0) { // No dynamic linking info, nothing to load return Collections.unmodifiableList(dependencies); } int i = 0; final List<Long> neededOffsets = new ArrayList<Long>(); long vStringTableOff = 0; Elf.DynamicStructure dynStructure; do { dynStructure = header.getDynamicStructure(dynamicSectionOff, i); if (dynStructure.tag == DynamicStructure.DT_NEEDED) { neededOffsets.add(dynStructure.val); } else if (dynStructure.tag == DynamicStructure.DT_STRTAB) { vStringTableOff = dynStructure.val; // d_ptr union } ++i; } while (dynStructure.tag != DynamicStructure.DT_NULL); if (vStringTableOff == 0) { throw new IllegalStateException("String table offset not found!"); } // Map to file offset final long stringTableOff = offsetFromVma(header, numProgramHeaderEntries, vStringTableOff); for (final Long strOff : neededOffsets) { dependencies.add(readString(buffer, stringTableOff + strOff)); } return dependencies; } private long offsetFromVma(final Elf.Header header, final long numEntries, final long vma) throws IOException { for (long i = 0; i < numEntries; ++i) { final Elf.ProgramHeader programHeader = header.getProgramHeader(i); if (programHeader.type == ProgramHeader.PT_LOAD) { // Within memsz instead of filesz to be more tolerant if (programHeader.vaddr <= vma && vma <= programHeader.vaddr + programHeader.memsz) { return vma - programHeader.vaddr + programHeader.offset; } } } throw new IllegalStateException("Could not map vma to file offset!"); } @Override public void close() throws IOException { this.channel.close(); } protected String readString(final ByteBuffer buffer, long offset) throws IOException { final StringBuilder builder = new StringBuilder(); short c; while ((c = readByte(buffer, offset++)) != 0) { builder.append((char) c); } return builder.toString(); } protected long readLong(final ByteBuffer buffer, final long offset) throws IOException { read(buffer, offset, 8); return buffer.getLong(); } protected long readWord(final ByteBuffer buffer, final long offset) throws IOException { read(buffer, offset, 4); return buffer.getInt() & 0xFFFFFFFFL; } protected int readHalf(final ByteBuffer buffer, final long offset) throws IOException { read(buffer, offset, 2); return buffer.getShort() & 0xFFFF; } protected short readByte(final ByteBuffer buffer, final long offset) throws IOException { read(buffer, offset, 1); return (short) (buffer.get() & 0xFF); } protected void read(final ByteBuffer buffer, long offset, final int length) throws IOException { buffer.position(0); buffer.limit(length); long bytesRead = 0; while (bytesRead < length) { final int read = channel.read(buffer, offset + bytesRead); if (read == -1) { throw new EOFException(); } bytesRead += read; } buffer.position(0); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Program32Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program32Header extends Elf.ProgramHeader { public Program32Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset); offset = parser.readWord(buffer, baseOffset + 0x4); vaddr = parser.readWord(buffer, baseOffset + 0x8); memsz = parser.readWord(buffer, baseOffset + 0x14); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Program64Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program64Header extends Elf.ProgramHeader { public Program64Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset); offset = parser.readLong(buffer, baseOffset + 0x8); vaddr = parser.readLong(buffer, baseOffset + 0x10); memsz = parser.readLong(buffer, baseOffset + 0x28); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Section32Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Section32Header extends Elf.SectionHeader { public Section32Header(final ElfParser parser, final Elf.Header header, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
ReLinker/src/main/java/com/getkeepsafe/relinker/elf/Section64Header.java
Java
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getkeepsafe.relinker.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Section64Header extends Elf.SectionHeader { public Section64Header(final ElfParser parser, final Elf.Header header, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SafetyJniLib/build.gradle
Gradle
apply plugin: 'com.android.library' android { compileSdkVersion 29 defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" externalNativeBuild { cmake { cppFlags "" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } buildToolsVersion '29.0.0' } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.annotation:annotation:1.1.0' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SafetyJniLib/src/main/cpp/safetyjnilib.cpp
C++
#include <jni.h> #include <string> // // Created by 杨充 on 2023/6/7. // jstring ByteToHexStr(JNIEnv *env, const char *string, char *result, jsize length); jstring ToMd5(JNIEnv *env, jbyteArray source); jstring loadSignature(JNIEnv *env, jobject context); extern "C" JNIEXPORT jstring JNICALL Java_com_yc_safetyjni_SafetyJniLib_stringFromJNI(JNIEnv *env, jobject thiz) { std::string hello = "Hello from C++ , yc"; return env->NewStringUTF(hello.c_str()); } extern "C" JNIEXPORT jstring JNICALL Java_com_yc_safetyjni_SafetyJniLib_getAppSign(JNIEnv *env, jobject thiz) { jclass appClass = env->FindClass("com/yc/App"); jmethodID getAppContextMethod = env->GetStaticMethodID(appClass, "getContext", "()Landroid/content/Context;"); //获取APplication定义的context实例 jobject appContext = env->CallStaticObjectMethod(appClass, getAppContextMethod); // 获取应用当前的签名信息 jstring signature = loadSignature(env, appContext); // 期待的签名信息 jstring keystoreSigature = env->NewStringUTF("31BC77F998CB0D305D74464DAECC2"); const char *keystroreMD5 = env->GetStringUTFChars(keystoreSigature, NULL); const char *releaseMD5 = env->GetStringUTFChars(signature, NULL); // 比较两个签名信息是否相等 int result = strcmp(keystroreMD5, releaseMD5); // 这里记得释放内存 env->ReleaseStringUTFChars(signature, releaseMD5); env->ReleaseStringUTFChars(keystoreSigature, keystroreMD5); } jstring loadSignature(JNIEnv *env, jobject context) { // 获取Context类 jclass contextClass = env->GetObjectClass(context); // 得到getPackageManager方法的ID jmethodID getPkgManagerMethodId = env->GetMethodID( contextClass, "getPackageManager", "()Landroid/content/pm/PackageManager;"); // PackageManager jobject pm = env->CallObjectMethod(context, getPkgManagerMethodId); // 得到应用的包名 jmethodID pkgNameMethodId = env->GetMethodID( contextClass, "getPackageName", "()Ljava/lang/String;"); jstring pkgName = (jstring) env->CallObjectMethod(context, pkgNameMethodId); // 获得PackageManager类 jclass cls = env->GetObjectClass(pm); // 得到getPackageInfo方法的ID jmethodID mid = env->GetMethodID( cls, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;"); // 获得应用包的信息 jobject packageInfo = env->CallObjectMethod(pm, mid, pkgName, 0x40); //GET_SIGNATURES = 64; // 获得PackageInfo 类 cls = env->GetObjectClass(packageInfo); // 获得签名数组属性的ID jfieldID fid = env->GetFieldID(cls, "signatures", "[Landroid/content/pm/Signature;"); // 得到签名数组 jobjectArray signatures = (jobjectArray) env->GetObjectField(packageInfo, fid); // 得到签名 jobject signature = env->GetObjectArrayElement(signatures, 0); // 获得Signature类 cls = env->GetObjectClass(signature); // 得到toCharsString方法的ID mid = env->GetMethodID(cls, "toByteArray", "()[B"); // 返回当前应用签名信息 jbyteArray signatureByteArray = (jbyteArray) env->CallObjectMethod(signature, mid); return ToMd5(env, signatureByteArray); } jstring ToMd5(JNIEnv *env, jbyteArray source) { // MessageDigest类 jclass classMessageDigest = env->FindClass( "java/security/MessageDigest"); // MessageDigest.getInstance()静态方法 jmethodID midGetInstance = env->GetStaticMethodID( classMessageDigest, "getInstance", "(Ljava/lang/String;)Ljava/security/MessageDigest;"); // MessageDigest object jobject objMessageDigest = env->CallStaticObjectMethod( classMessageDigest, midGetInstance, env->NewStringUTF("md5")); // update方法,这个函数的返回值是void,写V jmethodID midUpdate = env->GetMethodID( classMessageDigest, "update", "([B)V"); env->CallVoidMethod(objMessageDigest, midUpdate, source); // digest方法 jmethodID midDigest = env->GetMethodID(classMessageDigest, "digest", "()[B"); jbyteArray objArraySign = (jbyteArray) env->CallObjectMethod(objMessageDigest, midDigest); jsize intArrayLength = env->GetArrayLength(objArraySign); jbyte *byte_array_elements = env->GetByteArrayElements(objArraySign, NULL); size_t length = (size_t) intArrayLength * 2 + 1; char *char_result = (char *) malloc(length); memset(char_result, 0, length); // 将byte数组转换成16进制字符串,发现这里不用强转,jbyte和unsigned char应该字节数是一样的 ByteToHexStr(env, (const char *) byte_array_elements, char_result, intArrayLength); // 在末尾补\0 *(char_result + intArrayLength * 2) = '\0'; jstring stringResult = env->NewStringUTF(char_result); // release env->ReleaseByteArrayElements(objArraySign, byte_array_elements, JNI_ABORT); // 释放指针使用free free(char_result); return stringResult; } jstring ByteToHexStr(JNIEnv *env, const char *bytes, char *result, jsize length) { if (bytes == NULL) { return env->NewStringUTF(""); } std::string buff; const int len = length; for (int j = 0; j < len; j++) { int high = bytes[j] / 16, low = bytes[j] % 16; buff += (high < 10) ? ('0' + high) : ('a' + high - 10); buff += (low < 10) ? ('0' + low) : ('a' + low - 10); } return env->NewStringUTF(buff.c_str()); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SafetyJniLib/src/main/java/com/yc/safetyjni/SafetyJniLib.java
Java
package com.yc.safetyjni; public class SafetyJniLib { private static SafetyJniLib instance; // Used to load the 'safetyjnilib' library on application startup. static { System.loadLibrary("safetyjnilib"); } public static SafetyJniLib getInstance() { if (instance == null) { synchronized (SafetyJniLib.class) { if (instance == null) { instance = new SafetyJniLib(); } } } return instance; } public native String stringFromJNI(); public native String getAppSign(); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/build.gradle
Gradle
//plugins {id 'com.android.library'} apply plugin: 'com.android.library' android { compileSdkVersion 29 // buildToolsVersion '29.0.0' defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { cppFlags "" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.annotation:annotation:1.1.0' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/cpp/jni_env_manager.cc
C++
#include "jni_env_manager.h" #include <pthread.h> #include <cstdlib> namespace JniInvocation { static JavaVM *g_VM = nullptr; static pthread_once_t g_onceInitTls = PTHREAD_ONCE_INIT; static pthread_key_t g_tlsJavaEnv; void init(JavaVM *vm) { if (g_VM) return; g_VM = vm; } JavaVM *getJavaVM() { return g_VM; } JNIEnv *getEnv() { JNIEnv *env; int ret = g_VM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6); if (ret != JNI_OK) { pthread_once(&g_onceInitTls, []() { pthread_key_create(&g_tlsJavaEnv, [](void *d) { if (d && g_VM) g_VM->DetachCurrentThread(); }); }); if (g_VM->AttachCurrentThread(&env, nullptr) == JNI_OK) { pthread_setspecific(g_tlsJavaEnv, reinterpret_cast<const void *>(1)); } else { env = nullptr; } } return env; } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/cpp/jni_env_manager.h
C/C++ Header
#ifndef LAG_DETECTOR_LAG_DETECTOR_MAIN_CPP_NATIVE_HELPER_MANAGED_JNIENV_H_ #define LAG_DETECTOR_LAG_DETECTOR_MAIN_CPP_NATIVE_HELPER_MANAGED_JNIENV_H_ #include <jni.h> namespace JniInvocation { void init(JavaVM *vm); JavaVM *getJavaVM(); JNIEnv *getEnv(); } #endif
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/cpp/quit_signal_hooker.cc
C++
#include "quit_signal_hooker.h" #include "jni_env_manager.h" #include <jni.h> #include <sys/utsname.h> #include <unistd.h> #include <pthread.h> #include <android/log.h> #include <sys/types.h> #include <sys/socket.h> #include <linux/prctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <csignal> #include <cstdio> #include <ctime> #include <csignal> #include <thread> #include <memory> #include <string> #include <optional> #include <sstream> #include <fstream> #define PROP_VALUE_MAX 92 #define PROP_VERSION_NAME "ro.build.version.sdk" #define PROP_MODEL_NAME "ro.product.model" #define TOOL_CLASS_PATH "com/didi/rider/signal_hooker/SigQuitHooker" #define TOOL_CLASS_RECEIVE_ANR_SIGNAL "onReceiveAnrSignal" #define TOOL_CLASS_RECEIVE_ANR_SIGNAL_SIGNATURE "()V" #define TOOL_CLASS_PRINT_LOG "onPrintLog" #define TOOL_CLASS_PRINT_LOG_SIGNATURE "(Ljava/lang/String;)V" //using namespace std; static bool sHandlerInstalled = false; struct sigaction sOldHandlers; static std::mutex sHandlerStackMutex; static sigset_t old_sigSet; static struct MethodHolderForJNI { jclass AnrDetector; jmethodID AnrDetector_onReceiveSignal; jmethodID AnrDetector_printLog; } gJ; void receiveAnrSignal() { JNIEnv *env = JniInvocation::getEnv(); if (!env) { return; } env->CallStaticVoidMethod(gJ.AnrDetector, gJ.AnrDetector_onReceiveSignal); } void printLog(jstring message) { JNIEnv *env = JniInvocation::getEnv(); if (!env) { return; } env->CallStaticVoidMethod(gJ.AnrDetector, gJ.AnrDetector_printLog, message); } static void *anrCallback(void *arg) { receiveAnrSignal(); return nullptr; } void handleSignal(int sig, const siginfo_t *info, void *uc) { if (sig == SIGQUIT) { pthread_t thd; pthread_create(&thd, nullptr, anrCallback, nullptr); pthread_detach(thd); } } void signalHandler(int sig, siginfo_t *info, void *uc) { std::unique_lock<std::mutex> lock(sHandlerStackMutex); handleSignal(sig, info, uc); lock.unlock(); } static void initSignalHooker(JNIEnv *env, jclass) { if (sHandlerInstalled) { return; } sigset_t sigSet; sigemptyset(&sigSet); sigaddset(&sigSet, SIGQUIT); pthread_sigmask(SIG_UNBLOCK, &sigSet, &old_sigSet); if (sigaction(SIGQUIT, nullptr, &sOldHandlers) == -1) { return; } struct sigaction sa{}; sa.sa_sigaction = signalHandler; sa.sa_flags = SA_ONSTACK | SA_SIGINFO | SA_RESTART; if (sigaction(SIGQUIT, &sa, nullptr) == -1) { return; } sHandlerInstalled = true; printLog(env->NewStringUTF("install signal hooker success")); } template<typename T, std::size_t sz> static inline constexpr std::size_t NELEM(const T(&)[sz]) { return sz; } static const JNINativeMethod ANR_METHODS[] = { {"initSignalHooker", "()V", (void *) initSignalHooker}, }; int getApi() { char buf[PROP_VALUE_MAX] = {0}; int len = __system_property_get(PROP_VERSION_NAME, buf); if (len <= 0) return 0; return atoi(buf); } jstring getModel() { JNIEnv *env = JniInvocation::getEnv(); if (!env) { return nullptr; } char value[PROP_VALUE_MAX] = {0}; int len = __system_property_get(PROP_MODEL_NAME, value); if (len <= 0) { return env->NewStringUTF(""); } return env->NewStringUTF(value); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { JniInvocation::init(vm); JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } jclass anrDetectiveCls = env->FindClass(TOOL_CLASS_PATH); if (!anrDetectiveCls) { return -1; } gJ.AnrDetector = static_cast<jclass>(env->NewGlobalRef(anrDetectiveCls)); gJ.AnrDetector_onReceiveSignal = env->GetStaticMethodID(anrDetectiveCls, TOOL_CLASS_RECEIVE_ANR_SIGNAL, TOOL_CLASS_RECEIVE_ANR_SIGNAL_SIGNATURE); gJ.AnrDetector_printLog = env->GetStaticMethodID(anrDetectiveCls, TOOL_CLASS_PRINT_LOG, TOOL_CLASS_PRINT_LOG_SIGNATURE); if (env->RegisterNatives( anrDetectiveCls, ANR_METHODS, static_cast<jint>(NELEM(ANR_METHODS))) != 0) { return -1; } env->DeleteLocalRef(anrDetectiveCls); return JNI_VERSION_1_6; }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/cpp/quit_signal_hooker.h
C/C++ Header
#ifndef LAGDETECTOR_LAG_DETECTOR_MAIN_CPP_SignalHooker_H_ #define LAGDETECTOR_LAG_DETECTOR_MAIN_CPP_SignalHooker_H_ #include <jni.h> #endif
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/java/com/yc/signalhooker/ILogger.java
Java
package com.yc.signalhooker; public interface ILogger { void onPrintLog(String message); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/java/com/yc/signalhooker/ISignalListener.java
Java
package com.yc.signalhooker; public interface ISignalListener { void onReceiveAnrSignal(); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
SignalHooker/src/main/java/com/yc/signalhooker/SigQuitHooker.java
Java
package com.yc.signalhooker; import androidx.annotation.Keep; public class SigQuitHooker { private static ISignalListener mListener = null; private static ILogger mLogger = null; static { //so库加载 System.loadLibrary("signal-hooker"); } public static void setSignalListener(ISignalListener listener) { mListener = listener; } public static void setLogger(ILogger logger) { mLogger = logger; } @Keep private static void onReceiveAnrSignal() { if (mListener != null) { mListener.onReceiveAnrSignal(); } } @Keep private static void onPrintLog(String message) { if (mLogger != null) { mLogger.onPrintLog(message); } } public static native void initSignalHooker(); }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
TestJniLib/build.gradle
Gradle
//plugins {id 'com.android.library'} apply plugin: 'com.android.library' android { compileSdkVersion 29 // buildToolsVersion '29.0.0' defaultConfig { minSdkVersion 17 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64' } externalNativeBuild { cmake { //提供给C++编译器的一个标志 可选 cppFlags "" //声明当前Cmake项目使用的Android abi //abiFilters "armeabi-v7a" //提供给Cmake的参数信息 可选 //arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_TOOLCHAIN=clang" //提供给C编译器的一个标志 可选 //cFlags "-D__STDC_FORMAT_MACROS" //指定哪个so库会被打包到apk中去 可选 //targets "libexample-one", "my-executible-demo" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } //CMake的NDK项目它有自己一套运行流程 //Gradle 调用外部构建脚本CMakeLists.txt //CMake 按照构建脚本的命令将 C++ 源文件 testjnilib.cpp 编译到共享的对象库中,并命名为 libtestjnilib.so ,Gradle 随后会将其打包到APK中 externalNativeBuild { cmake { //声明cmake配置文件路径 path "src/main/cpp/CMakeLists.txt" //声明cmake版本 version "3.10.2" } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.annotation:annotation:1.1.0' }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
TestJniLib/src/main/cpp/testjnic.c
C
// // Created by 杨充 on 2023/6/7. // #include "testjnic.h"
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
TestJniLib/src/main/cpp/testjnic.h
C/C++ Header
// // Created by 杨充 on 2023/6/7. // #ifndef YCJNIHELPER_TESTJNIC_H #define YCJNIHELPER_TESTJNIC_H #endif //YCJNIHELPER_TESTJNIC_H
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
TestJniLib/src/main/cpp/testjnilib.cpp
C++
#include <jni.h> #include <string> #include "testjnilib.h" //java中stringFromJNI //extern “C” 指定以"C"的方式来实现native函数 extern "C" //JNIEXPORT 宏定义,用于指定该函数是JNI函数。表示此函数可以被外部调用,在Android开发中不可省略 JNIEXPORT jstring //JNICALL 宏定义,用于指定该函数是JNI函数。,无实际意义,但是不可省略 JNICALL //以注意到jni的取名规则,一般都是包名 + 类名,jni方法只是在前面加上了Java_,并把包名和类名之间的.换成了_ Java_com_yc_testjnilib_NativeLib_stringFromJNI(JNIEnv *env, jobject /* this */) { //JNIEnv 代表了JNI的环境,只要在本地代码中拿到了JNIEnv和jobject //JNI层实现的方法都是通过JNIEnv 指针调用JNI层的方法访问Java虚拟机,进而操作Java对象,这样就能调用Java代码。 //jobject thiz //在AS中自动为我们生成的JNI方法声明都会带一个这样的参数,这个instance就代表Java中native方法声明所在的 std::string hello = "Hello from C++"; //思考一下,为什么直接返回字符串会出现错误提示? //return "hello"; return env->NewStringUTF(hello.c_str()); } extern "C" JNIEXPORT jstring JNICALL Java_com_yc_testjnilib_NativeLib_getMd5(JNIEnv *env, jobject thiz, jstring str) { std::string stringHello = "哈哈哈哈哈,逗比"; return env->NewStringUTF(stringHello.c_str()); } extern "C" JNIEXPORT void JNICALL Java_com_yc_testjnilib_NativeLib_initLib(JNIEnv *env, jobject thiz, jstring version) { printf("初始化: 初始化操作2", version); } jstring getNameFromJNI(JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++ , yc lov txy"; return env->NewStringUTF(hello.c_str()); } //JNIEnv是什么? //JNIEnv代表Java调用native层的环境,一个封装了几乎所有的JNI方法的指针。其只在创建它的线程有效,不能跨线程传递,不同的线程的JNIEnv彼此独立。 //native 环境中创建的线程,如果需要访问JNI,必须调用AttachCurrentThread 进行关联,然后使用DetachCurrentThread 解除关联。 //JNI动态注册案例学习 //动态注册其实就是使用到了前面分析的so加载原理:在最后一步的JNI_OnLoad中注册对应的jni方法。这样在类加载的过程中就可以自动注册native函数。 //java路径 #define JNI_CLASS_NAME "com/yc/testjnilib/NativeLib" /** * 需要动态注册的方法 * 第一个参数:java中要注册的native方法名 * 第二个参数:方法的签名,括号内为参数类型,后面为返回类型 * 第三个参数:需要重新注册的方法名 */ //研究下JNINativeMethod: //JNI允许我们提供一个函数映射表,注册给Java虚拟机,这样JVM就可以用函数映射表来调用相应的函数。 //这样就可以不必通过函数名来查找需要调用的函数了。 //Java与JNI通过JNINativeMethod的结构来建立联系,它被定义在jni.h中,其结构内容如下: //typedef struct { // const char* name; // const char* signature; // void* fnPtr; //} JNINativeMethod; static JNINativeMethod gMethods[] = { {"stringFromJNI", "()Ljava/lang/String;", (void *) Java_com_yc_testjnilib_NativeLib_stringFromJNI}, {"getNameFromJNI", "()Ljava/lang/String;", (void *) getNameFromJNI}, }; int register_dynamic_Methods(JNIEnv *env) { std::string s = JNI_CLASS_NAME; const char *className = s.c_str(); // 找到需要动态注册的java类 jclass clazz = env->FindClass(className); if (clazz == NULL) { return JNI_FALSE; } //注册JNI方法 //核心方法:RegisterNatives,jni注册native方法。 //参数1:Java对应的类。 //参数2:JNINativeMethod数组。 //参数3:JNINativeMethod数组的长度,也就是要注册的方法的个数。 //通过调用RegisterNatives函数将注册函数的Java类,以及注册函数的数组,以及个数注册在一起,这样就实现了绑定。 if (env->RegisterNatives(clazz, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) < 0) { return JNI_FALSE; } return JNI_TRUE; } //System.loadLibrary()执行时会调用此方法 extern "C" //类加载时会调用到这里 JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; //指定JNI版本:告诉VM该组件使用那一个JNI版本(若未提供JNI_OnLoad()函数,VM会默认该使用最老的JNI 1.1版), //如果要使用新版本的JNI,例如JNI 1.6版,则必须由JNI_OnLoad()函数返回常量JNI_VERSION_1_6(该常量定义在jni.h中) 来告知VM。 if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; } assert(env != NULL); if (!register_dynamic_Methods(env)) { return JNI_ERR; } // 返回JNI使用的版本 return JNI_VERSION_1_6; } //JNI_OnUnload()的作用与JNI_OnLoad()对应,当VM释放JNI组件时会呼叫它,因此在该方法中进行善后清理,资源释放的动作最为合适。 extern "C" JNIEXPORT void JNI_OnUnload(JavaVM *jvm, void *reserved) { JNIEnv *env = NULL; if (jvm->GetEnv((void **) (&env), JNI_VERSION_1_6) != JNI_OK) { return; } std::string s = JNI_CLASS_NAME; const char *className = s.c_str(); // 找到需要动态注册的java类 jclass clazz = env->FindClass(className); if (clazz != NULL) { env->UnregisterNatives(clazz); } }
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent
TestJniLib/src/main/cpp/testjnilib.h
C/C++ Header
#include <jni.h> // // Created by 杨充 on 2023/6/7. // //约定俗成的操作是 .h 文件主要负责类成员变量和方法的声明; .cpp 文件主要负责成员变量和方法的定义。 //ida打开显示为:assume cs:yc #define JNI_SECTION ".yc" //#ifndef YCJNIHELPER_TESTJNILIB_H //#define YCJNIHELPER_TESTJNILIB_H // //#endif //YCJNIHELPER_TESTJNILIB_H //__cplusplus这个宏是微软自定义宏,表示是C++编译 //两个一样的函数,在c在函数是通过函数名来识别的,而在C++中,由于存在函数的重载问题,函数的识别方式通函数名、函数的返回类型、函数参数列表三者组合来完成的。 //因此上面两个相同的函数,经过C,C++编绎后会产生完全不同的名字。所以,如果把一个用c编绎器编绎的目标代码和一个用C++编绎器编绎的目标代码进行连接,就会出现连接失败的错误。 //extern "C" 是为了避免C++编绎器按照C++的方式去编绎C函数, #ifdef __cplusplus extern "C" { #endif jstring Java_com_yc_testjnilib_NativeLib_stringFromJNI(JNIEnv *env, jobject /* this */); jstring Java_com_yc_testjnilib_NativeLib_getMd5(JNIEnv *env, jobject thiz, jstring str); jstring getNameFromJNI(JNIEnv *env, jobject obj); #ifdef __cplusplus } #endif
yangchong211/YCJniHelper
283
JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例
Java
yangchong211
杨充
Tencent