| 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_arrayclass.h" |
| 19 | #include "jp_primitive_accessor.h" |
| 20 | #include "jp_gc.h" |
| 21 | #include "jp_stringtype.h" |
| 22 | #include "jp_classloader.h" |
| 23 | #ifdef WIN32 |
| 24 | #include <Windows.h> |
| 25 | #endif |
| 26 | |
| 27 | void PyJPModule_installGC(PyObject* module); |
| 28 | |
| 29 | bool _jp_cpp_exceptions = false; |
| 30 | |
| 31 | extern void PyJPArray_initType(PyObject* module); |
| 32 | extern void PyJPBuffer_initType(PyObject* module); |
| 33 | extern void PyJPClass_initType(PyObject* module); |
| 34 | extern void PyJPField_initType(PyObject* module); |
| 35 | extern void PyJPMethod_initType(PyObject* module); |
| 36 | extern void PyJPMonitor_initType(PyObject* module); |
| 37 | extern void PyJPProxy_initType(PyObject* module); |
| 38 | extern void PyJPObject_initType(PyObject* module); |
| 39 | extern void PyJPNumber_initType(PyObject* module); |
| 40 | extern void PyJPClassHints_initType(PyObject* module); |
| 41 | extern void PyJPPackage_initType(PyObject* module); |
| 42 | extern void PyJPChar_initType(PyObject* module); |
| 43 | extern void PyJPValue_initType(PyObject* module); |
| 44 | |
| 45 | static PyObject *PyJPModule_convertBuffer(JPPyBuffer& buffer, PyObject *dtype); |
| 46 | |
| 47 | // To ensure no leaks (requires C++ linkage) |
| 48 | |
| 49 | class JPViewWrapper |
| 50 | { |
| 51 | public: |
| 52 | |
| 53 | JPViewWrapper() |
| 54 | { |
| 55 | view = new Py_buffer(); |
| 56 | } |
| 57 | |
| 58 | ~JPViewWrapper() |
| 59 | { |
| 60 | delete view; |
| 61 | } |
| 62 | Py_buffer *view; |
| 63 | } ; |
| 64 | |
| 65 | |
| 66 | PyObject* _JArray = nullptr; |
| 67 | PyObject* _JChar = nullptr; |
| 68 | PyObject* _JObject = nullptr; |
| 69 | PyObject* _JInterface = nullptr; |
| 70 | PyObject* _JException = nullptr; |
| 71 | PyObject* _JClassPre = nullptr; |
| 72 | PyObject* _JClassPost = nullptr; |
| 73 | PyObject* _JClassDoc = nullptr; |
| 74 | PyObject* _JMethodDoc = nullptr; |
| 75 | PyObject* _JMethodAnnotations = nullptr; |
| 76 | PyObject* _JMethodCode = nullptr; |
| 77 | PyObject* _JObjectKey = nullptr; |
| 78 | PyObject* _JVMNotRunning = nullptr; |
| 79 | |
| 80 | void PyJPModule_loadResources(PyObject* module) |
| 81 | { |
| 82 | // Note that if any resource is missing the user will get |
| 83 | // the message: |
| 84 | // |
| 85 | // AttributeError: module '_jpype' has no attribute 'SomeResource' |
| 86 | // The above exception was the direct cause of the following exception: |
| 87 | // |
| 88 | // Traceback (most recent call last): |
| 89 | // File ... |
| 90 | // RuntimeError: JPype resource is missing |
| 91 | try |
| 92 | { |
| 93 | // Complete the initialization here |
| 94 | _JObject = PyObject_GetAttrString(module, "JObject"); |
| 95 | JP_PY_CHECK(); |
| 96 | Py_INCREF(_JObject); |
| 97 | _JInterface = PyObject_GetAttrString(module, "JInterface"); |
| 98 | JP_PY_CHECK(); |
| 99 | Py_INCREF(_JInterface); |
| 100 | _JArray = PyObject_GetAttrString(module, "JArray"); |
| 101 | JP_PY_CHECK(); |
| 102 | Py_INCREF(_JArray); |
| 103 | _JChar = PyObject_GetAttrString(module, "JChar"); |
| 104 | JP_PY_CHECK(); |
| 105 | Py_INCREF(_JChar); |
| 106 | _JException = PyObject_GetAttrString(module, "JException"); |
| 107 | JP_PY_CHECK(); |
| 108 | Py_INCREF(_JException); |
| 109 | _JClassPre = PyObject_GetAttrString(module, "_jclassPre"); |
| 110 | JP_PY_CHECK(); |
| 111 | Py_INCREF(_JClassPre); |
| 112 | _JClassPost = PyObject_GetAttrString(module, "_jclassPost"); |
| 113 | JP_PY_CHECK(); |
| 114 | Py_INCREF(_JClassPost); |
| 115 | JP_PY_CHECK(); |
| 116 | _JClassDoc = PyObject_GetAttrString(module, "_jclassDoc"); |
| 117 | JP_PY_CHECK(); |
| 118 | Py_INCREF(_JClassDoc); |
| 119 | _JMethodDoc = PyObject_GetAttrString(module, "getMethodDoc"); |
| 120 | Py_INCREF(_JMethodDoc); |
| 121 | _JMethodAnnotations = PyObject_GetAttrString(module, "getMethodAnnotations"); |
| 122 | JP_PY_CHECK(); |
| 123 | Py_INCREF(_JMethodAnnotations); |
| 124 | _JMethodCode = PyObject_GetAttrString(module, "getMethodCode"); |
| 125 | JP_PY_CHECK(); |
| 126 | Py_INCREF(_JMethodCode); |
| 127 | |
| 128 | _JObjectKey = PyCapsule_New(module, "constructor key", nullptr); |
| 129 | |
| 130 | } catch (JPypeException&) // GCOVR_EXCL_LINE |
| 131 | { |
| 132 | // GCOVR_EXCL_START |
| 133 | PyJP_SetStringWithCause(PyExc_RuntimeError, "JPype resource is missing"); |
| 134 | JP_RAISE_PYTHON(); |
| 135 | // GCOVR_EXCL_STOP |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | #ifdef __cplusplus |
| 140 | extern "C" |
| 141 | { |
| 142 | #endif |
| 143 | |
| 144 | |
| 145 | // GCOVR_EXCL_START |
| 146 | // This is used exclusively during startup |
| 147 | |
| 148 | void PyJP_SetStringWithCause(PyObject *exception, |
| 149 | const char *str) |
| 150 | { |
| 151 | // See _PyErr_TrySetFromCause |
| 152 | PyObject *exc1, *val1, *tb1; |
| 153 | PyErr_Fetch(&exc1, &val1, &tb1); |
| 154 | PyErr_NormalizeException(&exc1, &val1, &tb1); |
| 155 | if (tb1 != nullptr) |
| 156 | { |
| 157 | PyException_SetTraceback(val1, tb1); |
| 158 | Py_DECREF(tb1); |
| 159 | } |
| 160 | Py_DECREF(exc1); |
| 161 | PyErr_SetString(exception, str); |
| 162 | PyObject *exc2, *val2, *tb2; |
| 163 | PyErr_Fetch(&exc2, &val2, &tb2); |
| 164 | PyErr_NormalizeException(&exc2, &val2, &tb2); |
| 165 | PyException_SetCause(val2, val1); |
| 166 | PyErr_Restore(exc2, val2, tb2); |
| 167 | } |
| 168 | // GCOVR_EXCL_STOP |
| 169 | |
| 170 | PyObject* PyJP_GetAttrDescriptor(PyTypeObject *type, PyObject *attr_name) |
| 171 | { |
| 172 | JP_PY_TRY("Py_GetAttrDescriptor"); |
| 173 | if (type->tp_mro == nullptr) |
| 174 | return nullptr; // GCOVR_EXCL_LINE |
| 175 | |
| 176 | // Grab the mro |
| 177 | PyObject *mro = type->tp_mro; |
| 178 | |
| 179 | // mro should be a tuple |
| 180 | Py_ssize_t n = PyTuple_Size(mro); |
| 181 | |
| 182 | // Search the tuple for the attribute |
| 183 | for (Py_ssize_t i = 0; i < n; ++i) |
| 184 | { |
| 185 | auto *type2 = (PyTypeObject*) PyTuple_GetItem(mro, i); |
| 186 | |
| 187 | // Skip objects without a functioning dictionary |
| 188 | if (type2->tp_dict == NULL) |
| 189 | continue; |
| 190 | |
| 191 | PyObject *res = PyDict_GetItem(type2->tp_dict, attr_name); |
| 192 | if (res) |
| 193 | { |
| 194 | Py_INCREF(res); |
| 195 | return res; |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // Last check is id in the parent |
| 200 | { |
| 201 | PyObject *res = PyDict_GetItem(Py_TYPE(type)->tp_dict, attr_name); |
| 202 | if (res) |
| 203 | { |
| 204 | Py_INCREF(res); |
| 205 | return res; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | return nullptr; |
| 210 | JP_PY_CATCH(nullptr); // GCOVR_EXCL_LINE |
| 211 | } |
| 212 | |
| 213 | int PyJP_IsSubClassSingle(PyTypeObject* type, PyTypeObject* obj) |
| 214 | { |
| 215 | if (type == nullptr || obj == nullptr) |
| 216 | return 0; // GCOVR_EXCL_LINE |
| 217 | PyObject* mro1 = obj->tp_mro; |
| 218 | Py_ssize_t n1 = PyTuple_Size(mro1); |
| 219 | Py_ssize_t n2 = PyTuple_Size(type->tp_mro); |
| 220 | if (n1 < n2) |
| 221 | return 0; |
| 222 | return PyTuple_GetItem(mro1, n1 - n2) == (PyObject*) type; |
| 223 | } |
| 224 | |
| 225 | int PyJP_IsInstanceSingle(PyObject* obj, PyTypeObject* type) |
| 226 | { |
| 227 | if (type == nullptr || obj == nullptr) |
| 228 | return 0; // GCOVR_EXCL_LINE |
| 229 | return PyJP_IsSubClassSingle(type, Py_TYPE(obj)); |
| 230 | } |
| 231 | |
| 232 | #ifndef ANDROID |
| 233 | extern JNIEnv *Android_JNI_GetEnv(); |
| 234 | |
| 235 | static string jarTmpPath; |
| 236 | static PyObject* PyJPModule_startup(PyObject* module, PyObject* pyargs) |
| 237 | { |
| 238 | JP_PY_TRY("PyJPModule_startup"); |
| 239 | |
| 240 | PyObject* vmOpt; |
| 241 | PyObject* vmPath; |
| 242 | char ignoreUnrecognized = true; |
| 243 | char convertStrings = false; |
| 244 | char interrupt = false; |
| 245 | PyObject* tmp; |
| 246 | |
| 247 | if (!PyArg_ParseTuple(pyargs, "OO!bbbO", &vmPath, &PyTuple_Type, &vmOpt, |
| 248 | &ignoreUnrecognized, &convertStrings, &interrupt, &tmp)) |
| 249 | return nullptr; |
| 250 | |
| 251 | if (tmp != Py_None) |
| 252 | { |
| 253 | if (!(JPPyString::check(tmp))) |
| 254 | { |
| 255 | PyErr_SetString(PyExc_TypeError, "Java jar path must be a string"); |
| 256 | return nullptr; |
| 257 | } |
| 258 | jarTmpPath = JPPyString::asStringUTF8(tmp); |
| 259 | } |
| 260 | |
| 261 | |
| 262 | if (!(JPPyString::check(vmPath))) |
| 263 | { |
| 264 | PyErr_SetString(PyExc_TypeError, "Java JVM path must be a string"); |
| 265 | return nullptr; |
| 266 | } |
| 267 | |
| 268 | string cVmPath = JPPyString::asStringUTF8(vmPath); |
| 269 | JP_TRACE("vmpath", cVmPath); |
| 270 | |
| 271 | StringVector args; |
| 272 | JPPySequence seq = JPPySequence::use(vmOpt); |
| 273 | |
| 274 | for (int i = 0; i < seq.size(); i++) |
| 275 | { |
| 276 | JPPyObject obj(seq[i]); |
| 277 | |
| 278 | if (JPPyString::check(obj.get())) |
| 279 | { |
| 280 | // TODO support unicode |
| 281 | string v = JPPyString::asStringUTF8(obj.get()); |
| 282 | JP_TRACE("arg", v); |
| 283 | args.emplace_back(v); |
| 284 | } else |
| 285 | { |
| 286 | PyErr_SetString(PyExc_TypeError, "VM Arguments must be strings"); |
| 287 | return nullptr; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // This section was moved down to make it easier to cover error cases |
| 292 | if (JPContext_global->isRunning()) |
| 293 | { |
| 294 | PyErr_SetString(PyExc_OSError, "JVM is already started"); |
| 295 | return nullptr; |
| 296 | } |
| 297 | |
| 298 | // install the gc hook |
| 299 | PyJPModule_installGC(module); |
| 300 | PyJPModule_loadResources(module); |
| 301 | JPContext_global->startJVM(cVmPath, args, ignoreUnrecognized != 0, convertStrings != 0, interrupt != 0); |
| 302 | |
| 303 | Py_RETURN_NONE; |
| 304 | JP_PY_CATCH(nullptr); |
| 305 | } |
| 306 | |
| 307 | static PyObject* PyJPModule_shutdown(PyObject* obj, PyObject* pyargs, PyObject* kwargs) |
| 308 | { |
| 309 | JP_PY_TRY("PyJPModule_shutdown"); |
| 310 | char destroyJVM = true; |
| 311 | char freeJVM = true; |
| 312 | |
| 313 | if (!PyArg_ParseTuple(pyargs, "bb", &destroyJVM, &freeJVM)) |
| 314 | return nullptr; |
| 315 | |
| 316 | JPContext_global->shutdownJVM(destroyJVM, freeJVM); |
| 317 | |
| 318 | #ifdef WIN32 |
| 319 | // Thus far this doesn't work on WINDOWS. The issue is a bug in the JVM |
| 320 | // is holding the file open and there is no apparent method to close it |
| 321 | // so that this can succeed |
| 322 | if (jarTmpPath != "") |
| 323 | remove(jarTmpPath.c_str()); |
| 324 | #else |
| 325 | if (jarTmpPath != "") |
| 326 | unlink(jarTmpPath.c_str()); |
| 327 | #endif |
| 328 | |
| 329 | Py_RETURN_NONE; |
| 330 | JP_PY_CATCH(nullptr); |
| 331 | } |
| 332 | #endif |
| 333 | |
| 334 | static PyObject* PyJPModule_isStarted(PyObject* obj) |
| 335 | { |
| 336 | return PyBool_FromLong(JPContext_global->isRunning()); |
| 337 | } |
| 338 | |
| 339 | #ifndef ANDROID |
| 340 | |
| 341 | static PyObject* PyJPModule_attachThread(PyObject* obj) |
| 342 | { |
| 343 | JP_PY_TRY("PyJPModule_attachThread"); |
| 344 | PyJPModule_getContext()->attachCurrentThread(); |
| 345 | Py_RETURN_NONE; |
| 346 | JP_PY_CATCH(nullptr); |
| 347 | } |
| 348 | |
| 349 | static PyObject* PyJPModule_attachThreadAsDaemon(PyObject* obj) |
| 350 | { |
| 351 | JP_PY_TRY("PyJPModule_attachThreadAsDaemon"); |
| 352 | PyJPModule_getContext()->attachCurrentThreadAsDaemon(); |
| 353 | Py_RETURN_NONE; |
| 354 | JP_PY_CATCH(nullptr); |
| 355 | } |
| 356 | |
| 357 | static PyObject* PyJPModule_detachThread(PyObject* obj) |
| 358 | { |
| 359 | JP_PY_TRY("PyJPModule_detachThread"); |
| 360 | if (JPContext_global->isRunning()) |
| 361 | JPContext_global->detachCurrentThread(); |
| 362 | Py_RETURN_NONE; |
| 363 | JP_PY_CATCH(nullptr); |
| 364 | } |
| 365 | #endif |
| 366 | |
| 367 | static PyObject* PyJPModule_isThreadAttached(PyObject* obj) |
| 368 | { |
| 369 | JP_PY_TRY("PyJPModule_isThreadAttached"); |
| 370 | if (!JPContext_global->isRunning()) |
| 371 | return PyBool_FromLong(0); // GCOVR_EXCL_LINE |
| 372 | return PyBool_FromLong(JPContext_global->isThreadAttached()); |
| 373 | JP_PY_CATCH(nullptr); |
| 374 | } |
| 375 | |
| 376 | // Cleanup hook for Py_buffer |
| 377 | |
| 378 | static void releaseView(void* view) |
| 379 | { |
| 380 | if (view != nullptr) |
| 381 | { |
| 382 | PyBuffer_Release((Py_buffer*) view); |
| 383 | delete (Py_buffer*) view; |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | static PyObject* PyJPModule_convertToDirectByteBuffer(PyObject* self, PyObject* args) |
| 388 | { |
| 389 | JP_PY_TRY("PyJPModule_convertToDirectByteBuffer"); |
| 390 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 391 | |
| 392 | PyObject *src; |
| 393 | int ro; |
| 394 | if (!PyArg_ParseTuple(args, "Op", &src, &ro)) |
| 395 | return nullptr; |
| 396 | |
| 397 | if (PyObject_CheckBuffer(src)) |
| 398 | { |
| 399 | JPViewWrapper vw; |
| 400 | if (PyObject_GetBuffer(src, vw.view, ro ? 0 : PyBUF_WRITABLE) == -1) |
| 401 | return nullptr; |
| 402 | |
| 403 | // Create a byte buffer |
| 404 | jvalue v; |
| 405 | v.l = frame.NewDirectByteBuffer(vw.view->buf, vw.view->len); |
| 406 | |
| 407 | if (vw.view->readonly) |
| 408 | v.l = frame.asReadOnlyBuffer(v.l); |
| 409 | |
| 410 | // Bind lifespan of the view to the java object. |
| 411 | frame.registerRef(v.l, vw.view, &releaseView); |
| 412 | vw.view = nullptr; |
| 413 | JPClass *type = frame.findClassForObject(v.l); |
| 414 | return type->convertToPythonObject(frame, v, false).keep(); |
| 415 | } |
| 416 | PyErr_SetString(PyExc_TypeError, "convertToDirectByteBuffer requires buffer support"); |
| 417 | JP_PY_CATCH(nullptr); |
| 418 | } |
| 419 | |
| 420 | static PyObject* PyJPModule_enableStacktraces(PyObject* self, PyObject* src) |
| 421 | { |
| 422 | _jp_cpp_exceptions = PyObject_IsTrue(src); |
| 423 | Py_RETURN_TRUE; |
| 424 | } |
| 425 | |
| 426 | PyObject *PyJPModule_newArrayType(PyObject *module, PyObject *args) |
| 427 | { |
| 428 | JP_PY_TRY("PyJPModule_newArrayType"); |
| 429 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 430 | |
| 431 | PyObject *type, *dims; |
| 432 | if (!PyArg_ParseTuple(args, "OO", &type, &dims)) |
| 433 | return nullptr; |
| 434 | if (!PyIndex_Check(dims)) |
| 435 | { |
| 436 | PyErr_SetString(PyExc_TypeError, "dims must be an integer"); |
| 437 | return nullptr; |
| 438 | } |
| 439 | long d = PyLong_AsLong(dims); |
| 440 | JPClass* cls = PyJPClass_getJPClass(type); |
| 441 | if (cls == nullptr) |
| 442 | { |
| 443 | PyErr_SetString(PyExc_TypeError, "Java class required"); |
| 444 | return nullptr; |
| 445 | } |
| 446 | |
| 447 | JPClass* arraycls = cls->newArrayType(frame, d); |
| 448 | return PyJPClass_create(frame, arraycls).keep(); |
| 449 | JP_PY_CATCH(nullptr); |
| 450 | } |
| 451 | |
| 452 | PyObject *PyJPModule_getClass(PyObject* module, PyObject *obj) |
| 453 | { |
| 454 | JP_PY_TRY("PyJPModule_getClass"); |
| 455 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 456 | JPContext *context = frame.getContext(); |
| 457 | |
| 458 | JPClass* cls; |
| 459 | if (JPPyString::check(obj)) |
| 460 | { |
| 461 | // String From Python |
| 462 | cls = frame.findClassByName(JPPyString::asStringUTF8(obj)); |
| 463 | if (cls == nullptr) |
| 464 | { |
| 465 | PyErr_SetString(PyExc_ValueError, "Unable to find Java class"); |
| 466 | return nullptr; |
| 467 | } |
| 468 | } else |
| 469 | { |
| 470 | // From an existing java.lang.Class object |
| 471 | JPValue *value = PyJPValue_getJavaSlot(obj); |
| 472 | if (value == nullptr || value->getClass() != context->_java_lang_Class) |
| 473 | { |
| 474 | PyErr_Format(PyExc_TypeError, "JClass requires str or java.lang.Class instance, not '%s'", Py_TYPE(obj)->tp_name); |
| 475 | return nullptr; |
| 476 | } |
| 477 | cls = frame.findClass((jclass) value->getValue().l); |
| 478 | if (cls == nullptr) |
| 479 | { |
| 480 | PyErr_SetString(PyExc_ValueError, "Unable to find class"); |
| 481 | return nullptr; |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | return PyJPClass_create(frame, cls).keep(); |
| 486 | JP_PY_CATCH(nullptr); |
| 487 | } |
| 488 | |
| 489 | PyObject *PyJPModule_hasClass(PyObject* module, PyObject *obj) |
| 490 | { |
| 491 | JP_PY_TRY("PyJPModule_hasClass"); |
| 492 | if (!JPContext_global->isRunning()) |
| 493 | Py_RETURN_FALSE; // GCOVR_EXCL_LINE |
| 494 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 495 | |
| 496 | JPClass* cls; |
| 497 | if (JPPyString::check(obj)) |
| 498 | { |
| 499 | // String From Python |
| 500 | cls = frame.findClassByName(JPPyString::asStringUTF8(obj)); |
| 501 | if (cls == nullptr) |
| 502 | { |
| 503 | PyErr_SetString(PyExc_ValueError, "Unable to find Java class"); |
| 504 | return nullptr; |
| 505 | } |
| 506 | } else |
| 507 | { |
| 508 | PyErr_Format(PyExc_TypeError, "str is required, not '%s'", Py_TYPE(obj)->tp_name); |
| 509 | return nullptr; |
| 510 | } |
| 511 | |
| 512 | auto *host = (PyObject*) cls->getHost(); |
| 513 | return PyBool_FromLong(host != nullptr); |
| 514 | JP_PY_CATCH(nullptr); |
| 515 | } |
| 516 | |
| 517 | static PyObject *PyJPModule_arrayFromBuffer(PyObject *module, PyObject *args, PyObject *kwargs) |
| 518 | { |
| 519 | JP_PY_TRY("PyJPModule_arrayFromBuffer"); |
| 520 | PyObject *source = nullptr; |
| 521 | PyObject *dtype = nullptr; |
| 522 | if (!PyArg_ParseTuple(args, "OO", &source, &dtype)) |
| 523 | return nullptr; |
| 524 | if (!PyObject_CheckBuffer(source)) |
| 525 | { |
| 526 | PyErr_Format(PyExc_TypeError, "'%s' does not support buffers", Py_TYPE(source)->tp_name); |
| 527 | return nullptr; |
| 528 | } |
| 529 | |
| 530 | // NUMPy does a series of probes looking for the best supported format, |
| 531 | // we will do the same. |
| 532 | { |
| 533 | JPPyBuffer buffer(source, PyBUF_FULL_RO); |
| 534 | if (buffer.valid()) |
| 535 | return PyJPModule_convertBuffer(buffer, dtype); |
| 536 | } |
| 537 | { |
| 538 | JPPyBuffer buffer(source, PyBUF_RECORDS_RO); |
| 539 | if (buffer.valid()) |
| 540 | return PyJPModule_convertBuffer(buffer, dtype); |
| 541 | } |
| 542 | { |
| 543 | JPPyBuffer buffer(source, PyBUF_ND | PyBUF_FORMAT); |
| 544 | if (buffer.valid()) |
| 545 | return PyJPModule_convertBuffer(buffer, dtype); |
| 546 | } |
| 547 | PyErr_Format(PyExc_TypeError, "buffer protocol for '%s' not supported", Py_TYPE(source)->tp_name); |
| 548 | return nullptr; |
| 549 | JP_PY_CATCH(nullptr); |
| 550 | } |
| 551 | |
| 552 | PyObject *PyJPModule_collect(PyObject* module, PyObject *obj) |
| 553 | { |
| 554 | JPContext* context = JPContext_global; |
| 555 | if (!context->isRunning()) |
| 556 | Py_RETURN_NONE; |
| 557 | PyObject *a1 = PyTuple_GetItem(obj, 0); |
| 558 | if (!PyUnicode_Check(a1)) |
| 559 | { |
| 560 | PyErr_SetString(PyExc_TypeError, "Bad callback argument"); |
| 561 | return nullptr; |
| 562 | } |
| 563 | if (PyUnicode_ReadChar(a1, 2) == 'a') |
| 564 | { |
| 565 | context->m_GC->onStart(); |
| 566 | } else |
| 567 | { |
| 568 | context->m_GC->onEnd(); |
| 569 | } |
| 570 | Py_RETURN_NONE; |
| 571 | } |
| 572 | |
| 573 | // GCOVR_EXCL_START |
| 574 | |
| 575 | PyObject *PyJPModule_gcStats(PyObject* module, PyObject *obj) |
| 576 | { |
| 577 | JPContext *context = PyJPModule_getContext(); |
| 578 | JPGCStats stats; |
| 579 | context->m_GC->getStats(stats); |
| 580 | PyObject *out = PyDict_New(); |
| 581 | PyObject *res; |
| 582 | PyDict_SetItemString(out, "current", res = PyLong_FromSsize_t((Py_ssize_t)(stats.current_rss))); |
| 583 | Py_DECREF(res); |
| 584 | PyDict_SetItemString(out, "java", res = PyLong_FromSsize_t((Py_ssize_t)(stats.java_rss))); |
| 585 | Py_DECREF(res); |
| 586 | PyDict_SetItemString(out, "python", res = PyLong_FromSsize_t((Py_ssize_t)(stats.python_rss))); |
| 587 | Py_DECREF(res); |
| 588 | PyDict_SetItemString(out, "max", res = PyLong_FromSsize_t((Py_ssize_t)(stats.max_rss))); |
| 589 | Py_DECREF(res); |
| 590 | PyDict_SetItemString(out, "min", res = PyLong_FromSsize_t((Py_ssize_t)(stats.min_rss))); |
| 591 | Py_DECREF(res); |
| 592 | PyDict_SetItemString(out, "triggered", res = PyLong_FromSsize_t((Py_ssize_t)(stats.python_triggered))); |
| 593 | Py_DECREF(res); |
| 594 | return out; |
| 595 | } |
| 596 | // GCOVR_EXCL_STOP |
| 597 | |
| 598 | static PyObject* PyJPModule_isPackage(PyObject *module, PyObject *pkg) |
| 599 | { |
| 600 | JP_PY_TRY("PyJPModule_isPackage"); |
| 601 | if (!PyUnicode_Check(pkg)) |
| 602 | { |
| 603 | PyErr_Format(PyExc_TypeError, "isPackage required unicode"); |
| 604 | return nullptr; |
| 605 | } |
| 606 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 607 | return PyBool_FromLong(frame.isPackage(JPPyString::asStringUTF8(pkg))); |
| 608 | JP_PY_CATCH(nullptr); // GCOVR_EXCL_LINE |
| 609 | } |
| 610 | |
| 611 | |
| 612 | #if 1 |
| 613 | // GCOVR_EXCL_START |
| 614 | // This code was used in testing the Java slot memory layout. It serves no purpose outside of debugging that issue. |
| 615 | PyObject* examine(PyObject *module, PyObject *other) |
| 616 | { |
| 617 | JP_PY_TRY("examine"); |
| 618 | int ret = 0; |
| 619 | PyTypeObject *type; |
| 620 | if (PyType_Check(other)) |
| 621 | type = (PyTypeObject*) other; |
| 622 | else |
| 623 | type = Py_TYPE(other); |
| 624 | |
| 625 | printf("======\n"); |
| 626 | int offset = 0; |
| 627 | if (!PyType_Check(other)) |
| 628 | { |
| 629 | offset = PyJPValue_getJavaSlotOffset(other); |
| 630 | printf(" Object:\n"); |
| 631 | printf(" size: %d\n", (int) Py_SIZE(other)); |
| 632 | printf(" dictoffset: %d\n", (int) ((long long) _PyObject_GetDictPtr(other)-(long long) other)); |
| 633 | printf(" javaoffset: %d\n", offset); |
| 634 | } |
| 635 | printf(" Type: %p\n", type); |
| 636 | printf(" name: %s\n", type->tp_name); |
| 637 | printf(" typename: %s\n", Py_TYPE(type)->tp_name); |
| 638 | printf(" gc: %d\n", (type->tp_flags & Py_TPFLAGS_HAVE_GC) == Py_TPFLAGS_HAVE_GC); |
| 639 | printf(" basicsize: %d\n", (int) type->tp_basicsize); |
| 640 | printf(" itemsize: %d\n", (int) type->tp_itemsize); |
| 641 | printf(" dictoffset: %d\n", (int) type->tp_dictoffset); |
| 642 | printf(" weaklistoffset: %d\n", (int) type->tp_weaklistoffset); |
| 643 | printf(" hasJavaSlot: %d\n", PyJPValue_hasJavaSlot(type)); |
| 644 | printf(" getattro: %p\n", type->tp_getattro); |
| 645 | printf(" setattro: %p\n", type->tp_setattro); |
| 646 | printf(" getattr: %p\n", type->tp_getattr); |
| 647 | printf(" setattr: %p\n", type->tp_setattr); |
| 648 | printf(" alloc: %p\n", type->tp_alloc); |
| 649 | printf(" free: %p\n", type->tp_free); |
| 650 | printf(" finalize: %p\n", type->tp_finalize); |
| 651 | long v = _PyObject_VAR_SIZE(type, 1)+(PyJPValue_hasJavaSlot(type)?sizeof (JPValue):0); |
| 652 | printf(" size?: %ld\n",v); |
| 653 | printf("======\n"); |
| 654 | |
| 655 | return PyBool_FromLong(ret); |
| 656 | JP_PY_CATCH(nullptr); |
| 657 | } |
| 658 | // GCOVR_EXCL_STOP |
| 659 | #endif |
| 660 | |
| 661 | // GCOVR_EXCL_START |
| 662 | int _PyJPModule_trace = 0; |
| 663 | |
| 664 | static PyObject* PyJPModule_trace(PyObject *module, PyObject *args) |
| 665 | { |
| 666 | bool old = _PyJPModule_trace; |
| 667 | _PyJPModule_trace = PyLong_AsLong(args); |
| 668 | return PyLong_FromLong(old); |
| 669 | } |
| 670 | // GCOVR_EXCL_STOP |
| 671 | |
| 672 | #ifdef JP_INSTRUMENTATION |
| 673 | uint32_t _PyJPModule_fault_code = -1; |
| 674 | |
| 675 | static PyObject* PyJPModule_fault(PyObject *module, PyObject *args) |
| 676 | { |
| 677 | if (args == Py_None) |
| 678 | { |
| 679 | _PyJPModule_fault_code = 0; |
| 680 | Py_RETURN_NONE; |
| 681 | } |
| 682 | string code = JPPyString::asStringUTF8(args); |
| 683 | uint32_t u = 0; |
| 684 | for (size_t i = 0; i < code.size(); ++i) |
| 685 | u = u * 0x1a481023 + code[i]; |
| 686 | _PyJPModule_fault_code = u; |
| 687 | return PyLong_FromLong(_PyJPModule_fault_code); |
| 688 | } |
| 689 | #endif |
| 690 | |
| 691 | #ifdef ANDROID |
| 692 | |
| 693 | static PyObject *PyJPModule_bootstrap(PyObject *module) |
| 694 | { |
| 695 | // After all the internals are created we can connect the API with the internal module |
| 696 | JNIEnv * env = Android_JNI_GetEnv(); |
| 697 | JPContext_global->attachJVM(env); |
| 698 | PyJPModule_installGC(module); |
| 699 | PyJPModule_loadResources(module); |
| 700 | Py_RETURN_NONE; |
| 701 | } |
| 702 | #endif |
| 703 | |
| 704 | static PyMethodDef moduleMethods[] = { |
| 705 | // Startup and initialization |
| 706 | {"isStarted", (PyCFunction) PyJPModule_isStarted, METH_NOARGS, ""}, |
| 707 | #ifdef ANDROID |
| 708 | {"bootstrap", (PyCFunction) PyJPModule_bootstrap, METH_NOARGS, ""}, |
| 709 | #else |
| 710 | {"startup", (PyCFunction) PyJPModule_startup, METH_VARARGS, ""}, |
| 711 | // {"attach", (PyCFunction) (&PyJPModule_attach), METH_VARARGS, ""}, |
| 712 | {"shutdown", (PyCFunction) PyJPModule_shutdown, METH_VARARGS, ""}, |
| 713 | #endif |
| 714 | {"_getClass", (PyCFunction) PyJPModule_getClass, METH_O, ""}, |
| 715 | {"_hasClass", (PyCFunction) PyJPModule_hasClass, METH_O, ""}, |
| 716 | {"_newArrayType", (PyCFunction) PyJPModule_newArrayType, METH_VARARGS, ""}, |
| 717 | {"_collect", (PyCFunction) PyJPModule_collect, METH_VARARGS, ""}, |
| 718 | {"gcStats", (PyCFunction) PyJPModule_gcStats, METH_NOARGS, ""}, |
| 719 | |
| 720 | // Threading |
| 721 | {"isThreadAttachedToJVM", (PyCFunction) PyJPModule_isThreadAttached, METH_NOARGS, ""}, |
| 722 | #ifndef ANDROID |
| 723 | {"attachThreadToJVM", (PyCFunction) PyJPModule_attachThread, METH_NOARGS, ""}, |
| 724 | {"detachThreadFromJVM", (PyCFunction) PyJPModule_detachThread, METH_NOARGS, ""}, |
| 725 | {"attachThreadAsDaemon", (PyCFunction) PyJPModule_attachThreadAsDaemon, METH_NOARGS, ""}, |
| 726 | #endif |
| 727 | |
| 728 | //{"dumpJVMStats", (PyCFunction) (&PyJPModule_dumpJVMStats), METH_NOARGS, ""}, |
| 729 | |
| 730 | {"convertToDirectBuffer", (PyCFunction) PyJPModule_convertToDirectByteBuffer, METH_VARARGS, ""}, |
| 731 | {"arrayFromBuffer", (PyCFunction) PyJPModule_arrayFromBuffer, METH_VARARGS, ""}, |
| 732 | {"enableStacktraces", (PyCFunction) PyJPModule_enableStacktraces, METH_O, ""}, |
| 733 | {"isPackage", (PyCFunction) PyJPModule_isPackage, METH_O, ""}, |
| 734 | {"trace", (PyCFunction) PyJPModule_trace, METH_O, ""}, |
| 735 | #ifdef JP_INSTRUMENTATION |
| 736 | {"fault", (PyCFunction) PyJPModule_fault, METH_O, ""}, |
| 737 | #endif |
| 738 | {"examine", (PyCFunction) examine, METH_O, ""}, |
| 739 | |
| 740 | // sentinel |
| 741 | {nullptr} |
| 742 | }; |
| 743 | |
| 744 | static struct PyModuleDef moduledef = { |
| 745 | PyModuleDef_HEAD_INIT, |
| 746 | "_jpype", |
| 747 | "jpype module", |
| 748 | -1, |
| 749 | moduleMethods, |
| 750 | }; |
| 751 | |
| 752 | PyObject *PyJPModule = nullptr; |
| 753 | JPContext* JPContext_global = nullptr; |
| 754 | |
| 755 | PyMODINIT_FUNC PyInit__jpype() |
| 756 | { |
| 757 | JP_PY_TRY("PyInit__jpype"); |
| 758 | JPContext_global = new JPContext(); |
| 759 | |
| 760 | // Initialize the module (depends on python version) |
| 761 | PyObject* module = PyModule_Create(&moduledef); |
| 762 | // PyJPModule = module; |
| 763 | Py_INCREF(module); |
| 764 | PyJPModule = module; |
| 765 | #ifdef Py_GIL_DISABLED |
| 766 | PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); |
| 767 | #endif |
| 768 | PyModule_AddStringConstant(module, "__version__", "1.6.0"); |
| 769 | |
| 770 | // Our module will be used for PyFrame object and it is a requirement that |
| 771 | // we have a builtins in our dictionary. |
| 772 | PyObject *builtins = PyEval_GetBuiltins(); |
| 773 | Py_INCREF(builtins); |
| 774 | PyModule_AddObject(module, "__builtins__", builtins); |
| 775 | |
| 776 | PyJPClassMagic = PyDict_New(); |
| 777 | // Initialize each of the python extension types |
| 778 | PyJPValue_initType(module); |
| 779 | PyJPClass_initType(module); |
| 780 | PyJPObject_initType(module); |
| 781 | |
| 782 | PyJPArray_initType(module); |
| 783 | PyJPBuffer_initType(module); |
| 784 | PyJPField_initType(module); |
| 785 | PyJPMethod_initType(module); |
| 786 | PyJPNumber_initType(module); |
| 787 | PyJPMonitor_initType(module); |
| 788 | PyJPProxy_initType(module); |
| 789 | PyJPClassHints_initType(module); |
| 790 | PyJPPackage_initType(module); |
| 791 | PyJPChar_initType(module); |
| 792 | |
| 793 | _PyJPModule_trace = true; |
| 794 | |
| 795 | return module; |
| 796 | JP_PY_CATCH(nullptr); // GCOVR_EXCL_LINE |
| 797 | } |
| 798 | |
| 799 | #ifdef __cplusplus |
| 800 | } |
| 801 | #endif |
| 802 | |
| 803 | void PyJPModule_rethrow(const JPStackInfo& info) |
| 804 | { |
| 805 | JP_TRACE_IN("PyJPModule_rethrow"); |
| 806 | JP_TRACE(info.getFile(), info.getLine()); |
| 807 | try |
| 808 | { |
| 809 | throw; |
| 810 | } catch (JPypeException& ex) |
| 811 | { |
| 812 | ex.from(info); // this likely wont be necessary, but for now we will add the entry point. |
| 813 | ex.toPython(); |
| 814 | return; |
| 815 | } catch (std::exception &ex) |
| 816 | { |
| 817 | PyErr_Format(PyExc_RuntimeError, "Unhandled C++ exception occurred: %s", ex.what()); |
| 818 | return; |
| 819 | } catch (...) |
| 820 | { |
| 821 | PyErr_Format(PyExc_RuntimeError, "Unhandled C++ exception occurred"); |
| 822 | return; |
| 823 | } |
| 824 | JP_TRACE_OUT; // GCOVR_EXCL_LINE |
| 825 | } |
| 826 | |
| 827 | static PyObject *PyJPModule_convertBuffer(JPPyBuffer& buffer, PyObject *dtype) |
| 828 | { |
| 829 | JPContext *context = PyJPModule_getContext(); |
| 830 | JPJavaFrame frame = JPJavaFrame::outer(); |
| 831 | Py_buffer& view = buffer.getView(); |
| 832 | |
| 833 | // Okay two possibilities here. We have a valid dtype specified, |
| 834 | // or we need to figure it out from the buffer. |
| 835 | JPClass *cls = nullptr; |
| 836 | |
| 837 | if (view.suboffsets != nullptr && view.suboffsets[view.ndim - 1] > 0) |
| 838 | { |
| 839 | PyErr_Format(PyExc_TypeError, "last dimension is not contiguous"); |
| 840 | return nullptr; |
| 841 | } |
| 842 | |
| 843 | // First lets find out what we are unpacking |
| 844 | Py_ssize_t itemsize = view.itemsize; |
| 845 | char *format = view.format; |
| 846 | if (format == nullptr) |
| 847 | format = "B"; |
| 848 | // Standard size for 'l' is 4 in docs, but numpy uses format 'l' for long long |
| 849 | if (itemsize == 8 && format[0] == 'l') |
| 850 | format = "q"; |
| 851 | if (itemsize == 8 && format[0] == 'L') |
| 852 | format = "Q"; |
| 853 | |
| 854 | if (dtype != nullptr && dtype != Py_None ) |
| 855 | { |
| 856 | cls = PyJPClass_getJPClass(dtype); |
| 857 | if (cls == nullptr || !cls->isPrimitive()) |
| 858 | { |
| 859 | PyErr_Format(PyExc_TypeError, "'%s' is not a Java primitive type", Py_TYPE(dtype)->tp_name); |
| 860 | return nullptr; |
| 861 | } |
| 862 | } else |
| 863 | { |
| 864 | switch (format[0]) |
| 865 | { |
| 866 | case '?': cls = context->_boolean; |
| 867 | case 'c': break; |
| 868 | case 'b': cls = context->_byte; |
| 869 | case 'B': break; |
| 870 | case 'h': cls = context->_short; |
| 871 | break; |
| 872 | case 'H': break; |
| 873 | case 'i': |
| 874 | case 'l': cls = context->_int; |
| 875 | break; |
| 876 | case 'I': |
| 877 | case 'L': break; |
| 878 | case 'q': cls = context->_long; |
| 879 | break; |
| 880 | case 'Q': break; |
| 881 | case 'f': cls = context->_float; |
| 882 | break; |
| 883 | case 'd': cls = context->_double; |
| 884 | break; |
| 885 | case 'n': |
| 886 | case 'N': |
| 887 | case 'P': |
| 888 | default: |
| 889 | break; |
| 890 | } |
| 891 | if (cls == nullptr) |
| 892 | { |
| 893 | PyErr_Format(PyExc_TypeError, "'%s' type code not supported without dtype specified", format); |
| 894 | return nullptr; |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | // Now we have a valid format code, so next lets get a converter for |
| 899 | // the type. |
| 900 | auto *pcls = dynamic_cast<JPPrimitiveType *>( cls); |
| 901 | |
| 902 | // Convert the shape |
| 903 | Py_ssize_t subs = 1; |
| 904 | Py_ssize_t base = 1; |
| 905 | auto jdims = (jintArray) context->_int->newArrayOf(frame, view.ndim); |
| 906 | if (view.shape != nullptr) |
| 907 | { |
| 908 | JPPrimitiveArrayAccessor<jintArray, jint*> accessor(frame, jdims, |
| 909 | &JPJavaFrame::GetIntArrayElements, &JPJavaFrame::ReleaseIntArrayElements); |
| 910 | jint *a = accessor.get(); |
| 911 | for (int i = 0; i < view.ndim; ++i) |
| 912 | { |
| 913 | a[i] = view.shape[i]; |
| 914 | } |
| 915 | accessor.commit(); |
| 916 | for (int i = 0; i < view.ndim - 1; ++i) |
| 917 | { |
| 918 | subs *= view.shape[i]; |
| 919 | } |
| 920 | base = view.shape[view.ndim - 1]; |
| 921 | } else |
| 922 | { |
| 923 | if (view.ndim > 1) |
| 924 | { |
| 925 | PyErr_Format(PyExc_TypeError, "buffer dims inconsistent"); |
| 926 | return nullptr; |
| 927 | } |
| 928 | base = view.len / view.itemsize; |
| 929 | } |
| 930 | return pcls->newMultiArray(frame, buffer, subs, base, (jobject) jdims); |
| 931 | } |
| 932 | |
| 933 | #ifdef JP_INSTRUMENTATION |
| 934 | |
| 935 | int PyJPModuleFault_check(uint32_t code) |
| 936 | { |
| 937 | return (code == _PyJPModule_fault_code); |
| 938 | } |
| 939 | |
| 940 | void PyJPModuleFault_throw(uint32_t code) |
| 941 | { |
| 942 | if (code == _PyJPModule_fault_code) |
| 943 | { |
| 944 | _PyJPModule_fault_code = -1; |
| 945 | JP_RAISE(PyExc_SystemError, "fault"); |
| 946 | } |
| 947 | } |
| 948 | #endif |
| 949 | |
| 950 | void PyJPModule_installGC(PyObject* module) |
| 951 | { |
| 952 | // Get the Python garbage collector |
| 953 | JPPyObject gc = JPPyObject::call(PyImport_ImportModule("gc")); |
| 954 | |
| 955 | // Find the callbacks |
| 956 | JPPyObject callbacks = JPPyObject::call(PyObject_GetAttrString(gc.get(), "callbacks")); |
| 957 | |
| 958 | // Hook up our callback |
| 959 | JPPyObject collect = JPPyObject::call(PyObject_GetAttrString(module, "_collect")); |
| 960 | PyList_Append(callbacks.get(), collect.get()); |
| 961 | JP_PY_CHECK(); |
| 962 | } |