Initialize.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "il2cpp-config.h"
  2. #if IL2CPP_TARGET_ANDROID
  3. #include <string>
  4. #include "os/Initialize.h"
  5. #include "os/LibraryLoader.h"
  6. #include "utils/Logging.h"
  7. #include <jni.h>
  8. #include <android/log.h>
  9. static void AndroidLogCallback(const char* message)
  10. {
  11. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "%s", message);
  12. }
  13. JavaVM *sJavaVM = nullptr;
  14. static const Il2CppNativeChar* AndroidLoadLibrary(const Il2CppNativeChar* libName)
  15. {
  16. if (sJavaVM == nullptr)
  17. {
  18. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "Java VM not initialized");
  19. return libName;
  20. }
  21. if (libName != nullptr)
  22. {
  23. JNIEnv* env = nullptr;
  24. bool detached = sJavaVM->GetEnv((void**)&env, JNI_VERSION_1_2) == JNI_EDETACHED;
  25. if (detached)
  26. {
  27. sJavaVM->AttachCurrentThread(&env, NULL);
  28. }
  29. env->ExceptionClear();
  30. jclass systemClass = env->FindClass("java/lang/System");
  31. if (systemClass != nullptr)
  32. {
  33. jmethodID loadLibrary = env->GetStaticMethodID(systemClass, "loadLibrary", "(Ljava/lang/String;)V");
  34. if (loadLibrary != nullptr)
  35. {
  36. jstring jstr = env->NewStringUTF(libName);
  37. env->CallStaticVoidMethod(systemClass, loadLibrary, jstr);
  38. if (env->ExceptionCheck())
  39. {
  40. env->ExceptionClear();
  41. // try without lib prefix
  42. if (std::string(libName).find("lib") == 0)
  43. {
  44. jstr = env->NewStringUTF(libName + 3);
  45. env->CallStaticVoidMethod(systemClass, loadLibrary, jstr);
  46. }
  47. }
  48. }
  49. }
  50. if (env->ExceptionCheck())
  51. {
  52. env->ExceptionClear();
  53. }
  54. if (detached)
  55. {
  56. sJavaVM->DetachCurrentThread();
  57. }
  58. }
  59. return libName;
  60. }
  61. extern "C"
  62. JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
  63. {
  64. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "JNI_OnLoad");
  65. sJavaVM = jvm;
  66. il2cpp::os::LibraryLoader::SetFindPluginCallback(AndroidLoadLibrary);
  67. return JNI_VERSION_1_6;
  68. }
  69. extern "C"
  70. JNIEXPORT void JNI_OnUnload(JavaVM *jvm, void *reserved)
  71. {
  72. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "JNI_OnUnload");
  73. sJavaVM = nullptr;
  74. }
  75. void il2cpp::os::Initialize()
  76. {
  77. if (!utils::Logging::IsLogCallbackSet())
  78. utils::Logging::SetLogCallback(AndroidLogCallback);
  79. }
  80. void il2cpp::os::Uninitialize()
  81. {
  82. }
  83. #endif