Debian Codegraph @

native/common/jp_exception.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 <Python.h>
17 #include <frameobject.h>
18
19 #include "jpype.h"
20 #include "jp_exception.h"
21 #include "pyjp.h"
22
23 static_assert(std::is_nothrow_copy_constructible<JPypeException>::value,
24 "S must be nothrow copy constructible");
25
26 PyObject* PyTrace_FromJPStackTrace(JPStackTrace& trace);
27
28 JPypeException::JPypeException(JPJavaFrame &frame, jthrowable th, const JPStackInfo& stackInfo)
29 : std::runtime_error(frame.toString(th)),
30 m_Type(JPError::_java_error),
31 m_Throwable(frame, th)
32 {
33 JP_TRACE("JAVA EXCEPTION THROWN with java throwable");
34 m_Error.l = nullptr;
35 from(stackInfo);
36 }
37
38 JPypeException::JPypeException(int type, void* error, const JPStackInfo& stackInfo)
39 : std::runtime_error("None"), m_Type(type)
40 {
41 JP_TRACE("EXCEPTION THROWN with error", error);
42 m_Error.l = error;
43 from(stackInfo);
44 }
45
46 JPypeException::JPypeException(int type, void* errType, const string& msn, const JPStackInfo& stackInfo)
47 : std::runtime_error(msn), m_Type(type)
48 {
49 JP_TRACE("EXCEPTION THROWN", errType, msn);
50 m_Error.l = errType;
51 //m_Message = msn;
52 from(stackInfo);
53 }
54
55 // GCOVR_EXCL_START
56 // This is only used during startup for OSError
57
58 JPypeException::JPypeException(int type, const string& msn, int errType, const JPStackInfo& stackInfo)
59 : std::runtime_error(msn), m_Type(type)
60 {
61 JP_TRACE("EXCEPTION THROWN", errType, msn);
62 m_Error.i = errType;
63 from(stackInfo);
64 }
65
66 JPypeException::JPypeException(const JPypeException &ex) noexcept
67 : runtime_error(ex.what()), m_Type(ex.m_Type), m_Error(ex.m_Error),
68 m_Trace(ex.m_Trace), m_Throwable(ex.m_Throwable)
69 {
70 }
71
72 JPypeException& JPypeException::operator = (const JPypeException& ex)
73 {
74 if(this == &ex)
75 {
76 return *this;
77 }
78 m_Type = ex.m_Type;
79 m_Trace = ex.m_Trace;
80 m_Throwable = ex.m_Throwable;
81 m_Error = ex.m_Error;
82 return *this;
83 }
84 // GCOVR_EXCL_STOP
85
86 void JPypeException::from(const JPStackInfo& info)
87 {
88 JP_TRACE("EXCEPTION FROM: ", info.getFile(), info.getLine());
89 m_Trace.push_back(info);
90 }
91
92 bool isJavaThrowable(PyObject* exceptionClass)
93 {
94 JPClass* cls = PyJPClass_getJPClass(exceptionClass);
95 if (cls == nullptr)
96 return false;
97 return cls->isThrowable();
98 }
99
100 void JPypeException::convertJavaToPython()
101 {
102 // Welcome to paranoia land, where they really are out to get you!
103 JP_TRACE_IN("JPypeException::convertJavaToPython");
104 // GCOVR_EXCL_START
105 JPContext* context = JPContext_global;
106 if (context == nullptr)
107 {
108 PyErr_SetString(PyExc_RuntimeError, "Unable to convert java error, context is null.");
109 return;
110 }
111 // GCOVR_EXCL_STOP
112
113 // Okay we can get to a frame to talk to the object
114 JPJavaFrame frame = JPJavaFrame::external(context->getEnv());
115 jthrowable th = m_Throwable.get();
116 jvalue v;
117 v.l = th;
118 // GCOVR_EXCL_START
119 // This is condition is only hit if something fails during the initial boot
120 if (context->getJavaContext() == nullptr || context->m_Context_GetExcClassID == nullptr)
121 {
122 PyErr_SetString(PyExc_SystemError, frame.toString(th).c_str());
123 return;
124 }
125 // GCOVR_EXCL_STOP
126 jlong pycls = frame.CallLongMethodA(context->getJavaContext(), context->m_Context_GetExcClassID, &v);
127 if (pycls != 0)
128 {
129 jlong value = frame.CallLongMethodA(context->getJavaContext(), context->m_Context_GetExcValueID, &v);
130 PyErr_SetObject((PyObject*) pycls, (PyObject*) value);
131 return;
132 }
133 JP_TRACE("Check typemanager");
134 // GCOVR_EXCL_START
135 if (!context->isRunning())
136 {
137 PyErr_SetString(PyExc_RuntimeError, frame.toString((jobject) th).c_str());
138 return;
139 }
140 // GCOVR_EXCL_STOP
141
142 // Convert to Python object
143 JP_TRACE("Convert to python");
144 JPClass* cls = frame.findClassForObject((jobject) th);
145
146 // GCOVR_EXCL_START
147 // This sanity check can only fail if the type system fails to find a
148 // class for the current exception.
149 if (cls == nullptr)
150 {
151 // Nope, no class found
152 PyErr_SetString(PyExc_RuntimeError, frame.toString(th).c_str());
153 return;
154 }
155 // GCOVR_EXCL_STOP
156
157 // Create the exception object (this may fail)
158 v.l = th;
159 JPPyObject pyvalue = cls->convertToPythonObject(frame, v, false);
160
161 // GCOVR_EXCL_START
162 // This sanity check can only be hit if the exception failed during
163 // conversion in some extraordinary way.
164 if (pyvalue.isNull())
165 {
166 PyErr_SetString(PyExc_RuntimeError, frame.toString(th).c_str());
167 return;
168 }
169 // GCOVR_EXCL_STOP
170
171 PyObject *type = (PyObject*) Py_TYPE(pyvalue.get());
172 Py_INCREF(type);
173
174 // Add cause to the exception
175 JPPyObject args = JPPyObject::call(Py_BuildValue("(s)", "Java Exception"));
176 JPPyObject cause = JPPyObject::call(PyObject_Call(PyExc_Exception, args.get(), nullptr));
177 JPPyObject trace = PyTrace_FromJavaException(frame, th, nullptr);
178
179 // Attach Java causes as well.
180 try
181 {
182 jthrowable jcause = frame.getCause(th);
183 if (jcause != nullptr)
184 {
185 jvalue a;
186 a.l = (jobject) jcause;
187 JPPyObject prev = context->_java_lang_Object->convertToPythonObject(frame, a, false);
188 PyJPException_normalize(frame, prev, jcause, th);
189 PyException_SetCause(cause.get(), prev.keep());
190 }
191 if (trace.get() != nullptr)
192 PyException_SetTraceback(cause.get(), trace.get());
193 PyException_SetCause(pyvalue.get(), cause.keep());
194 } catch (JPypeException& ex)
195 {
196 (void) ex;
197 JP_TRACE("FAILURE IN CAUSE");
198 // Any failures in this optional action should be ignored.
199 // worst case we don't print as much diagnostics.
200 }
201
202 // Transfer to Python
203 PyErr_SetObject(type, pyvalue.get());
204 JP_TRACE_OUT; // GCOVR_EXCL_LINE
205 }
206
207 void JPypeException::convertPythonToJava()
208 {
209 JP_TRACE_IN("JPypeException::convertPythonToJava");
210 JPJavaFrame frame = JPJavaFrame::outer();
211 JPContext *context = frame.getContext();
212 jthrowable th;
213 JPPyErrFrame eframe;
214 if (eframe.good && isJavaThrowable(eframe.m_ExceptionClass.get()))
215 {
216 eframe.good = false;
217 JPValue* javaExc = PyJPValue_getJavaSlot(eframe.m_ExceptionValue.get());
218 if (javaExc != nullptr)
219 {
220 th = (jthrowable) javaExc->getJavaObject();
221 JP_TRACE("Throwing Java", frame.toString(th));
222 frame.Throw(th);
223 return;
224 }
225 }
226
227 if (context->m_Context_CreateExceptionID == nullptr)
228 {
229 frame.ThrowNew(frame.FindClass("java/lang/RuntimeException"), std::runtime_error::what());
230 return;
231 }
232
233
234 // Otherwise
235 jvalue v[2];
236 v[0].j = (jlong) eframe.m_ExceptionClass.get();
237 v[1].j = (jlong) eframe.m_ExceptionValue.get();
238 th = (jthrowable) frame.CallObjectMethodA(context->getJavaContext(),
239 context->m_Context_CreateExceptionID, v);
240 frame.registerRef((jobject) th, eframe.m_ExceptionClass.get());
241 frame.registerRef((jobject) th, eframe.m_ExceptionValue.get());
242 eframe.clear();
243 frame.Throw(th);
244 JP_TRACE_OUT; // GCOVR_EXCL_LINE
245 }
246
247 void JPypeException::toPython()
248 {
249 const char* mesg = nullptr;
250 JP_TRACE_IN("JPypeException::toPython");
251 JP_TRACE("err", PyErr_Occurred());
252 try
253 {
254 // Check the signals before processing the exception
255 // It may be a signal when interrupted Java in which case
256 // the signal takes precedence.
257 if (PyErr_CheckSignals()!=0)
258 return;
259
260 mesg = std::runtime_error::what();
261 JP_TRACE(m_Error.l);
262 JP_TRACE(mesg);
263
264 // We already have a Python error on the stack.
265 if (PyErr_Occurred())
266 return;
267
268 if (m_Type == JPError::_java_error)
269 {
270 JP_TRACE("Java exception");
271 JPypeException::convertJavaToPython();
272 return;
273 } else if (m_Type == JPError::_python_error)
274 {
275 // Already on the stack
276 }// This section is only reachable during startup of the JVM.
277 // GCOVR_EXCL_START
278 else if (m_Type == JPError::_os_error_unix)
279 {
280 std::stringstream ss;
281 ss << "JVM DLL not found: " << mesg;
282 PyObject* val = Py_BuildValue("(iz)", m_Error.i,
283 ss.str().c_str());
284 if (val != nullptr)
285 {
286 PyObject* exc = PyObject_Call(PyExc_OSError, val, nullptr);
287 Py_DECREF(val);
288 if (exc != nullptr)
289 {
290 PyErr_SetObject(PyExc_OSError, exc);
291 Py_DECREF(exc);
292 }
293 }
294 } else if (m_Type == JPError::_os_error_windows)
295 {
296 std::stringstream ss;
297 ss << "JVM DLL not found: " << mesg;
298 PyObject* val = Py_BuildValue("(izzi)", 2,
299 ss.str().c_str(), NULL, m_Error.i);
300 if (val != nullptr)
301 {
302 PyObject* exc = PyObject_Call(PyExc_OSError, val, nullptr);
303 Py_DECREF(val);
304 if (exc != nullptr)
305 {
306 PyErr_SetObject(PyExc_OSError, exc);
307 Py_DECREF(exc);
308 }
309 }
310 }// GCOVR_EXCL_STOP
311
312 else if (m_Type == JPError::_python_exc)
313 {
314 // All others are Python errors
315 JP_TRACE(Py_TYPE(m_Error.l)->tp_name);
316 PyErr_SetString((PyObject*) m_Error.l, mesg);
317 } else
318 {
319 // This should not be possible unless we failed to cover one of the
320 // exception type codes.
321 JP_TRACE("Unknown error");
322 PyErr_SetString(PyExc_RuntimeError, mesg); // GCOVR_EXCL_LINE
323 }
324
325 // Attach our info as the cause
326 if (_jp_cpp_exceptions)
327 {
328 JPPyErrFrame eframe;
329 eframe.normalize();
330 JPPyObject args = JPPyObject::call(Py_BuildValue("(s)", "C++ Exception"));
331 JPPyObject trace = JPPyObject::call(PyTrace_FromJPStackTrace(m_Trace));
332 JPPyObject cause = JPPyObject::accept(PyObject_Call(PyExc_Exception, args.get(), nullptr));
333 if (!cause.isNull())
334 {
335 PyException_SetTraceback(cause.get(), trace.get());
336 PyException_SetCause(eframe.m_ExceptionValue.get(), cause.keep());
337 }
338 }
339 }// GCOVR_EXCL_START
340 catch (JPypeException& ex)
341 {
342 // Print our parting words
343 JPTracer::trace("Fatal error in exception handling");
344 JPTracer::trace("Handling:", mesg);
345 JPTracer::trace("Type:", m_Error.l);
346 if (ex.m_Type == JPError::_python_error)
347 {
348 JPPyErrFrame eframe;
349 JPTracer::trace("Inner Python:", ((PyTypeObject*) eframe.m_ExceptionClass.get())->tp_name);
350 return; // Let these go to Python, so we can see the error
351 } else if (ex.m_Type == JPError::_java_error)
352 JPTracer::trace("Inner Java:", ex.what());
353 else
354 JPTracer::trace("Inner:", ex.what());
355
356 JPStackInfo info = ex.m_Trace.front();
357 JPTracer::trace(info.getFile(), info.getFunction(), info.getLine());
358
359 // Heghlu'meH QaQ jajvam!
360 PyErr_SetString(PyExc_RuntimeError, "Fatal error occurred");
361 return;
362 } catch (...)
363 {
364 // urp?!
365 JPTracer::trace("Fatal error in exception handling");
366
367 // You shall not pass!
368 int *i = nullptr;
369 *i = 0;
370 }
371 // GCOVR_EXCL_STOP
372 JP_TRACE_OUT; // GCOVR_EXCL_LINE
373 }
374
375 void JPypeException::toJava()
376 {
377 JP_TRACE_IN("JPypeException::toJava");
378 JPContext* context = JPContext_global;
379 try
380 {
381 const char* mesg = what();
382 JPJavaFrame frame = JPJavaFrame::external(context->getEnv());
383 if (m_Type == JPError::_java_error)
384 {
385 JP_TRACE("Java exception");
386 //JP_TRACE(context->toString((jobject) frame.ExceptionOccurred()));
387 if (m_Throwable.get() != 0)
388 {
389 JP_TRACE("Java rethrow");
390 frame.Throw(m_Throwable.get());
391 return;
392 }
393 return;
394 }
395
396 if (m_Type == JPError::_python_error)
397 {
398 JPPyCallAcquire callback;
399 JP_TRACE("Python exception");
400 convertPythonToJava();
401 return;
402 }
403
404 if (m_Type == JPError::_python_exc)
405 {
406 JPPyCallAcquire callback;
407 // All others are Python errors
408 JP_TRACE(Py_TYPE(m_Error.l)->tp_name);
409 PyErr_SetString((PyObject*) m_Error.l, mesg);
410 convertPythonToJava();
411 return;
412 }
413
414 // All others are issued as RuntimeExceptions
415 JP_TRACE("String exception");
416 frame.ThrowNew(context->m_RuntimeException.get(), mesg);
417 return;
418 } catch (JPypeException& ex) // GCOVR_EXCL_LINE
419 { // GCOVR_EXCL_START
420 // Print our parting words.
421 JPTracer::trace("Fatal error in exception handling");
422 JPStackInfo info = ex.m_Trace.front();
423 JPTracer::trace(info.getFile(), info.getFunction(), info.getLine());
424
425 // Take one for the team.
426 int *i = nullptr;
427 *i = 0;
428 // GCOVR_EXCL_STOP
429 } catch (...) // GCOVR_EXCL_LINE
430 {
431 // GCOVR_EXCL_START
432 // urp?!
433 JPTracer::trace("Fatal error in exception handling");
434
435 // It is pointless, I can't go on.
436 int *i = nullptr;
437 *i = 0;
438 // GCOVR_EXCL_STOP
439 }
440 JP_TRACE_OUT; // GCOVR_EXCL_LINE
441 }
442
443 PyObject *tb_create(
444 PyObject *last_traceback,
445 PyObject *dict,
446 const char* filename,
447 const char* funcname,
448 int linenum)
449 {
450 // Create a code for this frame. (ref count is 1)
451 JPPyObject code = JPPyObject::accept((PyObject*)PyCode_NewEmpty(filename, funcname, linenum));
452
453 // If we don't get the code object there is no point
454 if (code.get() == nullptr)
455 return nullptr;
456
457 // Create a frame for the traceback.
458 PyThreadState *state = PyThreadState_GET();
459 PyFrameObject *pframe = PyFrame_New(state, (PyCodeObject*) code.get(), dict, NULL);
460 JPPyObject frame = JPPyObject::accept((PyObject*)pframe);
461
462 // If we don't get the frame object there is no point
463 if (frame.get() == nullptr)
464 return nullptr;
465
466 // Create a traceback
467 #if PY_MINOR_VERSION<11
468 JPPyObject lasti = JPPyObject::claim(PyLong_FromLong(pframe->f_lasti));
469 #else
470 JPPyObject lasti = JPPyObject::claim(PyLong_FromLong(PyFrame_GetLasti(pframe)));
471 #endif
472 JPPyObject linenuma = JPPyObject::claim(PyLong_FromLong(linenum));
473 JPPyObject tuple = JPPyTuple_Pack(Py_None, frame.get(), lasti.get(), linenuma.get());
474 JPPyObject traceback = JPPyObject::accept(PyObject_Call((PyObject*) &PyTraceBack_Type, tuple.get(), NULL));
475
476 // We could fail in process
477 if (traceback.get() == nullptr)
478 {
479 return nullptr;
480 }
481
482 return traceback.keep();
483 }
484
485 PyObject* PyTrace_FromJPStackTrace(JPStackTrace& trace)
486 {
487 PyObject *last_traceback = nullptr;
488 PyObject *dict = PyModule_GetDict(PyJPModule);
489 for (auto& iter : trace)
490 {
491 last_traceback = tb_create(last_traceback, dict, iter.getFile(),
492 iter.getFunction(), iter.getLine());
493 }
494 if (last_traceback == nullptr)
495 Py_RETURN_NONE;
496 return (PyObject*) last_traceback;
497 }
498
499 JPPyObject PyTrace_FromJavaException(JPJavaFrame& frame, jthrowable th, jthrowable prev)
500 {
501 PyObject *last_traceback = NULL;
502 JPContext *context = frame.getContext();
503 jvalue args[2];
504 args[0].l = th;
505 args[1].l = prev;
506 if (context->m_Context_GetStackFrameID == nullptr)
507 return {};
508
509 JNIEnv* env = frame.getEnv();
510 jobjectArray obj = static_cast<jobjectArray>(env->CallObjectMethodA(context->getJavaContext(),
511 context->m_Context_GetStackFrameID, args));
512
513 // Eat any exceptions that were generated
514 if (env->ExceptionCheck() == JNI_TRUE)
515 env->ExceptionClear();
516
517 if (obj == nullptr)
518 return {};
519 jsize sz = frame.GetArrayLength(obj);
520 PyObject *dict = PyModule_GetDict(PyJPModule);
521 for (jsize i = 0; i < sz; i += 4)
522 {
523 string filename, method;
524 auto jclassname = static_cast<jstring>(frame.GetObjectArrayElement(obj, i));
525 auto jmethodname = static_cast<jstring>(frame.GetObjectArrayElement(obj, i + 1));
526 auto jfilename = static_cast<jstring>(frame.GetObjectArrayElement(obj, i + 2));
527 if (jfilename != nullptr)
528 filename = frame.toStringUTF8(jfilename);
529 else
530 filename = frame.toStringUTF8(jclassname) + ".java";
531 if (jmethodname != nullptr)
532 method = frame.toStringUTF8(jclassname) + "." + frame.toStringUTF8(jmethodname);
533 jint lineNum =
534 frame.CallIntMethodA(frame.GetObjectArrayElement(obj, i + 3), context->_java_lang_Integer->m_IntValueID, nullptr);
535
536 // sending -1 will cause issues on Windows
537 if (lineNum<0)
538 lineNum = 0;
539
540 last_traceback = tb_create(last_traceback, dict, filename.c_str(),
541 method.c_str(), lineNum);
542 frame.DeleteLocalRef(jclassname);
543 frame.DeleteLocalRef(jmethodname);
544 frame.DeleteLocalRef(jfilename);
545 }
546 if (last_traceback == nullptr)
547 return {};
548 return JPPyObject::call((PyObject*) last_traceback);
549 }