From 31e2f78b3881d850500ef71c250ac784bd1ff546 Mon Sep 17 00:00:00 2001 From: Nate Trost Date: Tue, 10 Nov 2026 12:04:26 -0600 Subject: [PATCH 1/2] BGF: Fix log format args, enable printf format checking, add virtual base dtor, fix Home keycode typo Small, low-risk fixes in base_game_framework for undefined behavior and compiler warnings: - VulkanAPIUtils::CheckVkResult: pass the missing `message` argument for the `%s` specifier (guarding against nullptr). - GraphicsAPIGLES::ParseEGLConfigs: pass the missing `feature_flags_` argument for the `0x%x` specifier. - DebugManager::Log / PlatformUtilLog::Log: add printf format attributes (via a new BGF_PRINTF_FORMAT macro, a no-op on non-GCC/Clang compilers) so -Wformat actually checks call sites. Previously these wrappers were unannotated, so the compiler could not catch the two bugs above, and -Wformat-nonliteral flagged the forwarding call to __android_log_vprint. - GraphicsAPIBase: add a virtual default destructor so derived GraphicsAPIGLES/GraphicsAPIVulkan objects are destroyed correctly through a base pointer (fixes -Wnon-virtual-dtor). - EventKeyCode: add correctly spelled kKeyCode_Home; keep kKeyCode_Gome as an alias marked [[deprecated]] for source compatibility. Tested: agdktunnel builds with -Wall -Werror. All base_game_framework sources compile cleanly with -Wformat -Werror=format-security -Wformat-nonliteral -Wnon-virtual-dtor -Werror. Reintroducing either original log bug now fails with -Wformat-insufficient-args. Using kKeyCode_Gome emits -Wdeprecated-declarations. Verified agdktunnel launches and renders via Vulkan on a Pixel 10 Pro. --- .../base_game_framework/include/debug_manager.h | 14 ++++++++++++-- .../src/android/platform_keycodes_android.h | 4 +++- .../src/gles/graphics_api_gles.cpp | 3 ++- .../base_game_framework/src/graphics_api_base.h | 2 ++ .../base_game_framework/src/platform_util_log.h | 2 +- .../src/vulkan/graphics_api_vulkan_utils.cpp | 4 ++-- 6 files changed, 22 insertions(+), 7 deletions(-) diff --git a/agdk/common/base_game_framework/include/debug_manager.h b/agdk/common/base_game_framework/include/debug_manager.h index 72d2c8f8..d027b7e6 100644 --- a/agdk/common/base_game_framework/include/debug_manager.h +++ b/agdk/common/base_game_framework/include/debug_manager.h @@ -21,6 +21,16 @@ #include #include +// Enables compiler printf-style format string checking (-Wformat) on logging functions. +// format_index and args_index are 1-based parameter positions; pass 0 for args_index +// on functions taking a va_list. +#if defined(__GNUC__) || defined(__clang__) +#define BGF_PRINTF_FORMAT(format_index, args_index) \ + __attribute__((format(printf, format_index, args_index))) +#else +#define BGF_PRINTF_FORMAT(format_index, args_index) +#endif + namespace base_game_framework { /** @@ -130,7 +140,7 @@ namespace base_game_framework { const DebugLogLevel log_level, const char* tag, const char* format, - ...); + ...) BGF_PRINTF_FORMAT(4, 5); /** * @brief Log a debug message with variable parameters @@ -145,7 +155,7 @@ namespace base_game_framework { const DebugLogLevel log_level, const char* tag, const char* format, - va_list specifiers); + va_list specifiers) BGF_PRINTF_FORMAT(4, 0); /** * @brief Log a debug message with a string constant diff --git a/agdk/common/base_game_framework/src/android/platform_keycodes_android.h b/agdk/common/base_game_framework/src/android/platform_keycodes_android.h index 61d5b0c4..d6ab68e3 100644 --- a/agdk/common/base_game_framework/src/android/platform_keycodes_android.h +++ b/agdk/common/base_game_framework/src/android/platform_keycodes_android.h @@ -25,7 +25,9 @@ enum EventKeyCode : int32_t { kKeyCode_Unknown = AKEYCODE_UNKNOWN, kKeyCode_Soft_Left = AKEYCODE_SOFT_LEFT, kKeyCode_Soft_Right = AKEYCODE_SOFT_RIGHT, - kKeyCode_Gome = AKEYCODE_HOME, + kKeyCode_Home = AKEYCODE_HOME, + // Misspelled alias retained for source compatibility. + kKeyCode_Gome [[deprecated("Use kKeyCode_Home instead")]] = kKeyCode_Home, kKeyCode_Back = AKEYCODE_BACK, kKeyCode_Call = AKEYCODE_CALL, kKeyCode_Endcall = AKEYCODE_ENDCALL, diff --git a/agdk/common/base_game_framework/src/gles/graphics_api_gles.cpp b/agdk/common/base_game_framework/src/gles/graphics_api_gles.cpp index 973f1172..3ce354ec 100644 --- a/agdk/common/base_game_framework/src/gles/graphics_api_gles.cpp +++ b/agdk/common/base_game_framework/src/gles/graphics_api_gles.cpp @@ -234,7 +234,8 @@ void GraphicsAPIGLES::ParseEGLConfigs() { DebugManager::Log(DebugManager::kLog_Channel_Default, DebugManager::kLog_Level_Info, BGM_CLASS_TAG, - "EGL config count: %d Feature flags: 0x%x", config_count); + "EGL config count: %d Feature flags: 0x%x", config_count, + static_cast(feature_flags_)); for (EGLint i = 0; i < config_count; ++i) { EGLConfig config = configs[i]; diff --git a/agdk/common/base_game_framework/src/graphics_api_base.h b/agdk/common/base_game_framework/src/graphics_api_base.h index ad2031f7..e32b9d3f 100644 --- a/agdk/common/base_game_framework/src/graphics_api_base.h +++ b/agdk/common/base_game_framework/src/graphics_api_base.h @@ -29,6 +29,8 @@ namespace base_game_framework { class GraphicsAPIBase { public: + virtual ~GraphicsAPIBase() = default; + virtual DisplayManager::GraphicsAPI GetAPI() const = 0; virtual GraphicsAPIStatus GetAPIStatus() const { return kGraphicsAPI_Uninitialized; } virtual const GraphicsAPIFeatures& GetAPIFeatures() const = 0; diff --git a/agdk/common/base_game_framework/src/platform_util_log.h b/agdk/common/base_game_framework/src/platform_util_log.h index 0a5dccd5..e1e4c67e 100644 --- a/agdk/common/base_game_framework/src/platform_util_log.h +++ b/agdk/common/base_game_framework/src/platform_util_log.h @@ -31,7 +31,7 @@ class PlatformUtilLog { static void Log(const DebugManager::DebugLogLevel log_level, const char* tag, const char* format, - va_list specifiers); + va_list specifiers) BGF_PRINTF_FORMAT(3, 0); }; } // namespace base_game_framework diff --git a/agdk/common/base_game_framework/src/vulkan/graphics_api_vulkan_utils.cpp b/agdk/common/base_game_framework/src/vulkan/graphics_api_vulkan_utils.cpp index 14c27b99..8037edee 100644 --- a/agdk/common/base_game_framework/src/vulkan/graphics_api_vulkan_utils.cpp +++ b/agdk/common/base_game_framework/src/vulkan/graphics_api_vulkan_utils.cpp @@ -50,8 +50,8 @@ bool VulkanAPIUtils::CheckVkResult(const VkResult result, const char *message) { DebugManager::Log(DebugManager::kLog_Channel_Default, DebugManager::kLog_Level_Error, "VulkanAPIUtils", - "CheckVkResult failed: %d (%s)", result); - + "CheckVkResult failed: %d (%s)", result, + (message != nullptr) ? message : ""); } return (result == VK_SUCCESS); } From 5357bba04df751f90a1754d8eb00551bd38ac6ac Mon Sep 17 00:00:00 2001 From: Nate Trost Date: Tue, 10 Nov 2026 14:16:25 -0600 Subject: [PATCH 2/2] BGF: Fix JNI string/global ref leaks and free-space thread race Fix JNI resource leaks and a Java data race in base_game_framework's Android platform utilities: - FilesystemManager / SystemInfoUtils: release the UTF chars obtained with GetStringUTFChars for the root paths and package name, via a new PlatformUtilAndroid::JStringToString() helper. - Util object global ref: BaseGameFramework_Destroy() now deletes the global ref to the BaseGameFrameworkUtils object. Previously it was never deleted, so every Activity recreation leaked the old Activity. registerUtilObject() now passes its owning Activity, kept as a weak global ref. Destroy only releases a registration owned by its own Activity, so it can't free a newer Activity's registration (a new onCreate can run before the old onDestroy). No reflection is used, so this works under R8/ProGuard. - Thread safety: the global ref is only accessed under a mutex. Callers now get their own local ref via NewUtilObjectLocalRef(), which keeps the object valid even if a newer Activity replaces the registration. This removes the cached class ref and jmethodIDs. - Java exceptions: every native -> BaseGameFrameworkUtils call now checks for and clears pending exceptions. GetRootPath() and GetExternalStorageEmulated() null-check getExternalFilesDir() in Java instead of throwing a NullPointerException across JNI. - BaseGameFrameworkUtils.retrieveFreeSpace(): the lock was held only while starting the background thread, not while it wrote the results, racing with GetEstimatedFreeSpace(). The thread now queries into locals and publishes all values under the lock in a finally block, also catching RuntimeException (getUuidForPath() can throw IllegalArgumentException). mFreeSpace is final, which also fixes an NPE if queried before Initialize(). - BaseGameFramework_Destroy() clears the JNIEnv, android_app, activity and native window pointers after detaching, unless a newer instance has already re-initialized them. Tested on a Pixel 10 Pro with agdktunnel and CheckJNI enabled: no CheckJNI errors. Forced 6 Activity recreations (night-mode toggles) and checked a heap dump. Before: 7 BaseGameFrameworkUtils objects pinned by JNI global refs. After: 1 (the current Activity's). After each recreation, a temporary log confirmed root paths, package name, free space, emulated storage, DPI and AEP support were correct. The app renders normally. A new Activity registering before the old one is destroyed was not reproduced on device. --- .../BaseGameFrameworkUtils.java | 94 ++++++++----- .../basegameframework_init_android.cpp | 12 ++ .../android/filesystem_manager_android.cpp | 86 +++++++----- .../src/android/platform_util_android.cpp | 132 +++++++++++++----- .../src/android/platform_util_android.h | 33 +++-- .../src/android/system_info_utils_android.cpp | 5 +- 6 files changed, 243 insertions(+), 119 deletions(-) diff --git a/agdk/common/base_game_framework/java/com/google/android/games/basegameframework/BaseGameFrameworkUtils.java b/agdk/common/base_game_framework/java/com/google/android/games/basegameframework/BaseGameFrameworkUtils.java index dd13e557..9223ffef 100644 --- a/agdk/common/base_game_framework/java/com/google/android/games/basegameframework/BaseGameFrameworkUtils.java +++ b/agdk/common/base_game_framework/java/com/google/android/games/basegameframework/BaseGameFrameworkUtils.java @@ -27,6 +27,7 @@ import android.view.Display; import android.view.Surface; +import java.io.File; import java.io.IOException; import java.util.UUID; @@ -58,8 +59,11 @@ private class FreeSpace { public static final int CONTEXT_GET_DISPLAY_MIN_API = Build.VERSION_CODES.R; + private static final String TAG = "BaseGameFrameworkUtils"; + private Activity mGameActivity; - private FreeSpace mFreeSpace; + // Final so readers and the background retrieval thread always lock the same object. + private final FreeSpace mFreeSpace = new FreeSpace(); public BaseGameFrameworkUtils(Activity activity) { mGameActivity = activity; @@ -75,10 +79,12 @@ public boolean GetAndroidFeatureSupported(int featureId) { } public int GetExternalStorageEmulated() { - if (Environment.isExternalStorageEmulated(mGameActivity.getExternalFilesDir(null))) { - return 1; - } - return 0; + // Null if shared storage is currently unavailable; fall back to the primary volume. + File externalDir = mGameActivity.getExternalFilesDir(null); + boolean emulated = (externalDir != null) + ? Environment.isExternalStorageEmulated(externalDir) + : Environment.isExternalStorageEmulated(); + return emulated ? 1 : 0; } public int GetDisplayDPI() { @@ -96,7 +102,11 @@ public String GetRootPath(int pathType) { returnPath = mGameActivity.getFilesDir().getAbsolutePath(); break; case kRootPathExternalStorage: - returnPath = mGameActivity.getExternalFilesDir(null).getAbsolutePath(); + // Null if shared storage is currently unavailable. + File externalDir = mGameActivity.getExternalFilesDir(null); + if (externalDir != null) { + returnPath = externalDir.getAbsolutePath(); + } break; case kRootPathCacheStorage: returnPath = mGameActivity.getCacheDir().getAbsolutePath(); @@ -129,44 +139,54 @@ public long GetEstimatedFreeSpace(int pathType) { public void Initialize() { retrieveFreeSpace(); - registerUtilObject(); + registerUtilObject(mGameActivity); } private void retrieveFreeSpace() { - mFreeSpace = new FreeSpace(); if (Build.VERSION.SDK_INT >= FREE_SPACE_MIN_API) { - synchronized (mFreeSpace) { - new Thread(new Runnable() { - public void run() { - try { - StorageManager storageManager = (StorageManager) - mGameActivity.getSystemService(Context.STORAGE_SERVICE); - - UUID cacheUUID = storageManager.getUuidForPath( - mGameActivity.getCacheDir()); - long quota = storageManager.getCacheQuotaBytes(cacheUUID); - mFreeSpace.cacheSpace = quota; - - UUID internalUUID = storageManager.getUuidForPath( - mGameActivity.getFilesDir()); - mFreeSpace.internalSpace = - storageManager.getAllocatableBytes(internalUUID); - - UUID externalUUID = storageManager.getUuidForPath( - mGameActivity.getExternalFilesDir(null)); - mFreeSpace.externalSpace = storageManager.getAllocatableBytes( - externalUUID); - mFreeSpace.retrieved = true; - } catch (IOException e) { + new Thread(new Runnable() { + public void run() { + // Query into locals, then publish all values under the lock so + // GetEstimatedFreeSpace() never observes a partially updated FreeSpace. + long cacheSpace = 0; + long internalSpace = 0; + long externalSpace = 0; + try { + StorageManager storageManager = (StorageManager) + mGameActivity.getSystemService(Context.STORAGE_SERVICE); + + UUID cacheUUID = storageManager.getUuidForPath( + mGameActivity.getCacheDir()); + cacheSpace = storageManager.getCacheQuotaBytes(cacheUUID); + + UUID internalUUID = storageManager.getUuidForPath( + mGameActivity.getFilesDir()); + internalSpace = storageManager.getAllocatableBytes(internalUUID); + + // Null if shared storage is currently unavailable. + File externalDir = mGameActivity.getExternalFilesDir(null); + if (externalDir != null) { + UUID externalUUID = storageManager.getUuidForPath(externalDir); + externalSpace = storageManager.getAllocatableBytes(externalUUID); + } + } catch (IOException | RuntimeException e) { + // getUuidForPath() can also throw IllegalArgumentException. + Log.w(TAG, "Failed to retrieve free space", e); + } finally { + synchronized (mFreeSpace) { + mFreeSpace.cacheSpace = cacheSpace; + mFreeSpace.internalSpace = internalSpace; + mFreeSpace.externalSpace = externalSpace; mFreeSpace.retrieved = true; - e.printStackTrace(); } } - }).start(); - } + } + }).start(); } else { // If no API support, set retrieved, but all sizes are 0 - mFreeSpace.retrieved = true; + synchronized (mFreeSpace) { + mFreeSpace.retrieved = true; + } } } @@ -184,5 +204,7 @@ public int getDeviceRotation() } return rotation; } - public native void registerUtilObject(); + // `activity` identifies the owner so native code only releases this registration + // when that Activity's native thread shuts down. + private native void registerUtilObject(Activity activity); } diff --git a/agdk/common/base_game_framework/src/android/basegameframework_init_android.cpp b/agdk/common/base_game_framework/src/android/basegameframework_init_android.cpp index 707fdcd7..f4186723 100644 --- a/agdk/common/base_game_framework/src/android/basegameframework_init_android.cpp +++ b/agdk/common/base_game_framework/src/android/basegameframework_init_android.cpp @@ -60,7 +60,19 @@ void BaseGameFramework_Destroy() { FilesystemManager::ShutdownInstance(); DebugManager::ShutdownInstance(); android_app *app = PlatformUtilAndroid::GetAndroidApp(); + PlatformUtilAndroid::ReleaseUtilObject(PlatformUtilAndroid::GetMainThreadJNIEnv(), + app->activity->javaGameActivity); app->activity->vm->DetachCurrentThread(); + + // Don't leave dangling pointers to the detached JNIEnv / destroyed android_app + // between this shutdown and the next BaseGameFramework_Init(). Skip if a newer + // instance has already re-initialized these process-wide values. + if (PlatformUtilAndroid::GetAndroidApp() == app) { + PlatformUtilAndroid::SetMainThreadJniEnv(nullptr); + PlatformUtilAndroid::SetActivityClassObject(nullptr); + PlatformUtilAndroid::SetNativeWindow(nullptr); + PlatformUtilAndroid::SetAndroidApp(nullptr); + } } } // namespace basegameframework \ No newline at end of file diff --git a/agdk/common/base_game_framework/src/android/filesystem_manager_android.cpp b/agdk/common/base_game_framework/src/android/filesystem_manager_android.cpp index 46bf5c3e..4d8840f4 100644 --- a/agdk/common/base_game_framework/src/android/filesystem_manager_android.cpp +++ b/agdk/common/base_game_framework/src/android/filesystem_manager_android.cpp @@ -35,32 +35,32 @@ void FilesystemManager::ShutdownInstance() { FilesystemManager::FilesystemManager() { JNIEnv *env = PlatformUtilAndroid::GetMainThreadJNIEnv(); - jclass util_class = PlatformUtilAndroid::GetUtilClass(); - jobject util_object = PlatformUtilAndroid::GetUtilClassObject(); - if (env != nullptr && util_object != nullptr) { + jobject util_object = PlatformUtilAndroid::NewUtilObjectLocalRef(env); + if (util_object != nullptr) { + jclass util_class = env->GetObjectClass(util_object); jmethodID method_getrootpath = env->GetMethodID(util_class, "GetRootPath", "(I)Ljava/lang/String;"); - jstring ipath_jstring = static_cast( - env->CallObjectMethod(util_object, method_getrootpath, - static_cast(kRootPathInternalStorage))); - const char *ipath = env->GetStringUTFChars(ipath_jstring, NULL); - root_path_internal_ = ipath; - env->DeleteLocalRef(ipath_jstring); - - jstring epath_jstring = static_cast( - env->CallObjectMethod(util_object, method_getrootpath, - static_cast(kRootPathExternalStorage))); - const char *epath = env->GetStringUTFChars(epath_jstring, NULL); - root_path_external_ = epath; - env->DeleteLocalRef(epath_jstring); - - jstring cpath_jstring = static_cast( - env->CallObjectMethod(util_object, method_getrootpath, - static_cast(kRootPathCache))); - const char *cpath = env->GetStringUTFChars(cpath_jstring, NULL); - root_path_cache_ = cpath; - env->DeleteLocalRef(cpath_jstring); - } else if (util_object == nullptr) { + auto get_root_path = [env, util_object, method_getrootpath](RootPathType path_type) { + jstring path_jstring = static_cast( + env->CallObjectMethod(util_object, method_getrootpath, + static_cast(path_type))); + std::string path; + if (!PlatformUtilAndroid::ClearPendingException(env)) { + path = PlatformUtilAndroid::JStringToString(env, path_jstring); + } + env->DeleteLocalRef(path_jstring); + return path; + }; + if (method_getrootpath != nullptr) { + root_path_internal_ = get_root_path(kRootPathInternalStorage); + root_path_external_ = get_root_path(kRootPathExternalStorage); + root_path_cache_ = get_root_path(kRootPathCache); + } else { + PlatformUtilAndroid::ClearPendingException(env); + } + env->DeleteLocalRef(util_class); + env->DeleteLocalRef(util_object); + } else if (env != nullptr) { DebugManager::Log(DebugManager::kLog_Channel_Default, DebugManager::kLog_Level_Error, "FilesystemManager", @@ -71,13 +71,21 @@ FilesystemManager::FilesystemManager() { bool FilesystemManager::GetExternalStorageEmulated() const { bool emulated = true; JNIEnv *env = PlatformUtilAndroid::GetMainThreadJNIEnv(); - jclass util_class = PlatformUtilAndroid::GetUtilClass(); - jobject util_object = PlatformUtilAndroid::GetUtilClassObject(); - if (env != nullptr && util_object != nullptr) { + jobject util_object = PlatformUtilAndroid::NewUtilObjectLocalRef(env); + if (util_object != nullptr) { + jclass util_class = env->GetObjectClass(util_object); jmethodID method_getemulated = env->GetMethodID(util_class, "GetExternalStorageEmulated", "()I"); - jint jemulated = env->CallIntMethod(util_object, method_getemulated); - emulated = jemulated == 1 ? true : false; + if (method_getemulated != nullptr) { + const jint jemulated = env->CallIntMethod(util_object, method_getemulated); + if (!PlatformUtilAndroid::ClearPendingException(env)) { + emulated = (jemulated == 1); + } + } else { + PlatformUtilAndroid::ClearPendingException(env); + } + env->DeleteLocalRef(util_class); + env->DeleteLocalRef(util_object); } return emulated; } @@ -95,14 +103,22 @@ int64_t FilesystemManager::GetFreeSpace(const RootPathType path_type) const { int64_t free_space = -1; JNIEnv *env = PlatformUtilAndroid::GetMainThreadJNIEnv(); - jclass util_class = PlatformUtilAndroid::GetUtilClass(); - jobject util_object = PlatformUtilAndroid::GetUtilClassObject(); - if (env != nullptr && util_object != nullptr) { + jobject util_object = PlatformUtilAndroid::NewUtilObjectLocalRef(env); + if (util_object != nullptr) { + jclass util_class = env->GetObjectClass(util_object); jmethodID method_getfreespace = env->GetMethodID(util_class, "GetEstimatedFreeSpace", "(I)J"); - jlong jfree_space = env->CallLongMethod(util_object, method_getfreespace, - static_cast(path_type)); - free_space = static_cast(jfree_space); + if (method_getfreespace != nullptr) { + const jlong jfree_space = env->CallLongMethod(util_object, method_getfreespace, + static_cast(path_type)); + if (!PlatformUtilAndroid::ClearPendingException(env)) { + free_space = static_cast(jfree_space); + } + } else { + PlatformUtilAndroid::ClearPendingException(env); + } + env->DeleteLocalRef(util_class); + env->DeleteLocalRef(util_object); } return free_space; } diff --git a/agdk/common/base_game_framework/src/android/platform_util_android.cpp b/agdk/common/base_game_framework/src/android/platform_util_android.cpp index 42d655df..f00e0c63 100644 --- a/agdk/common/base_game_framework/src/android/platform_util_android.cpp +++ b/agdk/common/base_game_framework/src/android/platform_util_android.cpp @@ -16,67 +16,135 @@ #include "platform_util_android.h" +#include +#include + namespace base_game_framework { static constexpr const char* kGetAndroidFeatureSupportedName = "GetAndroidFeatureSupported"; static constexpr const char* kGetAndroidFeatureSupportedSignature = "(I)Z"; static constexpr const char* kGetDisplayDPIName = "GetDisplayDPI"; static constexpr const char* kGetDisplayDPISignature = "()I"; +namespace { +// The registered Java BaseGameFrameworkUtils object (global ref) and the Activity that +// owns it (weak global ref). Written on the Java UI thread by RegisterUtilObject and +// read/released on the native app thread, so all access is guarded by util_object_mutex. +std::mutex util_object_mutex; +jobject util_object = nullptr; +jweak util_owner_activity = nullptr; + +void DeleteUtilObjectRefsLocked(JNIEnv *env) { + if (util_object != nullptr) { + env->DeleteGlobalRef(util_object); + util_object = nullptr; + } + if (util_owner_activity != nullptr) { + env->DeleteWeakGlobalRef(util_owner_activity); + util_owner_activity = nullptr; + } +} +} // anonymous namespace + android_app* PlatformUtilAndroid::android_app_ = nullptr; JNIEnv* PlatformUtilAndroid::jni_env_ = nullptr; jclass PlatformUtilAndroid::activity_class_ = nullptr; jobject PlatformUtilAndroid::activity_class_object_ = nullptr; -jclass PlatformUtilAndroid::util_class_ = nullptr; -jobject PlatformUtilAndroid::util_class_object_ = nullptr; -jmethodID PlatformUtilAndroid::get_android_feature_method_ = nullptr; -jmethodID PlatformUtilAndroid::get_display_dpi_method_ = nullptr; ANativeWindow *PlatformUtilAndroid::native_window_ = nullptr; bool PlatformUtilAndroid::has_focus_ = false; std::thread::id PlatformUtilAndroid::main_thread_id_; bool PlatformUtilAndroid::GetAndroidFeatureSupported(const AndroidFeature android_feature) { bool supported = false; - if (util_class_ != nullptr && util_class_object_ != nullptr && jni_env_ != nullptr && - get_android_feature_method_ != nullptr) { - jboolean result = jni_env_->CallBooleanMethod(util_class_object_, - get_android_feature_method_, - static_cast(android_feature)); - supported = (result == JNI_TRUE); + JNIEnv *env = jni_env_; + jobject util = NewUtilObjectLocalRef(env); + if (util != nullptr) { + jclass util_class = env->GetObjectClass(util); + jmethodID method = env->GetMethodID(util_class, kGetAndroidFeatureSupportedName, + kGetAndroidFeatureSupportedSignature); + if (method != nullptr) { + const jboolean result = env->CallBooleanMethod(util, method, + static_cast(android_feature)); + supported = !ClearPendingException(env) && (result == JNI_TRUE); + } else { + ClearPendingException(env); + } + env->DeleteLocalRef(util_class); + env->DeleteLocalRef(util); } return supported; } int PlatformUtilAndroid::GetDisplayDPI() { int dpi = 0; - if (util_class_ != nullptr && util_class_object_ != nullptr && jni_env_ != nullptr && - get_display_dpi_method_ != nullptr) { - dpi = jni_env_->CallIntMethod(util_class_object_, get_display_dpi_method_); + JNIEnv *env = jni_env_; + jobject util = NewUtilObjectLocalRef(env); + if (util != nullptr) { + jclass util_class = env->GetObjectClass(util); + jmethodID method = env->GetMethodID(util_class, kGetDisplayDPIName, kGetDisplayDPISignature); + if (method != nullptr) { + const jint result = env->CallIntMethod(util, method); + dpi = ClearPendingException(env) ? 0 : result; + } else { + ClearPendingException(env); + } + env->DeleteLocalRef(util_class); + env->DeleteLocalRef(util); } return dpi; } -void PlatformUtilAndroid::InitMethods(JNIEnv* env) { - get_android_feature_method_ = env->GetMethodID(util_class_, - kGetAndroidFeatureSupportedName, - kGetAndroidFeatureSupportedSignature); - get_display_dpi_method_ = env->GetMethodID(util_class_, - kGetDisplayDPIName, - kGetDisplayDPISignature); +jobject PlatformUtilAndroid::NewUtilObjectLocalRef(JNIEnv *env) { + if (env == nullptr) { + return nullptr; + } + std::lock_guard lock(util_object_mutex); + return (util_object != nullptr) ? env->NewLocalRef(util_object) : nullptr; +} + +void PlatformUtilAndroid::RegisterUtilObject(JNIEnv *env, jobject util, jobject activity) { + std::lock_guard lock(util_object_mutex); + // Any thread still using a previous registration holds its own local ref + // (see NewUtilObjectLocalRef), so the old global refs can be deleted right away. + DeleteUtilObjectRefsLocked(env); + util_object = env->NewGlobalRef(util); + util_owner_activity = (activity != nullptr) ? env->NewWeakGlobalRef(activity) : nullptr; +} + +void PlatformUtilAndroid::ReleaseUtilObject(JNIEnv *env, jobject activity) { + if (env == nullptr || activity == nullptr) { + return; + } + std::lock_guard lock(util_object_mutex); + if (util_owner_activity != nullptr && env->IsSameObject(util_owner_activity, activity)) { + DeleteUtilObjectRefsLocked(env); + } +} + +std::string PlatformUtilAndroid::JStringToString(JNIEnv *env, jstring jstr) { + std::string result; + if (env != nullptr && jstr != nullptr) { + const char *chars = env->GetStringUTFChars(jstr, nullptr); + if (chars != nullptr) { + result = chars; + env->ReleaseStringUTFChars(jstr, chars); + } + } + return result; +} + +bool PlatformUtilAndroid::ClearPendingException(JNIEnv *env) { + if (env != nullptr && env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + return true; + } + return false; } } // namespace base_game_framework extern "C" JNIEXPORT void JNICALL Java_com_google_android_games_basegameframework_BaseGameFrameworkUtils_registerUtilObject( - JNIEnv* env, jobject thiz) { - jclass activity_class = env->GetObjectClass(thiz); - if (activity_class != nullptr) { - base_game_framework::PlatformUtilAndroid::SetUtilClass( - static_cast(env->NewGlobalRef(activity_class))); - base_game_framework::PlatformUtilAndroid::SetUtilClassObject( - env->NewGlobalRef(thiz)); - env->DeleteLocalRef(activity_class); - - base_game_framework::PlatformUtilAndroid::InitMethods(env); - } -} \ No newline at end of file + JNIEnv* env, jobject thiz, jobject activity) { + base_game_framework::PlatformUtilAndroid::RegisterUtilObject(env, thiz, activity); +} diff --git a/agdk/common/base_game_framework/src/android/platform_util_android.h b/agdk/common/base_game_framework/src/android/platform_util_android.h index 81e8dc25..b633a007 100644 --- a/agdk/common/base_game_framework/src/android/platform_util_android.h +++ b/agdk/common/base_game_framework/src/android/platform_util_android.h @@ -19,6 +19,7 @@ #include #include +#include #include #include "game-activity/native_app_glue/android_native_app_glue.h" @@ -46,12 +47,26 @@ class PlatformUtilAndroid { activity_class_object_ = activity_class_object; } - static jclass GetUtilClass() { return util_class_; } - static void SetUtilClass(jclass clazz) { util_class_ = clazz; } - static jobject GetUtilClassObject() { return util_class_object_; } - static void SetUtilClassObject(jobject util_class_object) { - util_class_object_ = util_class_object; - } + // Returns a new local ref to the registered Java BaseGameFrameworkUtils object, or + // nullptr if none is registered. The caller must DeleteLocalRef() the result. Holding + // the local ref keeps the object valid even if a newer Activity registers concurrently. + static jobject NewUtilObjectLocalRef(JNIEnv *env); + + // Stores a global ref to the Java BaseGameFrameworkUtils object, owned by `activity`, + // replacing (and deleting) any previous registration. + // Called from BaseGameFrameworkUtils.registerUtilObject() on the Java UI thread. + static void RegisterUtilObject(JNIEnv *env, jobject util_object, jobject activity); + + // Deletes the registered refs if they belong to `activity`. A registration made by a + // newer Activity is left untouched. Called from BaseGameFramework_Destroy(). + static void ReleaseUtilObject(JNIEnv *env, jobject activity); + + // Converts a Java string to a std::string, releasing the JNI UTF chars. + // Returns an empty string if `jstr` is null. Does not delete the `jstr` local ref. + static std::string JStringToString(JNIEnv *env, jstring jstr); + + // If a Java exception is pending, logs and clears it and returns true. + static bool ClearPendingException(JNIEnv *env); static ANativeWindow* GetNativeWindow() { return native_window_; } static void SetNativeWindow(ANativeWindow* native_window) { native_window_ = native_window; } @@ -63,17 +78,11 @@ class PlatformUtilAndroid { static std::thread::id GetMainThreadID() { return main_thread_id_; } static bool RunningOnMainThread() { return std::this_thread::get_id() == main_thread_id_; } - static void InitMethods(JNIEnv *env); - private: static android_app* android_app_; static JNIEnv* jni_env_; static jclass activity_class_; static jobject activity_class_object_; - static jclass util_class_; - static jobject util_class_object_; - static jmethodID get_android_feature_method_; - static jmethodID get_display_dpi_method_; static ANativeWindow *native_window_; static std::thread::id main_thread_id_; static bool has_focus_; diff --git a/agdk/common/base_game_framework/src/android/system_info_utils_android.cpp b/agdk/common/base_game_framework/src/android/system_info_utils_android.cpp index 7e0bc60a..82d6a718 100644 --- a/agdk/common/base_game_framework/src/android/system_info_utils_android.cpp +++ b/agdk/common/base_game_framework/src/android/system_info_utils_android.cpp @@ -30,10 +30,7 @@ const std::string &SystemInfoUtils::GetApplicationPackageName() { "()Ljava/lang/String;"); jstring package_name_jstring = static_cast( env->CallObjectMethod(activity_object, method_getpackagename)); - const char *package_name = env->GetStringUTFChars(package_name_jstring, NULL); - if (package_name != NULL) { - application_package_name_ = package_name; - } + application_package_name_ = PlatformUtilAndroid::JStringToString(env, package_name_jstring); env->DeleteLocalRef(activity_class); env->DeleteLocalRef(package_name_jstring); }