| 1 | /***************************************************************************** |
| 2 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | you may not use this file except in compliance with the License. |
| 4 | You may obtain a copy of the License at |
| 5 | |
| 6 | http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | |
| 8 | Unless required by applicable law or agreed to in writing, software |
| 9 | distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | See the License for the specific language governing permissions and |
| 12 | limitations under the License. |
| 13 | |
| 14 | See NOTICE file for details. |
| 15 | *****************************************************************************/ |
| 16 | #include "jpype.h" |
| 17 | #include "pyjp.h" |
| 18 | #include "jp_proxy.h" |
| 19 | #include "jp_classloader.h" |
| 20 | #include "jp_reference_queue.h" |
| 21 | #include "jp_primitive_accessor.h" |
| 22 | #include "jp_boxedtype.h" |
| 23 | #include "jp_functional.h" |
| 24 | |
| 25 | JPPyObject getArgs(jlongArray parameterTypePtrs, |
| 26 | jobjectArray args, PyObject* self, int addSelf) |
| 27 | { |
| 28 | JP_TRACE_IN("JProxy::getArgs"); |
| 29 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 30 | jsize argLen = frame.GetArrayLength(parameterTypePtrs); |
| 31 | jsize extra = addSelf?1:0; |
| 32 | JPPyObject pyargs = JPPyObject::call(PyTuple_New(argLen+extra)); |
| 33 | JPPrimitiveArrayAccessor<jlongArray, jlong*> accessor(frame, parameterTypePtrs, |
| 34 | &JPJavaFrame::GetLongArrayElements, &JPJavaFrame::ReleaseLongArrayElements); |
| 35 | |
| 36 | if (addSelf) |
| 37 | { |
| 38 | Py_IncRef(self); |
| 39 | PyTuple_SetItem(pyargs.get(), 0, self); |
| 40 | } |
| 41 | jlong* types = accessor.get(); |
| 42 | for (jsize i = 0; i < argLen; i++) |
| 43 | { |
| 44 | jobject obj = frame.GetObjectArrayElement(args, i); |
| 45 | JPClass* type = frame.findClassForObject(obj); |
| 46 | if (type == nullptr) |
| 47 | type = reinterpret_cast<JPClass*> (types[i]); |
| 48 | JPValue val = type->getValueFromObject(frame, JPValue(type, obj)); |
| 49 | PyTuple_SetItem(pyargs.get(), i+extra, type->convertToPythonObject(frame, val, false).keep()); |
| 50 | } |
| 51 | return pyargs; |
| 52 | JP_TRACE_OUT; |
| 53 | } |
| 54 | |
| 55 | extern "C" JNIEXPORT jobject JNICALL Java_org_jpype_proxy_JPypeProxy_hostInvoke( |
| 56 | JNIEnv *env, jclass clazz, |
| 57 | jlong contextPtr, jstring name, |
| 58 | jlong hostObj, |
| 59 | jlong returnTypePtr, |
| 60 | jlongArray parameterTypePtrs, |
| 61 | jobjectArray args, |
| 62 | jobject missing) |
| 63 | { |
| 64 | JPJavaFrame frame = JPJavaFrame::external(env); |
| 65 | |
| 66 | // We need the resources to be held for the full duration of the proxy. |
| 67 | JPPyCallAcquire callback; |
| 68 | try |
| 69 | { |
| 70 | JP_TRACE_IN("JPype_InvocationHandler_hostInvoke"); |
| 71 | JP_TRACE("hostObj", (void*) hostObj); |
| 72 | try |
| 73 | { |
| 74 | // GCOVR_EXCL_START |
| 75 | // Sanity check, should never be hit |
| 76 | if (hostObj == 0) |
| 77 | { |
| 78 | env->functions->ThrowNew(env, JPContext_global->m_RuntimeException.get(), |
| 79 | "host reference is null"); |
| 80 | return nullptr; |
| 81 | } |
| 82 | // GCOVR_EXCL_STOP |
| 83 | |
| 84 | string cname = frame.toStringUTF8(name); |
| 85 | JP_TRACE("Get callable for", cname); |
| 86 | |
| 87 | // Get the callable object |
| 88 | int addSelf = 0; |
| 89 | JPProxy* proxy = (JPProxy*) hostObj; |
| 90 | JPPyObject callable(proxy->getCallable(cname, addSelf)); |
| 91 | |
| 92 | // If method can't be called, throw an exception |
| 93 | if (callable.isNull() || callable.get() == Py_None) |
| 94 | return missing; |
| 95 | |
| 96 | // Find the return type |
| 97 | auto* returnClass = (JPClass*) returnTypePtr; |
| 98 | JP_TRACE("Get return type", returnClass->getCanonicalName()); |
| 99 | |
| 100 | // convert the arguments into a python list |
| 101 | JP_TRACE("Convert arguments"); |
| 102 | JPPyObject pyargs = getArgs(parameterTypePtrs, args, proxy->m_Instance->m_Target, addSelf); |
| 103 | |
| 104 | JP_TRACE("Call Python"); |
| 105 | JPPyObject returnValue = JPPyObject::call(PyObject_Call(callable.get(), pyargs.get(), nullptr)); |
| 106 | |
| 107 | JP_TRACE("Handle return", Py_TYPE(returnValue.get())->tp_name); |
| 108 | if (returnClass == JPContext_global->_void) |
| 109 | { |
| 110 | JP_TRACE("Void return"); |
| 111 | return nullptr; |
| 112 | } |
| 113 | |
| 114 | // This is a SystemError where the caller return null without |
| 115 | // setting a Python error. |
| 116 | if (returnValue.isNull()) |
| 117 | { |
| 118 | JP_TRACE("Null return"); |
| 119 | JP_RAISE(PyExc_TypeError, "Return value is null when it cannot be"); |
| 120 | } |
| 121 | |
| 122 | // We must box here. |
| 123 | JPMatch returnMatch(&frame, returnValue.get()); |
| 124 | if (returnClass->isPrimitive()) |
| 125 | { |
| 126 | JP_TRACE("Box return"); |
| 127 | if (returnClass->findJavaConversion(returnMatch) == JPMatch::_none) |
| 128 | JP_RAISE(PyExc_TypeError, "Return value is not compatible with required type."); |
| 129 | jvalue res = returnMatch.convert(); |
| 130 | auto *boxed = dynamic_cast<JPBoxedType *>( (dynamic_cast<JPPrimitiveType*>( returnClass))->getBoxedClass(frame)); |
| 131 | jvalue res2; |
| 132 | res2.l = boxed->box(frame, res); |
| 133 | return frame.keep(res2.l); |
| 134 | } |
| 135 | |
| 136 | if (returnClass->findJavaConversion(returnMatch) == JPMatch::_none) |
| 137 | { |
| 138 | JP_TRACE("Cannot convert"); |
| 139 | JP_RAISE(PyExc_TypeError, "Return value is not compatible with required type."); |
| 140 | } |
| 141 | |
| 142 | JP_TRACE("Convert return to", returnClass->getCanonicalName()); |
| 143 | jvalue res = returnMatch.convert(); |
| 144 | return frame.keep(res.l); |
| 145 | } catch (JPypeException& ex) |
| 146 | { |
| 147 | JP_TRACE("JPypeException raised"); |
| 148 | ex.toJava(); |
| 149 | } catch (...) // GCOVR_EXCL_LINE |
| 150 | { |
| 151 | JP_TRACE("Other Exception raised"); |
| 152 | env->functions->ThrowNew(env, JPContext_global->m_RuntimeException.get(), |
| 153 | "unknown error occurred"); |
| 154 | } |
| 155 | return nullptr; |
| 156 | JP_TRACE_OUT; // GCOVR_EXCL_LINE |
| 157 | } |
| 158 | catch (...) // JP_TRACE_OUT implies a throw but that is not allowed. |
| 159 | {} |
| 160 | return NULL; |
| 161 | } |
| 162 | |
| 163 | JPProxy::JPProxy(PyJPProxy* inst, JPClassList& intf) |
| 164 | : m_Instance(inst), m_InterfaceClasses(intf) |
| 165 | { |
| 166 | JP_TRACE_IN("JPProxy::JPProxy"); |
| 167 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 168 | |
| 169 | // Convert the interfaces to a Class[] |
| 170 | jobjectArray ar = frame.NewObjectArray((int) intf.size(), |
| 171 | JPContext_global->_java_lang_Class->getJavaClass(), nullptr); |
| 172 | for (unsigned int i = 0; i < intf.size(); i++) |
| 173 | { |
| 174 | frame.SetObjectArrayElement(ar, i, intf[i]->getJavaClass()); |
| 175 | } |
| 176 | jvalue v[4]; |
| 177 | v[0].l = JPContext_global->getJavaContext(); |
| 178 | v[1].j = (jlong) this; |
| 179 | v[2].j = (jlong) & JPProxy::releaseProxyPython; |
| 180 | v[3].l = ar; |
| 181 | |
| 182 | // Create the proxy |
| 183 | jobject proxy = frame.CallStaticObjectMethodA(JPContext_global->m_ProxyClass.get(), |
| 184 | JPContext_global->m_Proxy_NewID, v); |
| 185 | m_Proxy = JPObjectRef(proxy); |
| 186 | m_Ref = nullptr; |
| 187 | JP_TRACE_OUT; |
| 188 | } |
| 189 | |
| 190 | JPProxy::~JPProxy() |
| 191 | { |
| 192 | try |
| 193 | { |
| 194 | if (m_Ref != nullptr && JPContext_global->isRunning()) |
| 195 | { |
| 196 | JPContext_global->getEnv()->DeleteWeakGlobalRef(m_Ref); |
| 197 | } |
| 198 | } catch (JPypeException &ex) // GCOVR_EXCL_LINE |
| 199 | { |
| 200 | // Cannot throw |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | void JPProxy::releaseProxyPython(void* host) |
| 205 | { |
| 206 | Py_XDECREF(((JPProxy*) host)->m_Instance); |
| 207 | } |
| 208 | |
| 209 | jvalue JPProxy::getProxy() |
| 210 | { |
| 211 | JP_TRACE_IN("JPProxy::getProxy"); |
| 212 | JPJavaFrame frame = JPJavaFrame::inner(); |
| 213 | |
| 214 | jobject instance = nullptr; |
| 215 | if (m_Ref != nullptr) |
| 216 | { |
| 217 | instance = frame.NewLocalRef(m_Ref); |
| 218 | } |
| 219 | |
| 220 | if (instance == nullptr) |
| 221 | { |
| 222 | // Use the proxy to make an instance |
| 223 | JP_TRACE("Create handler"); |
| 224 | Py_INCREF(m_Instance); |
| 225 | instance = frame.CallObjectMethodA(m_Proxy.get(), |
| 226 | JPContext_global->m_Proxy_NewInstanceID, nullptr); |
| 227 | m_Ref = frame.NewWeakGlobalRef(instance); |
| 228 | } |
| 229 | jvalue out; |
| 230 | out.l = frame.keep(instance); |
| 231 | return out; |
| 232 | JP_TRACE_OUT; |
| 233 | } |
| 234 | |
| 235 | JPProxyType::JPProxyType(JPJavaFrame& frame, |
| 236 | jclass clss, |
| 237 | const string& name, |
| 238 | JPClass* super, |
| 239 | JPClassList& interfaces, |
| 240 | jint modifiers) |
| 241 | : JPClass(frame, clss, name, super, interfaces, modifiers) |
| 242 | { |
| 243 | jclass proxyClass = frame.FindClass("java/lang/reflect/Proxy"); |
| 244 | m_ProxyClass = JPClassRef(frame, proxyClass); |
| 245 | m_GetInvocationHandlerID = frame.GetStaticMethodID(proxyClass, "getInvocationHandler", |
| 246 | "(Ljava/lang/Object;)Ljava/lang/reflect/InvocationHandler;"); |
| 247 | m_InstanceID = frame.GetFieldID(clss, "instance", "J"); |
| 248 | } |
| 249 | |
| 250 | JPProxyType::~JPProxyType() |
| 251 | = default; |
| 252 | |
| 253 | JPPyObject JPProxyType::convertToPythonObject(JPJavaFrame& frame, jvalue val, bool cast) |
| 254 | { |
| 255 | JP_TRACE_IN("JPProxyType::convertToPythonObject"); |
| 256 | jobject ih = frame.CallStaticObjectMethodA(m_ProxyClass.get(), |
| 257 | m_GetInvocationHandlerID, &val); |
| 258 | |
| 259 | JPProxy *proxy = (JPProxy*) frame.GetLongField(ih, m_InstanceID); |
| 260 | PyJPProxy *pproxy = proxy->m_Instance; |
| 261 | |
| 262 | // Is it a native Python object |
| 263 | if (pproxy->m_Convert && pproxy->m_Target != Py_None) |
| 264 | return JPPyObject::use(pproxy->m_Target); |
| 265 | |
| 266 | // Is it a user extended class |
| 267 | if (pproxy->m_Dispatch == Py_None) |
| 268 | return JPPyObject::use((PyObject*) pproxy); |
| 269 | |
| 270 | // Return the Proxy itself |
| 271 | JP_TRACE("Target", pproxy); |
| 272 | return JPPyObject::use((PyObject*) pproxy); |
| 273 | JP_TRACE_OUT; // GCOVR_EXCL_LINE |
| 274 | } |
| 275 | |
| 276 | JPProxyDirect::JPProxyDirect(PyJPProxy* inst, JPClassList& intf) |
| 277 | : JPProxy(inst, intf) |
| 278 | { |
| 279 | } |
| 280 | |
| 281 | JPProxyDirect::~JPProxyDirect() |
| 282 | = default; |
| 283 | |
| 284 | JPPyObject JPProxyDirect::getCallable(const string& cname, int& addSelf) |
| 285 | { |
| 286 | return JPPyObject::accept(PyObject_GetAttrString((PyObject*) m_Instance, cname.c_str())); |
| 287 | } |
| 288 | |
| 289 | JPProxyIndirect::JPProxyIndirect(PyJPProxy* inst, JPClassList& intf) |
| 290 | : JPProxy(inst, intf) |
| 291 | { |
| 292 | } |
| 293 | |
| 294 | JPProxyIndirect::~JPProxyIndirect() |
| 295 | = default; |
| 296 | |
| 297 | JPPyObject JPProxyIndirect::getCallable(const string& cname, int& addSelf) |
| 298 | { |
| 299 | JPPyObject out = JPPyObject::accept(PyObject_GetAttrString(m_Instance->m_Dispatch, cname.c_str())); |
| 300 | if (!out.isNull()) |
| 301 | { |
| 302 | addSelf = (m_Instance->m_Dispatch != m_Instance->m_Target) && (m_Instance->m_Target != Py_None); |
| 303 | return out; |
| 304 | } |
| 305 | return JPPyObject::accept(PyObject_GetAttrString((PyObject*) m_Instance, cname.c_str())); |
| 306 | } |
| 307 | |
| 308 | JPProxyFunctional::JPProxyFunctional(PyJPProxy* inst, JPClassList& intf) |
| 309 | : JPProxy(inst, intf) |
| 310 | { |
| 311 | m_Functional = dynamic_cast<JPFunctional*>( intf[0]); |
| 312 | } |
| 313 | |
| 314 | JPProxyFunctional::~JPProxyFunctional() |
| 315 | = default; |
| 316 | |
| 317 | JPPyObject JPProxyFunctional::getCallable(const string& cname, int& addSelf) |
| 318 | { |
| 319 | if (cname == m_Functional->getMethod()) |
| 320 | return JPPyObject::accept(PyObject_GetAttrString(m_Instance->m_Dispatch, "__call__")); |
| 321 | return JPPyObject::accept(PyObject_GetAttrString((PyObject*) m_Instance, cname.c_str())); |
| 322 | } |