Skip to content

Commit c5de943

Browse files
Fixed the native crash happening on Android.
* Improved the `getPtr` method to throw a `NativeHandleDisposedException` when a native object is `nullptr`, updated the `CATCH_EXCEPTION` macro to handle this exception by mapping it to `java.lang.IllegalStateException`, and ensured proper error handling to prevent crashes when accessing disposed objects.
1 parent 4c6dadb commit c5de943

2 files changed

Lines changed: 11 additions & 0 deletions

File tree

lib/src/main/cpp/macros.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ catch(const zim::ZimFileFormatError& e) { \
5353
} catch(const zim::EntryNotFound& e) { \
5454
throwException(env, "org/kiwix/libzim/EntryNotFoundException", e.what()); \
5555
return RET; \
56+
} catch (const NativeHandleDisposedException& e) { \
57+
throwException(env, "java/lang/IllegalStateException", e.what()); \
58+
return RET; \
5659
} catch (const std::ios_base::failure& e) { \
5760
throwException(env, "java/io/IOException", e.what()); \
5861
return RET; \

lib/src/main/cpp/utils.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,11 @@ inline void setHandle(JNIEnv* env, jobject thisObj, Args && ...args)
9696
}
9797
#define SET_HANDLE(NATIVE_TYPE, OBJ, VALUE) setHandle<NATIVE_TYPE>(env, OBJ, VALUE)
9898

99+
class NativeHandleDisposedException : public std::runtime_error {
100+
public:
101+
explicit NativeHandleDisposedException(const std::string& message)
102+
: std::runtime_error(message) {}
103+
};
99104

100105
// Return a shared_ptr for the handle
101106
template<typename T>
@@ -104,6 +109,9 @@ shared_ptr<T> getPtr(JNIEnv* env, jobject thisObj, const char* handleName = "nat
104109
jclass thisClass = env->GetObjectClass(thisObj);
105110
jfieldID fidNumber = env->GetFieldID(thisClass, handleName, "J");
106111
auto handle = reinterpret_cast<shared_ptr<T>*>(env->GetLongField(thisObj, fidNumber));
112+
if (handle == nullptr) {
113+
throw NativeHandleDisposedException("The native object is already has been disposed");
114+
}
107115
return *handle;
108116
}
109117
#define GET_PTR(NATIVE_TYPE) getPtr<NATIVE_TYPE>(env, thisObj)

0 commit comments

Comments
 (0)