Skip to content

Commit

Permalink
[Android]Remove unnecessary globalRef for android IM JNI (#29710)
Browse files Browse the repository at this point in the history
* Remove unnecessary globalRef for android im functions

localReferences created by sdk's local functions  has not yet been
removed and are still valid, so there is no need to create globalRef when it is returned
from local functions.

* Restyled by clang-format

* add JniGlobalReference class with move constructor

* Restyled by whitespace

* Restyled by clang-format

---------

Co-authored-by: Restyled.io <[email protected]>
  • Loading branch information
2 people authored and pull[bot] committed Dec 1, 2023
1 parent b254599 commit 85c7c31
Show file tree
Hide file tree
Showing 6 changed files with 243 additions and 326 deletions.
459 changes: 168 additions & 291 deletions src/controller/java/AndroidCallbacks.cpp

Large diffs are not rendered by default.

27 changes: 14 additions & 13 deletions src/controller/java/AndroidCallbacks.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@
#include <controller/CHIPDeviceController.h>
#include <jni.h>
#include <lib/core/CHIPError.h>
#include <lib/support/JniTypeWrappers.h>
#include <list>
#include <utility>

namespace chip {
namespace Controller {

CHIP_ERROR CreateChipAttributePath(const app::ConcreteDataAttributePath & aPath, jobject & outObj);
CHIP_ERROR CreateChipAttributePath(JNIEnv * env, const app::ConcreteDataAttributePath & aPath, jobject & outObj);

// Callback for success and failure cases of GetConnectedDevice().
struct GetConnectedDeviceCallback
Expand All @@ -42,8 +43,8 @@ struct GetConnectedDeviceCallback

Callback::Callback<OnDeviceConnected> mOnSuccess;
Callback::Callback<OnDeviceConnectionFailure> mOnFailure;
jobject mWrapperCallbackRef = nullptr;
jobject mJavaCallbackRef = nullptr;
JniGlobalReference mWrapperCallbackRef;
JniGlobalReference mJavaCallbackRef;
};

struct ReportCallback : public app::ClusterStateCache::Callback
Expand Down Expand Up @@ -76,19 +77,19 @@ struct ReportCallback : public app::ClusterStateCache::Callback
void ReportError(jobject attributePath, jobject eventPath, Protocols::InteractionModel::Status status);
void ReportError(jobject attributePath, jobject eventPath, const char * message, ChipError::StorageType errorCode);

CHIP_ERROR CreateChipEventPath(const app::ConcreteEventPath & aPath, jobject & outObj);
CHIP_ERROR CreateChipEventPath(JNIEnv * env, const app::ConcreteEventPath & aPath, jobject & outObj);

void UpdateClusterDataVersion();

app::ReadClient * mReadClient = nullptr;

app::ClusterStateCache mClusterCacheAdapter;
jobject mWrapperCallbackRef = nullptr;
jobject mSubscriptionEstablishedCallbackRef = nullptr;
jobject mResubscriptionAttemptCallbackRef = nullptr;
jobject mReportCallbackRef = nullptr;
JniGlobalReference mWrapperCallbackRef;
JniGlobalReference mSubscriptionEstablishedCallbackRef;
JniGlobalReference mResubscriptionAttemptCallbackRef;
JniGlobalReference mReportCallbackRef;
// NodeState Java object that will be returned to the application.
jobject mNodeStateObj = nullptr;
JniGlobalReference mNodeStateObj;
};

struct WriteAttributesCallback : public app::WriteClient::Callback
Expand All @@ -110,8 +111,8 @@ struct WriteAttributesCallback : public app::WriteClient::Callback

app::WriteClient * mWriteClient = nullptr;
app::ChunkedWriteCallback mChunkedWriteCallback;
jobject mWrapperCallbackRef = nullptr;
jobject mJavaCallbackRef = nullptr;
JniGlobalReference mWrapperCallbackRef;
JniGlobalReference mJavaCallbackRef;
};

struct InvokeCallback : public app::CommandSender::Callback
Expand All @@ -132,8 +133,8 @@ struct InvokeCallback : public app::CommandSender::Callback
void ReportError(const char * message, ChipError::StorageType errorCode);

app::CommandSender * mCommandSender = nullptr;
jobject mWrapperCallbackRef = nullptr;
jobject mJavaCallbackRef = nullptr;
JniGlobalReference mWrapperCallbackRef;
JniGlobalReference mJavaCallbackRef;
};

} // namespace Controller
Expand Down
14 changes: 5 additions & 9 deletions src/controller/java/AndroidControllerExceptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,14 @@ CHIP_ERROR AndroidControllerExceptions::CreateAndroidControllerException(JNIEnv
jthrowable & outEx)
{
jclass controllerExceptionCls;
CHIP_ERROR err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/ChipDeviceControllerException",
controllerExceptionCls);
CHIP_ERROR err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/ChipDeviceControllerException",
controllerExceptionCls);
VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_TYPE_NOT_FOUND);

JniObject controllerExceptionJniCls(env, static_cast<jobject>(controllerExceptionCls));

jmethodID exceptionConstructor = env->GetMethodID(controllerExceptionCls, "<init>", "(JLjava/lang/String;)V");
jobject localRef =
env->NewObject(controllerExceptionCls, exceptionConstructor, static_cast<jlong>(errorCode), env->NewStringUTF(message));
VerifyOrReturnError(localRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
outEx = (jthrowable) (env->NewGlobalRef(localRef));
VerifyOrReturnError(outEx != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
outEx = static_cast<jthrowable>(
env->NewObject(controllerExceptionCls, exceptionConstructor, static_cast<jlong>(errorCode), env->NewStringUTF(message)));
VerifyOrReturnError(outEx != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
return CHIP_NO_ERROR;
}

Expand Down
18 changes: 13 additions & 5 deletions src/lib/support/JniReferences.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,18 @@ JNIEnv * JniReferences::GetEnvForCurrentThread()

CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass & outCls)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jclass cls = nullptr;
CHIP_ERROR err = GetLocalClassRef(env, clsType, cls);
ReturnErrorOnFailure(err);
outCls = (jclass) env->NewGlobalRef((jobject) cls);
VerifyOrReturnError(outCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);

return err;
}

CHIP_ERROR JniReferences::GetLocalClassRef(JNIEnv * env, const char * clsType, jclass & outCls)
{
jclass cls = nullptr;

// Try `j$/util/Optional` when enabling Java8.
if (strcmp(clsType, "java/util/Optional") == 0)
Expand All @@ -100,10 +110,8 @@ CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass
VerifyOrReturnError(cls != nullptr && env->ExceptionCheck() != JNI_TRUE, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
}

outCls = (jclass) env->NewGlobalRef((jobject) cls);
VerifyOrReturnError(outCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);

return err;
outCls = cls;
return CHIP_NO_ERROR;
}

CHIP_ERROR JniReferences::N2J_ByteArray(JNIEnv * env, const uint8_t * inArray, jsize inArrayLen, jbyteArray & outArray)
Expand Down
15 changes: 14 additions & 1 deletion src/lib/support/JniReferences.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class JniReferences

/**
* @brief
* Creates a jclass reference to the given class type.
* Creates a global jclass reference to the given class type.
*
* This must be called after SetJavaVm().
*
Expand All @@ -67,6 +67,19 @@ class JniReferences
* @param[out] outCls A Java reference to the class matching clsType.
*/
CHIP_ERROR GetClassRef(JNIEnv * env, const char * clsType, jclass & outCls);

/**
* @brief
* Creates a local jclass reference to the given class type.
*
* This must be called after SetJavaVm().
*
* @param[in] env The JNIEnv for finding a Java class and creating a new Java reference.
* @param[in] clsType The fully-qualified Java class name to find, e.g. java/lang/IllegalStateException.
* @param[out] outCls A Java reference to the class matching clsType.
*/
CHIP_ERROR GetLocalClassRef(JNIEnv * env, const char * clsType, jclass & outCls);

CHIP_ERROR FindMethod(JNIEnv * env, jobject object, const char * methodName, const char * methodSignature,
jmethodID * methodId);
void CallVoidInt(JNIEnv * env, jobject object, const char * methodName, jint argument);
Expand Down
36 changes: 29 additions & 7 deletions src/lib/support/JniTypeWrappers.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include <cstdint>
#include <jni.h>
#include <lib/support/CHIPJNIError.h>
#include <lib/support/JniReferences.h>
#include <lib/support/Span.h>
#include <string>
Expand Down Expand Up @@ -203,22 +204,43 @@ class JniLocalReferenceManager
bool mlocalFramePushed = false;
};

class JniObject
class JniGlobalReference
{
public:
JniObject(JNIEnv * aEnv, jobject aObjectRef) : mEnv(aEnv), mObjectRef(aObjectRef) {}
~JniObject()
JniGlobalReference() {}

CHIP_ERROR Init(jobject aObjectRef)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(aObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(mObjectRef == nullptr, CHIP_ERROR_INCORRECT_STATE);
mObjectRef = env->NewGlobalRef(aObjectRef);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
VerifyOrReturnError(mObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}

JniGlobalReference(JniGlobalReference && aOther)
{
if (mEnv != nullptr && mObjectRef != nullptr)
mObjectRef = aOther.mObjectRef;
aOther.mObjectRef = nullptr;
}

~JniGlobalReference()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env != nullptr && mObjectRef != nullptr)
{
mEnv->DeleteGlobalRef(mObjectRef);
env->DeleteGlobalRef(mObjectRef);
}
}

jobject objectRef() { return mObjectRef; }
jobject ObjectRef() { return mObjectRef; }

bool HasValidObjectRef() { return mObjectRef != nullptr; }

private:
JNIEnv * mEnv = nullptr;
jobject mObjectRef = nullptr;
};

Expand Down

0 comments on commit 85c7c31

Please sign in to comment.