@@ -921,17 +921,61 @@ extern int register_android_database_CursorWindow(JNIEnv *env);
921921
922922} // namespace android
923923
924+ void setEnvarToCacheDirectory (JNIEnv* env, const char *envar) {
925+ jclass activity = NULL , context = NULL , file = NULL ;
926+ jmethodID getCurrentApp = NULL , getCacheDir = NULL , getAbsolutePath = NULL ;
927+ jobject app = NULL , cache = NULL ;
928+ jstring path = NULL ;
929+ const char *pathUtf8 = NULL , *tmpdir = getenv (envar);
930+
931+ /* check if SQLCIPHER_TMP is already set externally by the application (i.e. an override), and return immediately if it is */
932+ if (tmpdir && strlen (tmpdir) > 0 ) {
933+ return ;
934+ }
935+
936+ /* call ActivityThread.currentApplication().getCacheDir().getAbsolutePath() and set it to SQLCIPHER_TMP*/
937+ if (
938+ (activity = env->FindClass (" android/app/ActivityThread" ))
939+ && (context = env->FindClass (" android/content/Context" ))
940+ && (file = env->FindClass (" java/io/File" ))
941+ && (getCurrentApp = env->GetStaticMethodID (activity, " currentApplication" , " ()Landroid/app/Application;" ))
942+ && (getCacheDir = env->GetMethodID (context, " getCacheDir" , " ()Ljava/io/File;" ))
943+ && (getAbsolutePath = env->GetMethodID (file, " getAbsolutePath" , " ()Ljava/lang/String;" ))
944+ && (app = env->CallStaticObjectMethod (activity, getCurrentApp))
945+ && (cache = env->CallObjectMethod (app, getCacheDir))
946+ && (path = (jstring) env->CallObjectMethod (cache, getAbsolutePath))
947+ && (pathUtf8 = env->GetStringUTFChars (path, NULL ))
948+ ) {
949+ setenv (envar, pathUtf8, 1 );
950+ } else {
951+ ALOGE (" %s unable to obtain cache directory from JNIEnv" , __func__);
952+ }
953+
954+ /* cleanup */
955+ if (pathUtf8) env->ReleaseStringUTFChars (path, pathUtf8);
956+ if (path) env->DeleteLocalRef (path);
957+ if (cache) env->DeleteLocalRef (cache);
958+ if (app) env->DeleteLocalRef (app);
959+ if (file) env->DeleteLocalRef (file);
960+ if (context) env->DeleteLocalRef (context);
961+ if (activity) env->DeleteLocalRef (activity);
962+ }
963+
964+
924965extern " C" JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM* vm, void * reserved) {
925966 JNIEnv *env = 0 ;
926967
927968 android::gpJavaVM = vm;
928969 vm->GetEnv ((void **)&env, JNI_VERSION_1_4);
929970
971+ setEnvarToCacheDirectory (env, " SQLCIPHER_TMP" );
972+
930973 android::register_android_database_SQLiteConnection (env);
931974 android::register_android_database_SQLiteDebug (env);
932975 android::register_android_database_SQLiteGlobal (env);
933976 android::register_android_database_CursorWindow (env);
934977
978+
935979 return JNI_VERSION_1_4;
936980}
937981
0 commit comments