Debian Codegraph @

native/common/jp_context.cpp

raw symbols SCIP
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_typemanager.h"
19 #include "jp_stringtype.h"
20 #include "jp_classloader.h"
21 #include "jp_proxy.h"
22 #include "jp_platform.h"
23 #include "jp_gc.h"
24
25 #ifdef WIN32
26 #include <Windows.h>
27 #else
28 #if defined(_HPUX) && !defined(_IA64)
29 #include <dl.h>
30 #else
31 #include <dlfcn.h>
32 #endif // HPUX
33 #include <errno.h>
34 #endif
35
36
37 JPResource::~JPResource() = default;
38
39
40 #define USE_JNI_VERSION JNI_VERSION_1_4
41
42 void JPRef_failed()
43 {
44 JP_RAISE(PyExc_SystemError, "NULL context in JPRef()");
45 }
46
47 JPContext::JPContext()
48 {
49 m_Embedded = false;
50
51 m_GC = new JPGarbageCollection();
52 }
53
54 JPContext::~JPContext()
55 {
56 delete m_TypeManager;
57 delete m_GC;
58 }
59
60 bool JPContext::isRunning()
61 {
62 if (m_JavaVM == nullptr || !m_Running)
63 {
64 return false;
65 }
66 return true;
67 }
68
69 /**
70 throw a JPypeException if the JVM is not started
71 */
72 void assertJVMRunning(JPContext* context, const JPStackInfo& info)
73 {
74 if (_JVMNotRunning == nullptr)
75 {
76 _JVMNotRunning = PyObject_GetAttrString(PyJPModule, "JVMNotRunning");
77 JP_PY_CHECK();
78 Py_INCREF(_JVMNotRunning);
79 }
80
81 if (context == nullptr)
82 {
83 throw JPypeException(JPError::_python_exc, _JVMNotRunning, "Java Context is null", info);
84 }
85
86 if (!context->isRunning())
87 {
88 throw JPypeException(JPError::_python_exc, _JVMNotRunning, "Java Virtual Machine is not running", info);
89 }
90 }
91
92 void JPContext::loadEntryPoints(const string& path)
93 {
94 JP_TRACE_IN("JPContext::loadEntryPoints");
95 JPPlatformAdapter *platform = JPPlatformAdapter::getAdapter();
96 // Load symbols from the shared library
97 platform->loadLibrary((char*) path.c_str());
98 CreateJVM_Method = (jint(JNICALL *)(JavaVM **, void **, void *) )platform->getSymbol("JNI_CreateJavaVM");
99 GetCreatedJVMs_Method = (jint(JNICALL *)(JavaVM **, jsize, jsize*))platform->getSymbol("JNI_GetCreatedJavaVMs");
100 JP_TRACE_OUT;
101 }
102
103 void JPContext::startJVM(const string& vmPath, const StringVector& args,
104 bool ignoreUnrecognized, bool convertStrings, bool interrupt)
105 {
106 JP_TRACE_IN("JPContext::startJVM");
107
108 JP_TRACE("Convert strings", convertStrings);
109 m_ConvertStrings = convertStrings;
110
111 // Get the entry points in the shared library
112 try
113 {
114 JP_TRACE("Load entry points");
115 loadEntryPoints(vmPath);
116 } catch (JPypeException& ex)
117 {
118 (void) ex;
119 throw;
120 }
121
122 // Determine the memory requirements
123 #define PAD(x) ((x+31)&~31)
124 size_t mem = PAD(sizeof(JavaVMInitArgs));
125 size_t oblock = mem;
126 mem += PAD(sizeof(JavaVMOption)*args.size() + 1);
127 size_t sblock = mem;
128 for (size_t i = 0; i < args.size(); i++)
129 {
130 mem += PAD(args[i].size()+1);
131 }
132
133 // Pack the arguments
134 JP_TRACE("Pack arguments");
135 char *block = (char*) malloc(mem);
136 JavaVMInitArgs* jniArgs = (JavaVMInitArgs*) block;
137 memset(jniArgs, 0, mem);
138 jniArgs->options = (JavaVMOption*)(&block[oblock]);
139
140 // prepare this ...
141 jniArgs->version = USE_JNI_VERSION;
142 jniArgs->ignoreUnrecognized = ignoreUnrecognized;
143 JP_TRACE("IgnoreUnrecognized", ignoreUnrecognized);
144
145 jniArgs->nOptions = (jint) args.size();
146 JP_TRACE("NumOptions", jniArgs->nOptions);
147 size_t j = sblock;
148 for (size_t i = 0; i < args.size(); i++)
149 {
150 JP_TRACE("Option", args[i]);
151 strncpy(&block[j], args[i].c_str(), args[i].size());
152 jniArgs->options[i].optionString = (char*) &block[j];
153 j += PAD(args[i].size()+1);
154 }
155
156 // Launch the JVM
157 JNIEnv* env = nullptr;
158 JP_TRACE("Create JVM");
159 try
160 {
161 CreateJVM_Method(&m_JavaVM, (void**) &env, (void*) jniArgs);
162 } catch (...)
163 {
164 JP_TRACE("Exception in CreateJVM?");
165 }
166 JP_TRACE("JVM created");
167 free(jniArgs);
168
169 if (m_JavaVM == nullptr)
170 {
171 JP_TRACE("Unable to start");
172 JP_RAISE(PyExc_RuntimeError, "Unable to start JVM");
173 }
174
175 // Mark running for assert
176 m_Running = true;
177 initializeResources(env, interrupt);
178 JP_TRACE_OUT;
179 }
180
181 void JPContext::attachJVM(JNIEnv* env)
182 {
183 env->GetJavaVM(&m_JavaVM);
184 #ifndef ANDROID
185 m_Embedded = true;
186 #endif
187 initializeResources(env, false);
188 }
189
190 std::string getShared()
191 {
192 #ifdef WIN32
193 // Windows specific
194 char path[MAX_PATH];
195 HMODULE hm = NULL;
196 if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
197 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
198 (LPCSTR) &getShared, &hm) != 0 &&
199 GetModuleFileName(hm, path, sizeof(path)) != 0)
200 {
201 // This is needed when there is no-ascii characters in path
202 char shortPathBuffer[MAX_PATH];
203 long len = GetShortPathName(path, shortPathBuffer, MAX_PATH);
204 if (len != 0)
205 return std::string(shortPathBuffer);
206 }
207 #else
208 // Linux specific
209 Dl_info info;
210 if (dladdr((void*)getShared, &info))
211 return info.dli_fname;
212 #endif
213 // Generic
214 JPPyObject import = JPPyObject::use(PyImport_AddModule("importlib.util"));
215 JPPyObject jpype = JPPyObject::call(PyObject_CallMethod(import.get(), "find_spec", "s", "_jpype"));
216 JPPyObject origin = JPPyObject::call(PyObject_GetAttrString(jpype.get(), "origin"));
217 return JPPyString::asStringUTF8(origin.get());
218 }
219
220 void JPContext::initializeResources(JNIEnv* env, bool interrupt)
221 {
222 JPJavaFrame frame = JPJavaFrame::external(env);
223 // This is the only frame that we can use until the system
224 // is initialized. Any other frame creation will result in an error.
225
226 jclass throwableClass = (jclass) frame.FindClass("java/lang/Throwable");
227 m_Throwable_GetCauseID = frame.GetMethodID(throwableClass, "getCause", "()Ljava/lang/Throwable;");
228 m_Throwable_GetMessageID = frame.GetMethodID(throwableClass, "getMessage", "()Ljava/lang/String;");
229
230 // After the JVM is created but before the context is started, we need
231 // to set up all the services that the context will need.
232 JP_TRACE("Initialize");
233
234 // We need these first because if anything goes south this is the first
235 // thing that will get hit.
236 jclass objectClass = frame.FindClass("java/lang/Object");
237 m_Object_ToStringID = frame.GetMethodID(objectClass, "toString", "()Ljava/lang/String;");
238 m_Object_EqualsID = frame.GetMethodID(objectClass, "equals", "(Ljava/lang/Object;)Z");
239 m_Object_HashCodeID = frame.GetMethodID(objectClass, "hashCode", "()I");
240 m_Object_GetClassID = frame.GetMethodID(objectClass, "getClass", "()Ljava/lang/Class;");
241
242 m_RuntimeException = JPClassRef(frame, (jclass) frame.FindClass("java/lang/RuntimeException"));
243
244 jclass stringClass = frame.FindClass("java/lang/String");
245 m_String_ToCharArrayID = frame.GetMethodID(stringClass, "toCharArray", "()[C");
246
247 jclass classClass = frame.FindClass("java/lang/Class");
248 m_Class_GetNameID = frame.GetMethodID(classClass, "getName", "()Ljava/lang/String;");
249
250 // Bootloader needs to go first so we can load classes
251 m_ClassLoader = new JPClassLoader(frame);
252
253 JP_TRACE("Install native");
254 // Start the rest of the services
255 m_TypeManager = new JPTypeManager(frame);
256
257 // Prepare to launch
258 JP_TRACE("Start Context");
259 m_ContextClass = JPClassRef(frame, (jclass) m_ClassLoader->findClass(frame, "org.jpype.JPypeContext"));
260 jclass contextClass = m_ContextClass.get();
261 m_Context_GetStackFrameID = frame.GetMethodID(contextClass, "getStackTrace",
262 "(Ljava/lang/Throwable;Ljava/lang/Throwable;)[Ljava/lang/Object;");
263
264 jmethodID startMethod = frame.GetStaticMethodID(contextClass, "createContext",
265 "(JLjava/lang/ClassLoader;Ljava/lang/String;Z)Lorg/jpype/JPypeContext;");
266
267 // Launch
268 jvalue val[4];
269 val[0].j = (jlong) this;
270 val[1].l = m_ClassLoader->getBootLoader();
271 val[2].l = nullptr;
272 val[3].z = interrupt;
273
274 if (!m_Embedded)
275 {
276 std::string shared = getShared();
277 val[2].l = frame.fromStringUTF8(shared);
278 }
279
280 // Required before launch
281 m_Context_GetFunctionalID = frame.GetStaticMethodID(contextClass,
282 "getFunctional",
283 "(Ljava/lang/Class;)Ljava/lang/String;");
284
285 m_JavaContext = JPObjectRef(frame, frame.CallStaticObjectMethodA(contextClass, startMethod, val));
286
287 // Post launch
288 JP_TRACE("Connect resources");
289 // Hook up the type manager
290 jmethodID getTypeManager = frame.GetMethodID(contextClass, "getTypeManager",
291 "()Lorg/jpype/manager/TypeManager;");
292 m_TypeManager->m_JavaTypeManager = JPObjectRef(frame,
293 frame.CallObjectMethodA(m_JavaContext.get(), getTypeManager, nullptr));
294
295 // Set up methods after everything is start so we get better error
296 // messages
297 jclass reflectorClass = frame.FindClass("org/jpype/JPypeReflector");
298 jfieldID reflectorField = frame.GetFieldID(contextClass, "reflector", "Lorg/jpype/JPypeReflector;");
299 m_Reflector = JPObjectRef(frame, frame.GetObjectField(m_JavaContext.get(), reflectorField));
300 m_CallMethodID = frame.GetMethodID(reflectorClass, "callMethod",
301 "(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
302 m_Context_collectRectangularID = frame.GetMethodID(contextClass,
303 "collectRectangular",
304 "(Ljava/lang/Object;)[Ljava/lang/Object;");
305
306 m_Context_assembleID = frame.GetMethodID(contextClass,
307 "assemble",
308 "([ILjava/lang/Object;)Ljava/lang/Object;");
309
310 m_Context_CreateExceptionID = frame.GetMethodID(contextClass, "createException",
311 "(JJ)Ljava/lang/Exception;");
312 m_Context_GetExcClassID = frame.GetMethodID(contextClass, "getExcClass",
313 "(Ljava/lang/Throwable;)J");
314 m_Context_GetExcValueID = frame.GetMethodID(contextClass, "getExcValue",
315 "(Ljava/lang/Throwable;)J");
316 m_Context_OrderID = frame.GetMethodID(contextClass, "order", "(Ljava/nio/Buffer;)Z");
317 m_Context_IsPackageID = frame.GetMethodID(contextClass, "isPackage", "(Ljava/lang/String;)Z");
318 m_Context_GetPackageID = frame.GetMethodID(contextClass, "getPackage", "(Ljava/lang/String;)Lorg/jpype/pkg/JPypePackage;");
319 m_Context_ClearInterruptID = frame.GetStaticMethodID(contextClass, "clearInterrupt", "(Z)V");
320
321 jclass packageClass = m_ClassLoader->findClass(frame, "org.jpype.pkg.JPypePackage");
322 m_Package_GetObjectID = frame.GetMethodID(packageClass, "getObject",
323 "(Ljava/lang/String;)Ljava/lang/Object;");
324 m_Package_GetContentsID = frame.GetMethodID(packageClass, "getContents",
325 "()[Ljava/lang/String;");
326 m_Context_NewWrapperID = frame.GetMethodID(contextClass, "newWrapper",
327 "(J)V");
328
329 m_Array = JPClassRef(frame, frame.FindClass("java/lang/reflect/Array"));
330 m_Array_NewInstanceID = frame.GetStaticMethodID(m_Array.get(), "newInstance",
331 "(Ljava/lang/Class;[I)Ljava/lang/Object;");
332
333 jclass bufferClass = frame.FindClass("java/nio/Buffer");
334 m_Buffer_IsReadOnlyID = frame.GetMethodID(bufferClass, "isReadOnly",
335 "()Z");
336
337 jclass bytebufferClass = frame.FindClass("java/nio/ByteBuffer");
338 m_Buffer_AsReadOnlyID = frame.GetMethodID(bytebufferClass, "asReadOnlyBuffer",
339 "()Ljava/nio/ByteBuffer;");
340
341 jclass comparableClass = frame.FindClass("java/lang/Comparable");
342 m_CompareToID = frame.GetMethodID(comparableClass, "compareTo",
343 "(Ljava/lang/Object;)I");
344
345 jclass proxyClass = getClassLoader()->findClass(frame, "org.jpype.proxy.JPypeProxy");
346 m_ProxyClass = JPClassRef(frame, proxyClass);
347 m_Proxy_NewID = frame.GetStaticMethodID(m_ProxyClass.get(),
348 "newProxy",
349 "(Lorg/jpype/JPypeContext;JJ[Ljava/lang/Class;)Lorg/jpype/proxy/JPypeProxy;");
350 m_Proxy_NewInstanceID = frame.GetMethodID(m_ProxyClass.get(),
351 "newInstance",
352 "()Ljava/lang/Object;");
353
354 m_GC->init(frame);
355
356 _java_nio_ByteBuffer = this->getTypeManager()->findClassByName("java.nio.ByteBuffer");
357
358 // Testing code to make sure C++ exceptions are handled.
359 // FIXME find a way to call this from instrumentation.
360 // throw std::runtime_error("Failed");
361 // Everything is started.
362 }
363
364 void JPContext::onShutdown()
365 {
366 m_Running = false;
367 }
368
369 void JPContext::shutdownJVM(bool destroyJVM, bool freeJVM)
370 {
371 JP_TRACE_IN("JPContext::shutdown");
372 if (m_JavaVM == nullptr)
373 JP_RAISE(PyExc_RuntimeError, "Attempt to shutdown without a live JVM");
374 // if (m_Embedded)
375 // JP_RAISE(PyExc_RuntimeError, "Cannot shutdown from embedded Python");
376
377 // Wait for all non-demon threads to terminate
378 if (destroyJVM)
379 {
380 JP_TRACE("Destroy JVM");
381 JPPyCallRelease call;
382 m_JavaVM->DestroyJavaVM();
383 }
384
385 // unload the jvm library
386 if (freeJVM)
387 {
388 JP_TRACE("Unload JVM");
389 m_JavaVM = nullptr;
390 JPPlatformAdapter::getAdapter()->unloadLibrary();
391 }
392
393 JP_TRACE("Delete resources");
394 for (auto & m_Resource : m_Resources)
395 {
396 delete m_Resource;
397 }
398 m_Resources.clear();
399
400 JP_TRACE_OUT;
401 }
402
403 void JPContext::ReleaseGlobalRef(jobject obj)
404 {
405 JP_TRACE_IN("JPContext::ReleaseGlobalRef", obj);
406 // Check if the JVM is already shutdown
407 if (m_JavaVM == nullptr)
408 return;
409
410 // Get the environment and release the resource if we can.
411 // Do not attach the thread if called from an unattached thread it is
412 // likely a shutdown anyway.
413 JNIEnv* env;
414 jint res = m_JavaVM->functions->GetEnv(m_JavaVM, (void**) &env, USE_JNI_VERSION);
415 if (res != JNI_EDETACHED)
416 env->functions->DeleteGlobalRef(env, obj);
417 JP_TRACE_OUT;
418 }
419
420 /*****************************************************************************/
421 // Thread code
422
423 void JPContext::attachCurrentThread()
424 {
425 JNIEnv* env;
426 jint res = m_JavaVM->functions->AttachCurrentThread(m_JavaVM, (void**) &env, nullptr);
427 if (res != JNI_OK)
428 JP_RAISE(PyExc_RuntimeError, "Unable to attach to thread");
429 }
430
431 void JPContext::attachCurrentThreadAsDaemon()
432 {
433 JNIEnv* env;
434 jint res = m_JavaVM->functions->AttachCurrentThreadAsDaemon(m_JavaVM, (void**) &env, nullptr);
435 if (res != JNI_OK)
436 JP_RAISE(PyExc_RuntimeError, "Unable to attach to thread as daemon");
437 }
438
439 bool JPContext::isThreadAttached()
440 {
441 JNIEnv* env;
442 return JNI_OK == m_JavaVM->functions->GetEnv(m_JavaVM, (void**) &env, USE_JNI_VERSION);
443 }
444
445 void JPContext::detachCurrentThread()
446 {
447 m_JavaVM->functions->DetachCurrentThread(m_JavaVM);
448 }
449
450 JNIEnv* JPContext::getEnv()
451 {
452 JNIEnv* env = nullptr;
453 if (m_JavaVM == nullptr)
454 {
455 JP_RAISE(PyExc_RuntimeError, "JVM is null");
456 }
457
458 // Get the environment
459 jint res = m_JavaVM->functions->GetEnv(m_JavaVM, (void**) &env, USE_JNI_VERSION);
460
461 // If we don't have an environment then we are in a thread, so we must attach
462 if (res == JNI_EDETACHED)
463 {
464 // We will attach as daemon so that the newly attached thread does
465 // not deadlock the shutdown. The user can convert later if they want.
466 res = m_JavaVM->AttachCurrentThreadAsDaemon((void**) &env, nullptr);
467 if (res != JNI_OK)
468 {
469 JP_RAISE(PyExc_RuntimeError, "Unable to attach to local thread");
470 }
471 }
472 return env;
473 }
474
475 extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeContext_onShutdown
476 (JNIEnv *env, jobject obj, jlong contextPtr)
477 {
478 ((JPContext*) contextPtr)->onShutdown();
479 }
480
481 /**********************************************************************
482 * Interrupts are complex. Both Java and Python want to handle the
483 * interrupt, but only one can be in control. Java starts later and
484 * installs its handler over Python as a chain. If Java handles it then
485 * the JVM will terminate which leaves Python with a bunch of bad
486 * references which tends to lead to segfaults. So we need to disable
487 * the Java one by routing it back to Python. But if we do so then
488 * Java wont respect Ctrl+C. So we need to handle the interrupt, convert
489 * it to a wait interrupt so that Java can break at the next I/O and
490 * then trip Python signal handler so the Python gets the interrupt.
491 *
492 * But this leads to a few race conditions.
493 *
494 * If the control is in Java then it will get the interrupt next time
495 * it hits Python code when the returned object is checked resulting
496 * InterruptedException. Now we have two exceptions on the stack,
497 * the one from Java and the one from Python. We check to see if
498 * Python has a pending interrupt and eat the Java one.
499 *
500 * If the control is in Java and it hits an I/O call. This generates
501 * InterruptedException which again transfers control to Python where
502 * the Exception is resolved.
503 *
504 * If the control is in Python when the interrupt occurs, then
505 * we have a bogus Java interrupt sitting on the main thread that the next
506 * Java call will trip over. So we need to call clearInterrupt(false).
507 * This checks clears the interrupt in C++ and in Java.
508 *
509 */
510
511 static int interruptState = 0;
512 extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeSignal_interruptPy
513 (JNIEnv *env, jclass cls, jint signal)
514 {
515 interruptState = 1;
516 #if PY_MINOR_VERSION<10
517 PyErr_SetInterrupt();
518 #else
519 PyErr_SetInterruptEx((int) signal);
520 #endif
521 }
522
523 extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeSignal_acknowledgePy
524 (JNIEnv *env, jclass cls)
525 {
526 interruptState = 0;
527 }
528
529 int hasInterrupt()
530 {
531 return interruptState != 0;
532 }