mozglue/android/SQLiteBridge.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mozglue/android/SQLiteBridge.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,405 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +#include <stdlib.h>
     1.9 +#include <stdio.h>
    1.10 +#include <jni.h>
    1.11 +#include <android/log.h>
    1.12 +#include "dlfcn.h"
    1.13 +#include "APKOpen.h"
    1.14 +#include "ElfLoader.h"
    1.15 +#include "SQLiteBridge.h"
    1.16 +
    1.17 +#ifdef DEBUG
    1.18 +#define LOG(x...) __android_log_print(ANDROID_LOG_INFO, "GeckoJNI", x)
    1.19 +#else
    1.20 +#define LOG(x...)
    1.21 +#endif
    1.22 +
    1.23 +#define SQLITE_WRAPPER_INT(name) name ## _t f_ ## name;
    1.24 +
    1.25 +SQLITE_WRAPPER_INT(sqlite3_open)
    1.26 +SQLITE_WRAPPER_INT(sqlite3_errmsg)
    1.27 +SQLITE_WRAPPER_INT(sqlite3_prepare_v2)
    1.28 +SQLITE_WRAPPER_INT(sqlite3_bind_parameter_count)
    1.29 +SQLITE_WRAPPER_INT(sqlite3_bind_text)
    1.30 +SQLITE_WRAPPER_INT(sqlite3_step)
    1.31 +SQLITE_WRAPPER_INT(sqlite3_column_count)
    1.32 +SQLITE_WRAPPER_INT(sqlite3_finalize)
    1.33 +SQLITE_WRAPPER_INT(sqlite3_close)
    1.34 +SQLITE_WRAPPER_INT(sqlite3_column_name)
    1.35 +SQLITE_WRAPPER_INT(sqlite3_column_type)
    1.36 +SQLITE_WRAPPER_INT(sqlite3_column_blob)
    1.37 +SQLITE_WRAPPER_INT(sqlite3_column_bytes)
    1.38 +SQLITE_WRAPPER_INT(sqlite3_column_text)
    1.39 +SQLITE_WRAPPER_INT(sqlite3_changes)
    1.40 +SQLITE_WRAPPER_INT(sqlite3_last_insert_rowid)
    1.41 +
    1.42 +void setup_sqlite_functions(void *sqlite_handle)
    1.43 +{
    1.44 +#define GETFUNC(name) f_ ## name = (name ## _t) (uintptr_t) __wrap_dlsym(sqlite_handle, #name)
    1.45 +  GETFUNC(sqlite3_open);
    1.46 +  GETFUNC(sqlite3_errmsg);
    1.47 +  GETFUNC(sqlite3_prepare_v2);
    1.48 +  GETFUNC(sqlite3_bind_parameter_count);
    1.49 +  GETFUNC(sqlite3_bind_text);
    1.50 +  GETFUNC(sqlite3_step);
    1.51 +  GETFUNC(sqlite3_column_count);
    1.52 +  GETFUNC(sqlite3_finalize);
    1.53 +  GETFUNC(sqlite3_close);
    1.54 +  GETFUNC(sqlite3_column_name);
    1.55 +  GETFUNC(sqlite3_column_type);
    1.56 +  GETFUNC(sqlite3_column_blob);
    1.57 +  GETFUNC(sqlite3_column_bytes);
    1.58 +  GETFUNC(sqlite3_column_text);
    1.59 +  GETFUNC(sqlite3_changes);
    1.60 +  GETFUNC(sqlite3_last_insert_rowid);
    1.61 +#undef GETFUNC
    1.62 +}
    1.63 +
    1.64 +static bool initialized = false;
    1.65 +static jclass stringClass;
    1.66 +static jclass objectClass;
    1.67 +static jclass byteBufferClass;
    1.68 +static jclass cursorClass;
    1.69 +static jmethodID jByteBufferAllocateDirect;
    1.70 +static jmethodID jCursorConstructor;
    1.71 +static jmethodID jCursorAddRow;
    1.72 +
    1.73 +static jobject sqliteInternalCall(JNIEnv* jenv, sqlite3 *db, jstring jQuery,
    1.74 +                                  jobjectArray jParams, jlongArray jQueryRes);
    1.75 +
    1.76 +static void throwSqliteException(JNIEnv* jenv, const char* aFormat, ...)
    1.77 +{
    1.78 +    va_list ap;
    1.79 +    va_start(ap, aFormat);
    1.80 +    char* msg = nullptr;
    1.81 +    vasprintf(&msg, aFormat, ap);
    1.82 +    LOG("Error in SQLiteBridge: %s\n", msg);
    1.83 +    JNI_Throw(jenv, "org/mozilla/gecko/sqlite/SQLiteBridgeException", msg);
    1.84 +    free(msg);
    1.85 +    va_end(ap);
    1.86 +}
    1.87 +
    1.88 +static void
    1.89 +JNI_Setup(JNIEnv* jenv)
    1.90 +{
    1.91 +    if (initialized) return;
    1.92 +
    1.93 +    jclass lObjectClass       = jenv->FindClass("java/lang/Object");
    1.94 +    jclass lStringClass       = jenv->FindClass("java/lang/String");
    1.95 +    jclass lByteBufferClass   = jenv->FindClass("java/nio/ByteBuffer");
    1.96 +    jclass lCursorClass       = jenv->FindClass("org/mozilla/gecko/sqlite/MatrixBlobCursor");
    1.97 +
    1.98 +    if (lStringClass == nullptr
    1.99 +        || lObjectClass == nullptr
   1.100 +        || lByteBufferClass == nullptr
   1.101 +        || lCursorClass == nullptr) {
   1.102 +        throwSqliteException(jenv, "FindClass error");
   1.103 +        return;
   1.104 +    }
   1.105 +
   1.106 +    // Those are only local references. Make them global so they work
   1.107 +    // across calls and threads.
   1.108 +    objectClass = (jclass)jenv->NewGlobalRef(lObjectClass);
   1.109 +    stringClass = (jclass)jenv->NewGlobalRef(lStringClass);
   1.110 +    byteBufferClass = (jclass)jenv->NewGlobalRef(lByteBufferClass);
   1.111 +    cursorClass = (jclass)jenv->NewGlobalRef(lCursorClass);
   1.112 +
   1.113 +    if (stringClass == nullptr || objectClass == nullptr
   1.114 +        || byteBufferClass == nullptr
   1.115 +        || cursorClass == nullptr) {
   1.116 +        throwSqliteException(jenv, "NewGlobalRef error");
   1.117 +        return;
   1.118 +    }
   1.119 +
   1.120 +    // public static ByteBuffer allocateDirect(int capacity)
   1.121 +    jByteBufferAllocateDirect =
   1.122 +        jenv->GetStaticMethodID(byteBufferClass, "allocateDirect", "(I)Ljava/nio/ByteBuffer;");
   1.123 +    // new MatrixBlobCursor(String [])
   1.124 +    jCursorConstructor =
   1.125 +        jenv->GetMethodID(cursorClass, "<init>", "([Ljava/lang/String;)V");
   1.126 +    // public void addRow (Object[] columnValues)
   1.127 +    jCursorAddRow =
   1.128 +        jenv->GetMethodID(cursorClass, "addRow", "([Ljava/lang/Object;)V");
   1.129 +
   1.130 +    if (jByteBufferAllocateDirect == nullptr
   1.131 +        || jCursorConstructor == nullptr
   1.132 +        || jCursorAddRow == nullptr) {
   1.133 +        throwSqliteException(jenv, "GetMethodId error");
   1.134 +        return;
   1.135 +    }
   1.136 +
   1.137 +    initialized = true;
   1.138 +}
   1.139 +
   1.140 +extern "C" NS_EXPORT jobject JNICALL
   1.141 +Java_org_mozilla_gecko_sqlite_SQLiteBridge_sqliteCall(JNIEnv* jenv, jclass,
   1.142 +                                                      jstring jDb,
   1.143 +                                                      jstring jQuery,
   1.144 +                                                      jobjectArray jParams,
   1.145 +                                                      jlongArray jQueryRes)
   1.146 +{
   1.147 +    JNI_Setup(jenv);
   1.148 +
   1.149 +    int rc;
   1.150 +    jobject jCursor = nullptr;
   1.151 +    const char* dbPath;
   1.152 +    sqlite3 *db;
   1.153 +
   1.154 +    dbPath = jenv->GetStringUTFChars(jDb, nullptr);
   1.155 +    rc = f_sqlite3_open(dbPath, &db);
   1.156 +    jenv->ReleaseStringUTFChars(jDb, dbPath);
   1.157 +    if (rc != SQLITE_OK) {
   1.158 +        throwSqliteException(jenv,
   1.159 +            "Can't open database: %s", f_sqlite3_errmsg(db));
   1.160 +        f_sqlite3_close(db); // close db even if open failed
   1.161 +        return nullptr;
   1.162 +    }
   1.163 +    jCursor = sqliteInternalCall(jenv, db, jQuery, jParams, jQueryRes);
   1.164 +    f_sqlite3_close(db);
   1.165 +    return jCursor;
   1.166 +}
   1.167 +
   1.168 +extern "C" NS_EXPORT jobject JNICALL
   1.169 +Java_org_mozilla_gecko_sqlite_SQLiteBridge_sqliteCallWithDb(JNIEnv* jenv, jclass,
   1.170 +                                                            jlong jDb,
   1.171 +                                                            jstring jQuery,
   1.172 +                                                            jobjectArray jParams,
   1.173 +                                                            jlongArray jQueryRes)
   1.174 +{
   1.175 +    JNI_Setup(jenv);
   1.176 +
   1.177 +    jobject jCursor = nullptr;
   1.178 +    sqlite3 *db = (sqlite3*)jDb;
   1.179 +    jCursor = sqliteInternalCall(jenv, db, jQuery, jParams, jQueryRes);
   1.180 +    return jCursor;
   1.181 +}
   1.182 +
   1.183 +extern "C" NS_EXPORT jlong JNICALL
   1.184 +Java_org_mozilla_gecko_sqlite_SQLiteBridge_openDatabase(JNIEnv* jenv, jclass,
   1.185 +                                                        jstring jDb)
   1.186 +{
   1.187 +    JNI_Setup(jenv);
   1.188 +
   1.189 +    int rc;
   1.190 +    const char* dbPath;
   1.191 +    sqlite3 *db;
   1.192 +
   1.193 +    dbPath = jenv->GetStringUTFChars(jDb, nullptr);
   1.194 +    rc = f_sqlite3_open(dbPath, &db);
   1.195 +    jenv->ReleaseStringUTFChars(jDb, dbPath);
   1.196 +    if (rc != SQLITE_OK) {
   1.197 +        throwSqliteException(jenv,
   1.198 +            "Can't open database: %s", f_sqlite3_errmsg(db));
   1.199 +        f_sqlite3_close(db); // close db even if open failed
   1.200 +        return 0;
   1.201 +    }
   1.202 +    return (jlong)db;
   1.203 +}
   1.204 +
   1.205 +extern "C" NS_EXPORT void JNICALL
   1.206 +Java_org_mozilla_gecko_sqlite_SQLiteBridge_closeDatabase(JNIEnv* jenv, jclass,
   1.207 +                                                        jlong jDb)
   1.208 +{
   1.209 +    JNI_Setup(jenv);
   1.210 +
   1.211 +    sqlite3 *db = (sqlite3*)jDb;
   1.212 +    f_sqlite3_close(db);
   1.213 +}
   1.214 +
   1.215 +static jobject
   1.216 +sqliteInternalCall(JNIEnv* jenv,
   1.217 +                   sqlite3 *db,
   1.218 +                   jstring jQuery,
   1.219 +                   jobjectArray jParams,
   1.220 +                   jlongArray jQueryRes)
   1.221 +{
   1.222 +    JNI_Setup(jenv);
   1.223 +
   1.224 +    jobject jCursor = nullptr;
   1.225 +    jsize numPars = 0;
   1.226 +
   1.227 +    const char *pzTail;
   1.228 +    sqlite3_stmt *ppStmt;
   1.229 +    int rc;
   1.230 +
   1.231 +    const char* queryStr;
   1.232 +    queryStr = jenv->GetStringUTFChars(jQuery, nullptr);
   1.233 +
   1.234 +    rc = f_sqlite3_prepare_v2(db, queryStr, -1, &ppStmt, &pzTail);
   1.235 +    if (rc != SQLITE_OK || ppStmt == nullptr) {
   1.236 +        throwSqliteException(jenv,
   1.237 +            "Can't prepare statement: %s", f_sqlite3_errmsg(db));
   1.238 +        return nullptr;
   1.239 +    }
   1.240 +    jenv->ReleaseStringUTFChars(jQuery, queryStr);
   1.241 +
   1.242 +    // Check if number of parameters matches
   1.243 +    if (jParams != nullptr) {
   1.244 +        numPars = jenv->GetArrayLength(jParams);
   1.245 +    }
   1.246 +    int sqlNumPars;
   1.247 +    sqlNumPars = f_sqlite3_bind_parameter_count(ppStmt);
   1.248 +    if (numPars != sqlNumPars) {
   1.249 +        throwSqliteException(jenv,
   1.250 +            "Passed parameter count (%d) "
   1.251 +            "doesn't match SQL parameter count (%d)",
   1.252 +            numPars, sqlNumPars);
   1.253 +        return nullptr;
   1.254 +    }
   1.255 +
   1.256 +    if (jParams != nullptr) {
   1.257 +        // Bind parameters, if any
   1.258 +        if (numPars > 0) {
   1.259 +            for (int i = 0; i < numPars; i++) {
   1.260 +                jobject jObjectParam = jenv->GetObjectArrayElement(jParams, i);
   1.261 +                // IsInstanceOf or isAssignableFrom? String is final, so IsInstanceOf
   1.262 +                // should be OK.
   1.263 +                jboolean isString = jenv->IsInstanceOf(jObjectParam, stringClass);
   1.264 +                if (isString != JNI_TRUE) {
   1.265 +                    throwSqliteException(jenv,
   1.266 +                        "Parameter is not of String type");
   1.267 +                    return nullptr;
   1.268 +                }
   1.269 +                jstring jStringParam = (jstring)jObjectParam;
   1.270 +                const char* paramStr = jenv->GetStringUTFChars(jStringParam, nullptr);
   1.271 +                // SQLite parameters index from 1.
   1.272 +                rc = f_sqlite3_bind_text(ppStmt, i + 1, paramStr, -1, SQLITE_TRANSIENT);
   1.273 +                jenv->ReleaseStringUTFChars(jStringParam, paramStr);
   1.274 +                if (rc != SQLITE_OK) {
   1.275 +                    throwSqliteException(jenv, "Error binding query parameter");
   1.276 +                    return nullptr;
   1.277 +                }
   1.278 +            }
   1.279 +        }
   1.280 +    }
   1.281 +
   1.282 +    // Execute the query and step through the results
   1.283 +    rc = f_sqlite3_step(ppStmt);
   1.284 +    if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
   1.285 +        throwSqliteException(jenv,
   1.286 +            "Can't step statement: (%d) %s", rc, f_sqlite3_errmsg(db));
   1.287 +        return nullptr;
   1.288 +    }
   1.289 +
   1.290 +    // Get the column count and names
   1.291 +    int cols;
   1.292 +    cols = f_sqlite3_column_count(ppStmt);
   1.293 +
   1.294 +    {
   1.295 +        // Allocate a String[cols]
   1.296 +        jobjectArray jStringArray = jenv->NewObjectArray(cols,
   1.297 +                                                         stringClass,
   1.298 +                                                         nullptr);
   1.299 +        if (jStringArray == nullptr) {
   1.300 +            throwSqliteException(jenv, "Can't allocate String[]");
   1.301 +            return nullptr;
   1.302 +        }
   1.303 +
   1.304 +        // Assign column names to the String[]
   1.305 +        for (int i = 0; i < cols; i++) {
   1.306 +            const char* colName = f_sqlite3_column_name(ppStmt, i);
   1.307 +            jstring jStr = jenv->NewStringUTF(colName);
   1.308 +            jenv->SetObjectArrayElement(jStringArray, i, jStr);
   1.309 +        }
   1.310 +
   1.311 +        // Construct the MatrixCursor(String[]) with given column names
   1.312 +        jCursor = jenv->NewObject(cursorClass,
   1.313 +                                  jCursorConstructor,
   1.314 +                                  jStringArray);
   1.315 +        if (jCursor == nullptr) {
   1.316 +            throwSqliteException(jenv, "Can't allocate MatrixBlobCursor");
   1.317 +            return nullptr;
   1.318 +        }
   1.319 +    }
   1.320 +
   1.321 +    // Return the id and number of changed rows in jQueryRes
   1.322 +    {
   1.323 +        jlong id = f_sqlite3_last_insert_rowid(db);
   1.324 +        jenv->SetLongArrayRegion(jQueryRes, 0, 1, &id);
   1.325 +
   1.326 +        jlong changed = f_sqlite3_changes(db);
   1.327 +        jenv->SetLongArrayRegion(jQueryRes, 1, 1, &changed);
   1.328 +    }
   1.329 +
   1.330 +    // For each row, add an Object[] to the passed ArrayList,
   1.331 +    // with that containing either String or ByteArray objects
   1.332 +    // containing the columns
   1.333 +    while (rc != SQLITE_DONE) {
   1.334 +        // Process row
   1.335 +        // Construct Object[]
   1.336 +        jobjectArray jRow = jenv->NewObjectArray(cols,
   1.337 +                                                 objectClass,
   1.338 +                                                 nullptr);
   1.339 +        if (jRow == nullptr) {
   1.340 +            throwSqliteException(jenv, "Can't allocate jRow Object[]");
   1.341 +            return nullptr;
   1.342 +        }
   1.343 +
   1.344 +        for (int i = 0; i < cols; i++) {
   1.345 +            int colType = f_sqlite3_column_type(ppStmt, i);
   1.346 +            if (colType == SQLITE_BLOB) {
   1.347 +                // Treat as blob
   1.348 +                const void* blob = f_sqlite3_column_blob(ppStmt, i);
   1.349 +                int colLen = f_sqlite3_column_bytes(ppStmt, i);
   1.350 +
   1.351 +                // Construct ByteBuffer of correct size
   1.352 +                jobject jByteBuffer =
   1.353 +                    jenv->CallStaticObjectMethod(byteBufferClass,
   1.354 +                                                 jByteBufferAllocateDirect,
   1.355 +                                                 colLen);
   1.356 +                if (jByteBuffer == nullptr) {
   1.357 +                    throwSqliteException(jenv,
   1.358 +                        "Failure calling ByteBuffer.allocateDirect");
   1.359 +                    return nullptr;
   1.360 +                }
   1.361 +
   1.362 +                // Get its backing array
   1.363 +                void* bufferArray = jenv->GetDirectBufferAddress(jByteBuffer);
   1.364 +                if (bufferArray == nullptr) {
   1.365 +                    throwSqliteException(jenv,
   1.366 +                        "Failure calling GetDirectBufferAddress");
   1.367 +                    return nullptr;
   1.368 +                }
   1.369 +                memcpy(bufferArray, blob, colLen);
   1.370 +
   1.371 +                jenv->SetObjectArrayElement(jRow, i, jByteBuffer);
   1.372 +                jenv->DeleteLocalRef(jByteBuffer);
   1.373 +            } else if (colType == SQLITE_NULL) {
   1.374 +                jenv->SetObjectArrayElement(jRow, i, nullptr);
   1.375 +            } else {
   1.376 +                // Treat everything else as text
   1.377 +                const char* txt = (const char*)f_sqlite3_column_text(ppStmt, i);
   1.378 +                jstring jStr = jenv->NewStringUTF(txt);
   1.379 +                jenv->SetObjectArrayElement(jRow, i, jStr);
   1.380 +                jenv->DeleteLocalRef(jStr);
   1.381 +            }
   1.382 +        }
   1.383 +
   1.384 +        // Append Object[] to Cursor
   1.385 +        jenv->CallVoidMethod(jCursor, jCursorAddRow, jRow);
   1.386 +
   1.387 +        // Clean up
   1.388 +        jenv->DeleteLocalRef(jRow);
   1.389 +
   1.390 +        // Get next row
   1.391 +        rc = f_sqlite3_step(ppStmt);
   1.392 +        // Real error?
   1.393 +        if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
   1.394 +            throwSqliteException(jenv,
   1.395 +                "Can't re-step statement:(%d) %s", rc, f_sqlite3_errmsg(db));
   1.396 +            return nullptr;
   1.397 +        }
   1.398 +    }
   1.399 +
   1.400 +    rc = f_sqlite3_finalize(ppStmt);
   1.401 +    if (rc != SQLITE_OK) {
   1.402 +        throwSqliteException(jenv,
   1.403 +            "Can't finalize statement: %s", f_sqlite3_errmsg(db));
   1.404 +        return nullptr;
   1.405 +    }
   1.406 +
   1.407 +    return jCursor;
   1.408 +}

mercurial