#ifndef mozilla_jni_Natives_h__ #define mozilla_jni_Natives_h__ #include #include "mozilla/IndexSequence.h" #include "mozilla/Move.h" #include "mozilla/Tuple.h" #include "mozilla/TypeTraits.h" #include "mozilla/UniquePtr.h" #include "mozilla/WeakPtr.h" #include "mozilla/Unused.h" #include "mozilla/jni/Accessors.h" #include "mozilla/jni/Refs.h" #include "mozilla/jni/Types.h" #include "mozilla/jni/Utils.h" namespace mozilla { namespace jni { /** * C++ classes implementing instance (non-static) native methods can choose * from one of two ownership models, when associating a C++ object with a Java * instance. * * * If the C++ class inherits from mozilla::SupportsWeakPtr, weak pointers * will be used. The Java instance will store and own the pointer to a * WeakPtr object. The C++ class itself is otherwise not owned or directly * referenced. To attach a Java instance to a C++ instance, pass in a pointer * to the C++ class (i.e. MyClass*). * * class MyClass : public SupportsWeakPtr * , public MyJavaClass::Natives * { * // ... * * public: * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(MyClass) * using MyJavaClass::Natives::Dispose; * * void AttachTo(const MyJavaClass::LocalRef& instance) * { * MyJavaClass::Natives::AttachInstance(instance, this); * * // "instance" does NOT own "this", so the C++ object * // lifetime is separate from the Java object lifetime. * } * }; * * * If the C++ class doesn't inherit from mozilla::SupportsWeakPtr, the Java * instance will store and own a pointer to the C++ object itself. This * pointer must not be stored or deleted elsewhere. To attach a Java instance * to a C++ instance, pass in a reference to a UniquePtr of the C++ class * (i.e. UniquePtr). * * class MyClass : public MyJavaClass::Natives * { * // ... * * public: * using MyJavaClass::Natives::Dispose; * * static void AttachTo(const MyJavaClass::LocalRef& instance) * { * MyJavaClass::Natives::AttachInstance( * instance, mozilla::MakeUnique()); * * // "instance" owns the newly created C++ object, so the C++ * // object is destroyed as soon as instance.dispose() is called. * } * }; */ namespace detail { inline uintptr_t CheckNativeHandle(JNIEnv* env, uintptr_t handle) { if (!handle) { if (!env->ExceptionCheck()) { ThrowException(env, "java/lang/NullPointerException", "Null native pointer"); } return 0; } return handle; } template, Impl>::value /* = false */> struct NativePtr { static Impl* Get(JNIEnv* env, jobject instance) { return reinterpret_cast(CheckNativeHandle( env, GetNativeHandle(env, instance))); } template static Impl* Get(const LocalRef& instance) { return Get(instance.Env(), instance.Get()); } template static void Set(const LocalRef& instance, UniquePtr&& ptr) { Clear(instance); SetNativeHandle(instance.Env(), instance.Get(), reinterpret_cast(ptr.release())); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); } template static void Clear(const LocalRef& instance) { UniquePtr ptr(reinterpret_cast( GetNativeHandle(instance.Env(), instance.Get()))); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); if (ptr) { SetNativeHandle(instance.Env(), instance.Get(), 0); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); } } }; template struct NativePtr { static Impl* Get(JNIEnv* env, jobject instance) { const auto ptr = reinterpret_cast*>( CheckNativeHandle(env, GetNativeHandle(env, instance))); if (!ptr) { return nullptr; } Impl* const impl = *ptr; if (!impl) { ThrowException(env, "java/lang/NullPointerException", "Native object already released"); } return impl; } template static Impl* Get(const LocalRef& instance) { return Get(instance.Env(), instance.Get()); } template static void Set(const LocalRef& instance, Impl* ptr) { Clear(instance); SetNativeHandle(instance.Env(), instance.Get(), reinterpret_cast(new WeakPtr(ptr))); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); } template static void Clear(const LocalRef& instance) { const auto ptr = reinterpret_cast*>( GetNativeHandle(instance.Env(), instance.Get())); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); if (ptr) { SetNativeHandle(instance.Env(), instance.Get(), 0); MOZ_CATCH_JNI_EXCEPTION(instance.Env()); delete ptr; } } }; } // namespace detail using namespace detail; /** * For JNI native methods that are dispatched to a proxy, i.e. using * @WrapForJNI(dispatchTo = "proxy"), the implementing C++ class must provide a * OnNativeCall member. Subsequently, every native call is automatically * wrapped in a functor object, and the object is passed to OnNativeCall. The * OnNativeCall implementation can choose to invoke the call, save it, dispatch * it to a different thread, etc. Each copy of functor may only be invoked * once. * * class MyClass : public MyJavaClass::Natives * { * // ... * * template * class ProxyRunnable final : public Runnable * { * Functor mCall; * public: * ProxyRunnable(Functor&& call) : mCall(mozilla::Move(call)) {} * virtual void run() override { mCall(); } * }; * * public: * template * static void OnNativeCall(Functor&& call) * { * RunOnAnotherThread(new ProxyRunnable(mozilla::Move(call))); * } * }; */ namespace detail { // ProxyArg is used to handle JNI ref arguments for proxies. Because a proxied // call may happen outside of the original JNI native call, we must save all // JNI ref arguments as global refs to avoid the arguments going out of scope. template struct ProxyArg { static_assert(mozilla::IsPod::value, "T must be primitive type"); // Primitive types can be saved by value. typedef T Type; typedef typename TypeAdapter::JNIType JNIType; static void Clear(JNIEnv* env, Type&) {} static Type From(JNIEnv* env, JNIType val) { return TypeAdapter::ToNative(env, val); } }; template struct ProxyArg> { // Ref types need to be saved by global ref. typedef typename C::GlobalRef Type; typedef typename TypeAdapter>::JNIType JNIType; static void Clear(JNIEnv* env, Type& ref) { ref.Clear(env); } static Type From(JNIEnv* env, JNIType val) { return Type(env, C::Ref::From(val)); } }; template struct ProxyArg : ProxyArg {}; template<> struct ProxyArg : ProxyArg {}; template struct ProxyArg> : ProxyArg {}; // ProxyNativeCall implements the functor object that is passed to OnNativeCall template class ProxyNativeCall : public AbstractCall { // "this arg" refers to the Class::LocalRef (for static methods) or // Owner::LocalRef (for instance methods) that we optionally (as indicated // by HasThisArg) pass into the destination C++ function. typedef typename mozilla::Conditional::Type ThisArgClass; typedef typename mozilla::Conditional::Type ThisArgJNIType; // Type signature of the destination C++ function, which matches the // Method template parameter in NativeStubImpl::Wrap. typedef typename mozilla::Conditional::Type, typename mozilla::Conditional::Type>::Type NativeCallType; // Destination C++ function. NativeCallType mNativeCall; // Saved this arg. typename ThisArgClass::GlobalRef mThisArg; // Saved arguments. mozilla::Tuple::Type...> mArgs; // We cannot use IsStatic and HasThisArg directly (without going through // extra hoops) because GCC complains about invalid overloads, so we use // another pair of template parameters, Static and ThisArg. template typename mozilla::EnableIf::Type Call(const Class::LocalRef& cls, mozilla::IndexSequence) const { (*mNativeCall)(cls, mozilla::Get(mArgs)...); } template typename mozilla::EnableIf::Type Call(const Class::LocalRef& cls, mozilla::IndexSequence) const { (*mNativeCall)(mozilla::Get(mArgs)...); } template typename mozilla::EnableIf::Type Call(const typename Owner::LocalRef& inst, mozilla::IndexSequence) const { Impl* const impl = NativePtr::Get(inst); MOZ_CATCH_JNI_EXCEPTION(inst.Env()); (impl->*mNativeCall)(inst, mozilla::Get(mArgs)...); } template typename mozilla::EnableIf::Type Call(const typename Owner::LocalRef& inst, mozilla::IndexSequence) const { Impl* const impl = NativePtr::Get(inst); MOZ_CATCH_JNI_EXCEPTION(inst.Env()); (impl->*mNativeCall)(mozilla::Get(mArgs)...); } template void Clear(JNIEnv* env, mozilla::IndexSequence) { int dummy[] = { (ProxyArg::Clear(env, Get(mArgs)), 0)... }; mozilla::Unused << dummy; } public: // The class that implements the call target. typedef Impl TargetClass; typedef typename ThisArgClass::Param ThisArgType; static const bool isStatic = IsStatic; ProxyNativeCall(ThisArgJNIType thisArg, NativeCallType nativeCall, JNIEnv* env, typename ProxyArg::JNIType... args) : mNativeCall(nativeCall) , mThisArg(env, ThisArgClass::Ref::From(thisArg)) , mArgs(ProxyArg::From(env, args)...) {} ProxyNativeCall(ProxyNativeCall&&) = default; ProxyNativeCall(const ProxyNativeCall&) = default; // Get class ref for static calls or object ref for instance calls. typename ThisArgClass::Param GetThisArg() const { return mThisArg; } // Return if target is the given function pointer / pointer-to-member. // Because we can only compare pointers of the same type, we use a // templated overload that is chosen only if given a different type of // pointer than our target pointer type. bool IsTarget(NativeCallType call) const { return call == mNativeCall; } template bool IsTarget(T&&) const { return false; } // Redirect the call to another function / class member with the same // signature as the original target. Crash if given a wrong signature. void SetTarget(NativeCallType call) { mNativeCall = call; } template void SetTarget(T&&) const { MOZ_CRASH(); } void operator()() override { JNIEnv* const env = GetEnvForThread(); typename ThisArgClass::LocalRef thisArg(env, mThisArg); Call( thisArg, typename IndexSequenceFor::Type()); // Clear all saved global refs. We do this after the call is invoked, // and not inside the destructor because we already have a JNIEnv here, // so it's more efficient to clear out the saved args here. The // downside is that the call can only be invoked once. Clear(env, typename IndexSequenceFor::Type()); mThisArg.Clear(env); } }; template struct Dispatcher { template static typename EnableIf< Traits::dispatchTarget == DispatchTarget::PROXY, void>::Type Run(ProxyArgs&&... args) { Impl::OnNativeCall(ProxyNativeCall< Impl, typename Traits::Owner, IsStatic, HasThisArg, Args...>(Forward(args)...)); } template static typename EnableIf< Traits::dispatchTarget == DispatchTarget::GECKO, void>::Type Run(ThisArg thisArg, ProxyArgs&&... args) { // For a static method, do not forward the "this arg" (i.e. the class // local ref) if the implementation does not request it. This saves us // a pair of calls to add/delete global ref. DispatchToGeckoThread(MakeUnique>(HasThisArg || !IsStatic ? thisArg : nullptr, Forward(args)...)); } template static typename EnableIf< Traits::dispatchTarget == DispatchTarget::CURRENT, void>::Type Run(ProxyArgs&&... args) {} }; } // namespace detail // Wrapper methods that convert arguments from the JNI types to the native // types, e.g. from jobject to jni::Object::Ref. For instance methods, the // wrapper methods also convert calls to calls on objects. // // We need specialization for static/non-static because the two have different // signatures (jobject vs jclass and Impl::*Method vs *Method). // We need specialization for return type, because void return type requires // us to not deal with the return value. // Bug 1207642 - Work around Dalvik bug by realigning stack on JNI entry #ifdef __i386__ #define MOZ_JNICALL JNICALL __attribute__((force_align_arg_pointer)) #else #define MOZ_JNICALL JNICALL #endif template class NativeStub; template class NativeStub> { using Owner = typename Traits::Owner; using ReturnType = typename Traits::ReturnType; static constexpr bool isStatic = Traits::isStatic; static constexpr bool isVoid = mozilla::IsVoid::value; struct VoidType { using JNIType = void; }; using ReturnJNIType = typename Conditional< isVoid, VoidType, TypeAdapter>::Type::JNIType; using ReturnTypeForNonVoidInstance = typename Conditional< !isStatic && !isVoid, ReturnType, VoidType>::Type; using ReturnTypeForVoidInstance = typename Conditional< !isStatic && isVoid, ReturnType, VoidType&>::Type; using ReturnTypeForNonVoidStatic = typename Conditional< isStatic && !isVoid, ReturnType, VoidType>::Type; using ReturnTypeForVoidStatic = typename Conditional< isStatic && isVoid, ReturnType, VoidType&>::Type; static_assert(Traits::dispatchTarget == DispatchTarget::CURRENT || isVoid, "Dispatched calls must have void return type"); public: // Non-void instance method template static MOZ_JNICALL ReturnJNIType Wrap(JNIEnv* env, jobject instance, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); Impl* const impl = NativePtr::Get(env, instance); if (!impl) { // There is a pending JNI exception at this point. return ReturnJNIType(); } return TypeAdapter::FromNative(env, (impl->*Method)(TypeAdapter::ToNative(env, args)...)); } // Non-void instance method with instance reference template static MOZ_JNICALL ReturnJNIType Wrap(JNIEnv* env, jobject instance, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); Impl* const impl = NativePtr::Get(env, instance); if (!impl) { // There is a pending JNI exception at this point. return ReturnJNIType(); } auto self = Owner::LocalRef::Adopt(env, instance); const auto res = TypeAdapter::FromNative(env, (impl->*Method)(self, TypeAdapter::ToNative(env, args)...)); self.Forget(); return res; } // Void instance method template static MOZ_JNICALL void Wrap(JNIEnv* env, jobject instance, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); if (Traits::dispatchTarget != DispatchTarget::CURRENT) { Dispatcher:: template Run(instance, Method, env, args...); return; } Impl* const impl = NativePtr::Get(env, instance); if (!impl) { // There is a pending JNI exception at this point. return; } (impl->*Method)(TypeAdapter::ToNative(env, args)...); } // Void instance method with instance reference template static MOZ_JNICALL void Wrap(JNIEnv* env, jobject instance, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); if (Traits::dispatchTarget != DispatchTarget::CURRENT) { Dispatcher:: template Run(instance, Method, env, args...); return; } Impl* const impl = NativePtr::Get(env, instance); if (!impl) { // There is a pending JNI exception at this point. return; } auto self = Owner::LocalRef::Adopt(env, instance); (impl->*Method)(self, TypeAdapter::ToNative(env, args)...); self.Forget(); } // Overload for DisposeNative template static MOZ_JNICALL void Wrap(JNIEnv* env, jobject instance) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); if (Traits::dispatchTarget != DispatchTarget::CURRENT) { using LocalRef = typename Owner::LocalRef; Dispatcher:: template Run( /* ThisArg */ nullptr, DisposeNative, env, instance); return; } auto self = Owner::LocalRef::Adopt(env, instance); (Impl::DisposeNative)(self); self.Forget(); } // Non-void static method template static MOZ_JNICALL ReturnJNIType Wrap(JNIEnv* env, jclass, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); return TypeAdapter::FromNative(env, (*Method)(TypeAdapter::ToNative(env, args)...)); } // Non-void static method with class reference template static MOZ_JNICALL ReturnJNIType Wrap(JNIEnv* env, jclass cls, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); auto clazz = Class::LocalRef::Adopt(env, cls); const auto res = TypeAdapter::FromNative(env, (*Method)(clazz, TypeAdapter::ToNative(env, args)...)); clazz.Forget(); return res; } // Void static method template static MOZ_JNICALL void Wrap(JNIEnv* env, jclass cls, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); if (Traits::dispatchTarget != DispatchTarget::CURRENT) { Dispatcher:: template Run(cls, Method, env, args...); return; } (*Method)(TypeAdapter::ToNative(env, args)...); } // Void static method with class reference template static MOZ_JNICALL void Wrap(JNIEnv* env, jclass cls, typename TypeAdapter::JNIType... args) { MOZ_ASSERT_JNI_THREAD(Traits::callingThread); if (Traits::dispatchTarget != DispatchTarget::CURRENT) { Dispatcher:: template Run(cls, Method, env, args...); return; } auto clazz = Class::LocalRef::Adopt(env, cls); (*Method)(clazz, TypeAdapter::ToNative(env, args)...); clazz.Forget(); } }; // Generate a JNINativeMethod from a native // method's traits class and a wrapped stub. template constexpr JNINativeMethod MakeNativeMethod(MOZ_JNICALL Ret (*stub)(JNIEnv*, Args...)) { return { Traits::name, Traits::signature, reinterpret_cast(stub) }; } // Class inherited by implementing class. template class NativeImpl { typedef typename Cls::template Natives Natives; static bool sInited; public: static void Init() { if (sInited) { return; } const auto& ctx = typename Cls::Context(); ctx.Env()->RegisterNatives( ctx.ClassRef(), Natives::methods, sizeof(Natives::methods) / sizeof(Natives::methods[0])); MOZ_CATCH_JNI_EXCEPTION(ctx.Env()); sInited = true; } protected: // Associate a C++ instance with a Java instance. static void AttachNative(const typename Cls::LocalRef& instance, SupportsWeakPtr* ptr) { static_assert(mozilla::IsBaseOf, Impl>::value, "Attach with UniquePtr&& when not using WeakPtr"); return NativePtr::Set(instance, static_cast(ptr)); } static void AttachNative(const typename Cls::LocalRef& instance, UniquePtr&& ptr) { static_assert(!mozilla::IsBaseOf, Impl>::value, "Attach with SupportsWeakPtr* when using WeakPtr"); return NativePtr::Set(instance, mozilla::Move(ptr)); } // Get the C++ instance associated with a Java instance. // There is always a pending exception if the return value is nullptr. static Impl* GetNative(const typename Cls::LocalRef& instance) { return NativePtr::Get(instance); } static void DisposeNative(const typename Cls::LocalRef& instance) { NativePtr::Clear(instance); } NativeImpl() { // Initialize on creation if not already initialized. Init(); } }; // Define static member. template bool NativeImpl::sInited; } // namespace jni } // namespace mozilla #endif // mozilla_jni_Natives_h__