| 1 | /* |
| 2 | * Copyright (C) 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <android-base/logging.h> |
| 18 | #include <android-base/properties.h> |
| 19 | #include <android/graphics/jni_runtime.h> |
| 20 | #include <nativehelper/JNIHelp.h> |
| 21 | #include <nativehelper/jni_macros.h> |
| 22 | #include <unicode/putil.h> |
| 23 | #include <unicode/udata.h> |
| 24 | |
| 25 | #include <clocale> |
| 26 | #include <sstream> |
| 27 | #include <unordered_map> |
| 28 | #include <vector> |
| 29 | |
| 30 | #include "core_jni_helpers.h" |
| 31 | #include "jni.h" |
| 32 | #ifdef _WIN32 |
| 33 | #include <windows.h> |
| 34 | #else |
| 35 | #include <fcntl.h> |
| 36 | #include <sys/mman.h> |
| 37 | #include <sys/stat.h> |
| 38 | #endif |
| 39 | |
| 40 | #include <iostream> |
| 41 | |
| 42 | using namespace std; |
| 43 | |
| 44 | /* |
| 45 | * This is responsible for setting up the JNI environment for communication between |
| 46 | * the Java and native parts of layoutlib, including registering native methods. |
| 47 | * This is mostly achieved by copying the way it is done in the platform |
| 48 | * (see AndroidRuntime.cpp). |
| 49 | */ |
| 50 | |
| 51 | static JavaVM* javaVM; |
| 52 | static jclass bridge; |
| 53 | static jclass layoutLog; |
| 54 | static jmethodID getLogId; |
| 55 | static jmethodID logMethodId; |
| 56 | |
| 57 | extern int register_android_os_Binder(JNIEnv* env); |
| 58 | extern int register_libcore_util_NativeAllocationRegistry_Delegate(JNIEnv* env); |
| 59 | |
| 60 | typedef void (*FreeFunction)(void*); |
| 61 | |
| 62 | static void NativeAllocationRegistry_Delegate_nativeApplyFreeFunction(JNIEnv*, jclass, |
| 63 | jlong freeFunction, |
| 64 | jlong ptr) { |
| 65 | void* nativePtr = reinterpret_cast<void*>(static_cast<uintptr_t>(ptr)); |
| 66 | FreeFunction nativeFreeFunction = |
| 67 | reinterpret_cast<FreeFunction>(static_cast<uintptr_t>(freeFunction)); |
| 68 | nativeFreeFunction(nativePtr); |
| 69 | } |
| 70 | |
| 71 | static JNINativeMethod gMethods[] = { |
| 72 | NATIVE_METHOD(NativeAllocationRegistry_Delegate, nativeApplyFreeFunction, "(JJ)V"), |
| 73 | }; |
| 74 | |
| 75 | int register_libcore_util_NativeAllocationRegistry_Delegate(JNIEnv* env) { |
| 76 | return jniRegisterNativeMethods(env, "libcore/util/NativeAllocationRegistry_Delegate", gMethods, |
| 77 | NELEM(gMethods)); |
| 78 | } |
| 79 | |
| 80 | namespace android { |
| 81 | |
| 82 | extern int register_android_animation_PropertyValuesHolder(JNIEnv *env); |
| 83 | extern int register_android_content_AssetManager(JNIEnv* env); |
| 84 | extern int register_android_content_StringBlock(JNIEnv* env); |
| 85 | extern int register_android_content_XmlBlock(JNIEnv* env); |
| 86 | extern int register_android_content_res_ApkAssets(JNIEnv* env); |
| 87 | extern int register_android_database_CursorWindow(JNIEnv* env); |
| 88 | extern int register_android_database_SQLiteConnection(JNIEnv* env); |
| 89 | extern int register_android_database_SQLiteGlobal(JNIEnv* env); |
| 90 | extern int register_android_database_SQLiteDebug(JNIEnv* env); |
| 91 | extern int register_android_os_FileObserver(JNIEnv* env); |
| 92 | extern int register_android_os_MessageQueue(JNIEnv* env); |
| 93 | extern int register_android_os_Parcel(JNIEnv* env); |
| 94 | extern int register_android_os_SystemClock(JNIEnv* env); |
| 95 | extern int register_android_os_SystemProperties(JNIEnv* env); |
| 96 | extern int register_android_os_Trace(JNIEnv* env); |
| 97 | extern int register_android_text_AndroidCharacter(JNIEnv* env); |
| 98 | extern int register_android_util_EventLog(JNIEnv* env); |
| 99 | extern int register_android_util_Log(JNIEnv* env); |
| 100 | extern int register_android_util_jar_StrictJarFile(JNIEnv* env); |
| 101 | extern int register_android_view_KeyCharacterMap(JNIEnv* env); |
| 102 | extern int register_android_view_KeyEvent(JNIEnv* env); |
| 103 | extern int register_android_view_MotionEvent(JNIEnv* env); |
| 104 | extern int register_android_view_ThreadedRenderer(JNIEnv* env); |
| 105 | extern int register_android_view_VelocityTracker(JNIEnv* env); |
| 106 | extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env); |
| 107 | |
| 108 | #define REG_JNI(name) { name } |
| 109 | struct RegJNIRec { |
| 110 | int (*mProc)(JNIEnv*); |
| 111 | }; |
| 112 | |
| 113 | // Map of all possible class names to register to their corresponding JNI registration function pointer |
| 114 | // The actual list of registered classes will be determined at runtime via the 'native_classes' System property |
| 115 | static const std::unordered_map<std::string, RegJNIRec> gRegJNIMap = { |
| 116 | {"android.animation.PropertyValuesHolder", |
| 117 | REG_JNI(register_android_animation_PropertyValuesHolder)}, |
| 118 | #ifdef __linux__ |
| 119 | {"android.content.res.ApkAssets", REG_JNI(register_android_content_res_ApkAssets)}, |
| 120 | {"android.content.res.AssetManager", REG_JNI(register_android_content_AssetManager)}, |
| 121 | {"android.database.CursorWindow", REG_JNI(register_android_database_CursorWindow)}, |
| 122 | {"android.database.sqlite.SQLiteConnection", |
| 123 | REG_JNI(register_android_database_SQLiteConnection)}, |
| 124 | {"android.database.sqlite.SQLiteGlobal", REG_JNI(register_android_database_SQLiteGlobal)}, |
| 125 | {"android.database.sqlite.SQLiteDebug", REG_JNI(register_android_database_SQLiteDebug)}, |
| 126 | #endif |
| 127 | {"android.content.res.StringBlock", REG_JNI(register_android_content_StringBlock)}, |
| 128 | {"android.content.res.XmlBlock", REG_JNI(register_android_content_XmlBlock)}, |
| 129 | #ifdef __linux__ |
| 130 | {"android.os.Binder", REG_JNI(register_android_os_Binder)}, |
| 131 | {"android.os.FileObserver", REG_JNI(register_android_os_FileObserver)}, |
| 132 | {"android.os.MessageQueue", REG_JNI(register_android_os_MessageQueue)}, |
| 133 | {"android.os.Parcel", REG_JNI(register_android_os_Parcel)}, |
| 134 | #endif |
| 135 | {"android.os.SystemClock", REG_JNI(register_android_os_SystemClock)}, |
| 136 | {"android.os.SystemProperties", REG_JNI(register_android_os_SystemProperties)}, |
| 137 | {"android.os.Trace", REG_JNI(register_android_os_Trace)}, |
| 138 | {"android.text.AndroidCharacter", REG_JNI(register_android_text_AndroidCharacter)}, |
| 139 | {"android.util.EventLog", REG_JNI(register_android_util_EventLog)}, |
| 140 | {"android.util.Log", REG_JNI(register_android_util_Log)}, |
| 141 | {"android.util.jar.StrictJarFile", REG_JNI(register_android_util_jar_StrictJarFile)}, |
| 142 | {"android.view.KeyCharacterMap", REG_JNI(register_android_view_KeyCharacterMap)}, |
| 143 | {"android.view.KeyEvent", REG_JNI(register_android_view_KeyEvent)}, |
| 144 | {"android.view.MotionEvent", REG_JNI(register_android_view_MotionEvent)}, |
| 145 | {"android.view.VelocityTracker", REG_JNI(register_android_view_VelocityTracker)}, |
| 146 | {"com.android.internal.util.VirtualRefBasePtr", |
| 147 | REG_JNI(register_com_android_internal_util_VirtualRefBasePtr)}, |
| 148 | {"libcore.util.NativeAllocationRegistry_Delegate", |
| 149 | REG_JNI(register_libcore_util_NativeAllocationRegistry_Delegate)}, |
| 150 | }; |
| 151 | |
| 152 | static int register_jni_procs(const std::unordered_map<std::string, RegJNIRec>& jniRegMap, |
| 153 | const vector<string>& classesToRegister, JNIEnv* env) { |
| 154 | |
| 155 | for (const string& className : classesToRegister) { |
| 156 | if (jniRegMap.at(className).mProc(env) < 0) { |
| 157 | return -1; |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | if (register_android_graphics_classes(env) < 0) { |
| 162 | return -1; |
| 163 | } |
| 164 | |
| 165 | return 0; |
| 166 | } |
| 167 | |
| 168 | int AndroidRuntime::registerNativeMethods(JNIEnv* env, |
| 169 | const char* className, const JNINativeMethod* gMethods, int numMethods) { |
| 170 | return jniRegisterNativeMethods(env, className, gMethods, numMethods); |
| 171 | } |
| 172 | |
| 173 | JNIEnv* AndroidRuntime::getJNIEnv() { |
| 174 | JNIEnv* env; |
| 175 | if (javaVM->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) |
| 176 | return nullptr; |
| 177 | return env; |
| 178 | } |
| 179 | |
| 180 | JavaVM* AndroidRuntime::getJavaVM() { |
| 181 | return javaVM; |
| 182 | } |
| 183 | |
| 184 | static vector<string> parseCsv(const string& csvString) { |
| 185 | vector<string> result; |
| 186 | istringstream stream(csvString); |
| 187 | string segment; |
| 188 | while(getline(stream, segment, ',')) |
| 189 | { |
| 190 | result.push_back(segment); |
| 191 | } |
| 192 | return result; |
| 193 | } |
| 194 | |
| 195 | static vector<string> parseCsv(JNIEnv* env, jstring csvJString) { |
| 196 | const char* charArray = env->GetStringUTFChars(csvJString, 0); |
| 197 | string csvString(charArray); |
| 198 | vector<string> result = parseCsv(csvString); |
| 199 | env->ReleaseStringUTFChars(csvJString, charArray); |
| 200 | return result; |
| 201 | } |
| 202 | |
| 203 | void LayoutlibLogger(base::LogId, base::LogSeverity severity, const char* tag, const char* file, |
| 204 | unsigned int line, const char* message) { |
| 205 | JNIEnv* env = AndroidRuntime::getJNIEnv(); |
| 206 | jint logPrio = severity; |
| 207 | jstring tagString = env->NewStringUTF(tag); |
| 208 | jstring messageString = env->NewStringUTF(message); |
| 209 | |
| 210 | jobject bridgeLog = env->CallStaticObjectMethod(bridge, getLogId); |
| 211 | |
| 212 | env->CallVoidMethod(bridgeLog, logMethodId, logPrio, tagString, messageString); |
| 213 | |
| 214 | env->DeleteLocalRef(tagString); |
| 215 | env->DeleteLocalRef(messageString); |
| 216 | env->DeleteLocalRef(bridgeLog); |
| 217 | } |
| 218 | |
| 219 | void LayoutlibAborter(const char* abort_message) { |
| 220 | // Layoutlib should not call abort() as it would terminate Studio. |
| 221 | // Throw an exception back to Java instead. |
| 222 | JNIEnv* env = AndroidRuntime::getJNIEnv(); |
| 223 | jniThrowRuntimeException(env, "The Android framework has encountered a fatal error"); |
| 224 | } |
| 225 | |
| 226 | // This method has been copied/adapted from system/core/init/property_service.cpp |
| 227 | // If the ro.product.cpu.abilist* properties have not been explicitly |
| 228 | // set, derive them from ro.system.product.cpu.abilist* properties. |
| 229 | static void property_initialize_ro_cpu_abilist() { |
| 230 | const std::string EMPTY = ""; |
| 231 | const char* kAbilistProp = "ro.product.cpu.abilist"; |
| 232 | const char* kAbilist32Prop = "ro.product.cpu.abilist32"; |
| 233 | const char* kAbilist64Prop = "ro.product.cpu.abilist64"; |
| 234 | |
| 235 | // If the properties are defined explicitly, just use them. |
| 236 | if (base::GetProperty(kAbilistProp, EMPTY) != EMPTY) { |
| 237 | return; |
| 238 | } |
| 239 | |
| 240 | std::string abilist32_prop_val; |
| 241 | std::string abilist64_prop_val; |
| 242 | const auto abilist32_prop = "ro.system.product.cpu.abilist32"; |
| 243 | const auto abilist64_prop = "ro.system.product.cpu.abilist64"; |
| 244 | abilist32_prop_val = base::GetProperty(abilist32_prop, EMPTY); |
| 245 | abilist64_prop_val = base::GetProperty(abilist64_prop, EMPTY); |
| 246 | |
| 247 | // Merge ABI lists for ro.product.cpu.abilist |
| 248 | auto abilist_prop_val = abilist64_prop_val; |
| 249 | if (abilist32_prop_val != EMPTY) { |
| 250 | if (abilist_prop_val != EMPTY) { |
| 251 | abilist_prop_val += ","; |
| 252 | } |
| 253 | abilist_prop_val += abilist32_prop_val; |
| 254 | } |
| 255 | |
| 256 | // Set these properties |
| 257 | const std::pair<const char*, const std::string&> set_prop_list[] = { |
| 258 | {kAbilistProp, abilist_prop_val}, |
| 259 | {kAbilist32Prop, abilist32_prop_val}, |
| 260 | {kAbilist64Prop, abilist64_prop_val}, |
| 261 | }; |
| 262 | for (const auto& [prop, prop_val] : set_prop_list) { |
| 263 | base::SetProperty(prop, prop_val); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | static void* mmapFile(const char* dataFilePath) { |
| 268 | #ifdef _WIN32 |
| 269 | // Windows needs file path in wide chars to handle unicode file paths |
| 270 | int size = MultiByteToWideChar(CP_UTF8, 0, dataFilePath, -1, NULL, 0); |
| 271 | std::vector<wchar_t> wideDataFilePath(size); |
| 272 | MultiByteToWideChar(CP_UTF8, 0, dataFilePath, -1, wideDataFilePath.data(), size); |
| 273 | HANDLE file = |
| 274 | CreateFileW(wideDataFilePath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, |
| 275 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, nullptr); |
| 276 | if ((HANDLE)INVALID_HANDLE_VALUE == file) { |
| 277 | return nullptr; |
| 278 | } |
| 279 | |
| 280 | struct CloseHandleWrapper { |
| 281 | void operator()(HANDLE h) { CloseHandle(h); } |
| 282 | }; |
| 283 | std::unique_ptr<void, CloseHandleWrapper> mmapHandle( |
| 284 | CreateFileMapping(file, nullptr, PAGE_READONLY, 0, 0, nullptr)); |
| 285 | if (!mmapHandle) { |
| 286 | return nullptr; |
| 287 | } |
| 288 | return MapViewOfFile(mmapHandle.get(), FILE_MAP_READ, 0, 0, 0); |
| 289 | #else |
| 290 | int fd = open(dataFilePath, O_RDONLY); |
| 291 | if (fd == -1) { |
| 292 | return nullptr; |
| 293 | } |
| 294 | |
| 295 | struct stat sb; |
| 296 | if (fstat(fd, &sb) == -1) { |
| 297 | close(fd); |
| 298 | return nullptr; |
| 299 | } |
| 300 | |
| 301 | void* addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); |
| 302 | if (addr == MAP_FAILED) { |
| 303 | close(fd); |
| 304 | return nullptr; |
| 305 | } |
| 306 | |
| 307 | close(fd); |
| 308 | return addr; |
| 309 | #endif |
| 310 | } |
| 311 | |
| 312 | static bool init_icu(const char* dataPath) { |
| 313 | void* addr = mmapFile(dataPath); |
| 314 | UErrorCode err = U_ZERO_ERROR; |
| 315 | udata_setCommonData(addr, &err); |
| 316 | if (err != U_ZERO_ERROR) { |
| 317 | return false; |
| 318 | } |
| 319 | return true; |
| 320 | } |
| 321 | |
| 322 | } // namespace android |
| 323 | |
| 324 | using namespace android; |
| 325 | |
| 326 | JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { |
| 327 | javaVM = vm; |
| 328 | JNIEnv* env = nullptr; |
| 329 | if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) { |
| 330 | return JNI_ERR; |
| 331 | } |
| 332 | |
| 333 | init_android_graphics(); |
| 334 | |
| 335 | // Configuration is stored as java System properties. |
| 336 | // Get a reference to System.getProperty |
| 337 | jclass system = FindClassOrDie(env, "java/lang/System"); |
| 338 | jmethodID getPropertyMethod = GetStaticMethodIDOrDie(env, system, "getProperty", |
| 339 | "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); |
| 340 | |
| 341 | // Get the names of classes that need to register their native methods |
| 342 | auto nativesClassesJString = |
| 343 | (jstring)env->CallStaticObjectMethod(system, getPropertyMethod, |
| 344 | env->NewStringUTF("core_native_classes"), |
| 345 | env->NewStringUTF("")); |
| 346 | vector<string> classesToRegister = parseCsv(env, nativesClassesJString); |
| 347 | |
| 348 | jstring registerProperty = |
| 349 | (jstring)env->CallStaticObjectMethod(system, getPropertyMethod, |
| 350 | env->NewStringUTF( |
| 351 | "register_properties_during_load"), |
| 352 | env->NewStringUTF("")); |
| 353 | const char* registerPropertyString = env->GetStringUTFChars(registerProperty, 0); |
| 354 | if (strcmp(registerPropertyString, "true") == 0) { |
| 355 | // Set the system properties first as they could be used in the static initialization of |
| 356 | // other classes |
| 357 | if (register_android_os_SystemProperties(env) < 0) { |
| 358 | return JNI_ERR; |
| 359 | } |
| 360 | classesToRegister.erase(find(classesToRegister.begin(), classesToRegister.end(), |
| 361 | "android.os.SystemProperties")); |
| 362 | bridge = FindClassOrDie(env, "com/android/layoutlib/bridge/Bridge"); |
| 363 | bridge = MakeGlobalRefOrDie(env, bridge); |
| 364 | jmethodID setSystemPropertiesMethod = |
| 365 | GetStaticMethodIDOrDie(env, bridge, "setSystemProperties", "()V"); |
| 366 | env->CallStaticVoidMethod(bridge, setSystemPropertiesMethod); |
| 367 | property_initialize_ro_cpu_abilist(); |
| 368 | } |
| 369 | env->ReleaseStringUTFChars(registerProperty, registerPropertyString); |
| 370 | |
| 371 | if (register_jni_procs(gRegJNIMap, classesToRegister, env) < 0) { |
| 372 | return JNI_ERR; |
| 373 | } |
| 374 | |
| 375 | // Set the location of ICU data |
| 376 | auto stringPath = (jstring)env->CallStaticObjectMethod(system, getPropertyMethod, |
| 377 | env->NewStringUTF("icu.data.path"), |
| 378 | env->NewStringUTF("")); |
| 379 | const char* path = env->GetStringUTFChars(stringPath, 0); |
| 380 | bool icuInitialized = init_icu(path); |
| 381 | env->ReleaseStringUTFChars(stringPath, path); |
| 382 | if (!icuInitialized) { |
| 383 | return JNI_ERR; |
| 384 | } |
| 385 | |
| 386 | jstring useJniProperty = |
| 387 | (jstring)env->CallStaticObjectMethod(system, getPropertyMethod, |
| 388 | env->NewStringUTF("use_bridge_for_logging"), |
| 389 | env->NewStringUTF("")); |
| 390 | const char* useJniString = env->GetStringUTFChars(useJniProperty, 0); |
| 391 | if (strcmp(useJniString, "true") == 0) { |
| 392 | layoutLog = FindClassOrDie(env, "com/android/ide/common/rendering/api/ILayoutLog"); |
| 393 | layoutLog = MakeGlobalRefOrDie(env, layoutLog); |
| 394 | logMethodId = GetMethodIDOrDie(env, layoutLog, "logAndroidFramework", |
| 395 | "(ILjava/lang/String;Ljava/lang/String;)V"); |
| 396 | if (bridge == nullptr) { |
| 397 | bridge = FindClassOrDie(env, "com/android/layoutlib/bridge/Bridge"); |
| 398 | bridge = MakeGlobalRefOrDie(env, bridge); |
| 399 | } |
| 400 | getLogId = GetStaticMethodIDOrDie(env, bridge, "getLog", |
| 401 | "()Lcom/android/ide/common/rendering/api/ILayoutLog;"); |
| 402 | android::base::SetLogger(LayoutlibLogger); |
| 403 | android::base::SetAborter(LayoutlibAborter); |
| 404 | } else { |
| 405 | // initialize logging, so ANDROD_LOG_TAGS env variable is respected |
| 406 | android::base::InitLogging(nullptr, android::base::StderrLogger); |
| 407 | } |
| 408 | env->ReleaseStringUTFChars(useJniProperty, useJniString); |
| 409 | |
| 410 | // Use English locale for number format to ensure correct parsing of floats when using strtof |
| 411 | setlocale(LC_NUMERIC, "en_US.UTF-8"); |
| 412 | |
| 413 | return JNI_VERSION_1_6; |
| 414 | } |
| 415 | |
| 416 | JNIEXPORT void JNI_OnUnload(JavaVM* vm, void*) { |
| 417 | JNIEnv* env = nullptr; |
| 418 | vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6); |
| 419 | env->DeleteGlobalRef(bridge); |
| 420 | env->DeleteGlobalRef(layoutLog); |
| 421 | } |