Debian Codegraph @

native/python/jp_pythontypes.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
19 /****************************************************************************
20 * Base object
21 ***************************************************************************/
22
23 static void assertValid(PyObject *obj)
24 {
25 #ifndef Py_GIL_DISABLED
26 if (Py_REFCNT(obj) >= 1)
27 return;
28
29 // GCOVR_EXCL_START
30 // At this point our car has traveled beyond the end of the
31 // cliff and it will hit the ground some twenty
32 // python calls later with a nearly untracable fault, thus
33 // rather than waiting for the inevitable, we chose to take
34 // a noble death here.
35 JP_TRACE_PY("pyref FAULT", obj);
36 JP_RAISE(PyExc_SystemError, "Deleted reference");
37 // GCOVR_EXCL_STOP
38 #else
39 return; // GIL is disabled; we assume obj is valid
40 #endif
41 }
42
43 /**
44 * This policy is used if we need to hold a reference to an existing
45 * object for some duration. The object may be null.
46 *
47 * Increment reference count if not null, and decrement when done.
48 */
49 JPPyObject JPPyObject::use(PyObject* obj)
50 {
51 JP_TRACE_PY("pyref use(inc)", obj);
52 if (obj != nullptr)
53 {
54 assertValid(obj);
55 Py_INCREF(obj);
56 }
57 return JPPyObject(obj);
58 }
59
60 /**
61 * This policy is used when we are given a new reference that we must
62 * destroy. This will steal a reference.
63 *
64 * claim reference, and decremented when done.
65 */
66 JPPyObject JPPyObject::accept(PyObject* obj)
67 {
68 JP_TRACE_PY("pyref new(accept)", obj);
69 if (obj == nullptr)
70 PyErr_Clear();
71 return JPPyObject(obj);
72 }
73
74 /**
75 * This policy is used when we are given a new reference that we must
76 * destroy. This will steal a reference.
77 *
78 * Assert not null, claim reference, and decremented when done.
79 * Will throw an exception if the object is null.
80 */
81 JPPyObject JPPyObject::claim(PyObject* obj)
82 {
83 JP_TRACE_PY("pyref new(claim)", obj);
84 ASSERT_NOT_NULL(obj);
85 assertValid(obj);
86 return JPPyObject(obj);
87 }
88
89 /**
90 * This policy is used when we are capturing an object returned from a python
91 * call that we are responsible for. This will steal a reference.
92 *
93 * Check for errors, assert not null, then claim.
94 * Will throw an exception an error occurs.
95 */
96 JPPyObject JPPyObject::call(PyObject* obj)
97 {
98 JP_TRACE_PY("pyref new(call)", obj);
99 JP_PY_CHECK();
100 ASSERT_NOT_NULL(obj);
101 assertValid(obj);
102 return JPPyObject(obj);
103 }
104
105 JPPyObject::JPPyObject(PyObject* obj)
106 : m_PyObject(obj)
107 {
108 }
109
110 JPPyObject::JPPyObject(const JPPyObject &self)
111 : m_PyObject(self.m_PyObject)
112 {
113 if (m_PyObject != nullptr)
114 {
115 incref();
116 JP_TRACE_PY("pyref copy ctor(inc)", m_PyObject);
117 }
118 }
119
120 JPPyObject::~JPPyObject()
121 {
122 if (m_PyObject != nullptr)
123 {
124 JP_TRACE_PY("pyref dtor(dec)", m_PyObject);
125 decref();
126 } else
127 {
128 JP_TRACE_PY("pyref dtor(null)", m_PyObject);
129 }
130 }
131
132 JPPyObject& JPPyObject::operator=(const JPPyObject& self)
133 {
134 if (m_PyObject == self.m_PyObject)
135 return *this;
136 if (m_PyObject != nullptr)
137 {
138 JP_TRACE_PY("pyref op=(dec)", m_PyObject);
139 decref();
140 }
141 m_PyObject = self.m_PyObject;
142 if (m_PyObject != nullptr)
143 {
144 incref();
145 JP_TRACE_PY("pyref op=(inc)", m_PyObject);
146 }
147 return *this;
148 }
149
150 PyObject* JPPyObject::keep()
151 {
152 // This can only happen if we have a fatal error in our reference
153 // management system. It should never be triggered by the user.
154 if (m_PyObject == nullptr)
155 {
156 JP_RAISE(PyExc_SystemError, "Attempt to keep null reference"); // GCOVR_EXCL_LINE
157 }
158 JP_TRACE_PY("pyref keep ", m_PyObject);
159 PyObject *out = m_PyObject;
160 m_PyObject = nullptr;
161 return out;
162 }
163
164 void JPPyObject::incref()
165 {
166 assertValid(m_PyObject);
167 Py_INCREF(m_PyObject);
168 }
169
170 void JPPyObject::decref()
171 {
172 assertValid(m_PyObject);
173 Py_DECREF(m_PyObject);
174 m_PyObject = nullptr;
175 }
176
177 JPPyObject JPPyObject::getNone()
178 {
179 return JPPyObject::use(Py_None);
180 }
181
182 /****************************************************************************
183 * String
184 ***************************************************************************/
185
186 JPPyObject JPPyString::fromCharUTF16(jchar c)
187 {
188 #if defined(PYPY_VERSION)
189 wchar_t buf[1];
190 buf[0] = c;
191 return JPPyObject::call(PyUnicode_FromWideChar(buf, 1));
192 #else
193 if (c < 128)
194 {
195 char c1 = (char) c;
196 return JPPyObject::call(PyUnicode_FromStringAndSize(&c1, 1));
197 }
198 JPPyObject buf = JPPyObject::call(PyUnicode_New(1, 65535));
199 Py_UCS4 c2 = c;
200 PyUnicode_WriteChar(buf.get(), 0, c2);
201 JP_PY_CHECK();
202 PyUnicode_READY(buf.get());
203 return buf;
204 #endif
205 }
206
207 bool JPPyString::checkCharUTF16(PyObject* pyobj)
208 {
209 JP_TRACE_IN("JPPyString::checkCharUTF16");
210 if (PyIndex_Check(pyobj))
211 return true;
212 if (PyUnicode_Check(pyobj) && PyUnicode_GetLength(pyobj) == 1)
213 return true;
214 if (PyBytes_Check(pyobj) && PyBytes_Size(pyobj) == 1)
215 return true;
216 return false;
217 JP_TRACE_OUT; // GCOVR_EXCL_LINE
218 }
219
220 jchar JPPyString::asCharUTF16(PyObject* pyobj)
221 {
222 if (PyIndex_Check(pyobj))
223 {
224 jlong val = PyLong_AsLongLong(pyobj);
225 if (val < 0 || val > 65535)
226 JP_RAISE(PyExc_OverflowError, "Unable to convert int into char range");
227 return (jchar) val;
228 }
229
230 #if defined(PYPY_VERSION)
231 if (PyBytes_Check(pyobj))
232 {
233 int sz = PyBytes_Size(pyobj);
234 if (sz != 1)
235 JP_RAISE(PyExc_ValueError, "Char must be length 1");
236
237 jchar c = PyBytes_AsString(pyobj)[0];
238 if (PyErr_Occurred())
239 JP_RAISE_PYTHON();
240 return c;
241 }
242 if (PyUnicode_Check(pyobj))
243 {
244 if (PyUnicode_GetLength(pyobj) > 1)
245 JP_RAISE(PyExc_ValueError, "Char must be length 1");
246
247 PyUnicode_READY(pyobj);
248 Py_UCS4 value = PyUnicode_READ_CHAR(pyobj, 0);
249 if (value > 0xffff)
250 {
251 JP_RAISE(PyExc_ValueError, "Unable to pack 4 byte unicode into Java char");
252 }
253 return value;
254 }
255 #else
256 if (PyBytes_Check(pyobj))
257 {
258 Py_ssize_t sz = PyBytes_Size(pyobj);
259 if (sz != 1)
260 JP_RAISE(PyExc_ValueError, "Char must be length 1");
261
262 jchar c = PyBytes_AsString(pyobj)[0];
263 JP_PY_CHECK();
264 return c;
265 }
266 if (PyUnicode_Check(pyobj))
267 {
268 if (PyUnicode_GetLength(pyobj) > 1)
269 JP_RAISE(PyExc_ValueError, "Char must be length 1");
270
271 PyUnicode_READY(pyobj);
272 Py_UCS4 value = PyUnicode_ReadChar(pyobj, 0);
273 if (value > 0xffff)
274 {
275 JP_RAISE(PyExc_ValueError, "Unable to pack 4 byte unicode into Java char");
276 }
277 return value;
278 }
279 #endif
280 PyErr_Format(PyExc_TypeError, "Unable to convert '%s' to Java char", Py_TYPE(pyobj)->tp_name);
281 JP_RAISE_PYTHON();
282 }
283
284 /** Check if the object is a bytes or unicode.
285 *
286 * @returns true if the object is bytes or unicode.
287 */
288 bool JPPyString::check(PyObject* obj)
289 {
290 return PyUnicode_Check(obj) || PyBytes_Check(obj);
291 }
292
293 /** Create a new string from utf8 encoded string.
294 * Note: java utf8 is not utf8.
295 */
296 JPPyObject JPPyString::fromStringUTF8(const string& str)
297 {
298 auto len = static_cast<Py_ssize_t>(str.size());
299
300 // Python 3 is always unicode
301 JPPyObject bytes = JPPyObject::call(PyBytes_FromStringAndSize(str.c_str(), len));
302 return JPPyObject::call(PyUnicode_FromEncodedObject(bytes.get(), "UTF-8", "strict"));
303 }
304
305 string JPPyString::asStringUTF8(PyObject* pyobj)
306 {
307 JP_TRACE_IN("JPPyUnicode::asStringUTF8");
308 ASSERT_NOT_NULL(pyobj);
309
310 if (PyUnicode_Check(pyobj))
311 {
312 Py_ssize_t size = 0;
313 char *buffer = nullptr;
314 JPPyObject val = JPPyObject::call(PyUnicode_AsEncodedString(pyobj, "UTF-8", "strict"));
315 PyBytes_AsStringAndSize(val.get(), &buffer, &size);
316 JP_PY_CHECK();
317 if (buffer != nullptr)
318 return {buffer, static_cast<size_t>(size)};
319 else
320 return {};
321 } else if (PyBytes_Check(pyobj))
322 {
323 Py_ssize_t size = 0;
324 char *buffer = nullptr;
325 PyBytes_AsStringAndSize(pyobj, &buffer, &size);
326 JP_PY_CHECK();
327 return {buffer, static_cast<size_t>(size)};
328 }
329 // GCOVR_EXCL_START
330 JP_RAISE(PyExc_TypeError, "Failed to convert to string.");
331 return {};
332 JP_TRACE_OUT;
333 // GCOVR_EXCL_STOP
334 }
335
336 /****************************************************************************
337 * Container types
338 ***************************************************************************/
339
340 jlong JPPySequence::size()
341 {
342 return PySequence_Size(m_Sequence.get());
343 }
344
345 JPPyObject JPPySequence::operator[](jlong i)
346 {
347 return JPPyObject::call(PySequence_GetItem(m_Sequence.get(), (Py_ssize_t) i)); // new reference
348 }
349
350 JPPyObjectVector::JPPyObjectVector(PyObject* sequence)
351 {
352 m_Sequence = JPPyObject::use(sequence);
353 auto n = PySequence_Size(m_Sequence.get());
354 m_Contents.resize(n);
355 for (decltype(n) i = 0; i < n; ++i)
356 {
357 m_Contents[i] = JPPyObject::call(PySequence_GetItem(m_Sequence.get(), i));
358 }
359 }
360
361 JPPyObjectVector::JPPyObjectVector(PyObject* inst, PyObject* sequence)
362 {
363 m_Instance = JPPyObject::use(inst);
364 m_Sequence = JPPyObject::use(sequence);
365 Py_ssize_t n = 0;
366 if (sequence != nullptr)
367 n = PySequence_Size(m_Sequence.get());
368 m_Contents.resize(n + 1);
369 for (decltype(n) i = 0; i < n; ++i)
370 {
371 m_Contents[i + 1] = JPPyObject::call(PySequence_GetItem(m_Sequence.get(), i));
372 }
373 m_Contents[0] = m_Instance;
374 }
375
376 bool JPPyErr::fetch(JPPyObject& exceptionClass, JPPyObject& exceptionValue, JPPyObject& exceptionTrace)
377 {
378 PyObject *v1, *v2, *v3;
379 PyErr_Fetch(&v1, &v2, &v3);
380 if (v1 == nullptr && v2 == nullptr && v3 == nullptr)
381 return false;
382 exceptionClass = JPPyObject::accept(v1);
383 exceptionValue = JPPyObject::accept(v2);
384 exceptionTrace = JPPyObject::accept(v3);
385 return true;
386 }
387
388 void JPPyErr::restore(JPPyObject& exceptionClass, JPPyObject& exceptionValue, JPPyObject& exceptionTrace)
389 {
390 PyErr_Restore(exceptionClass.keepNull(), exceptionValue.keepNull(), exceptionTrace.keepNull());
391 }
392
393 JPPyCallAcquire::JPPyCallAcquire()
394 {
395 m_State = (long) PyGILState_Ensure();
396 }
397
398 JPPyCallAcquire::~JPPyCallAcquire()
399 {
400 PyGILState_Release((PyGILState_STATE) m_State);
401 }
402
403 // This is used when leaving python from to perform some
404
405 JPPyCallRelease::JPPyCallRelease()
406 {
407 // Release the lock and set the thread state to NULL
408 m_State1 = PyEval_SaveThread();
409 }
410
411 JPPyCallRelease::~JPPyCallRelease()
412 {
413 // Re-acquire the lock
414 PyEval_RestoreThread(m_State1);
415 }
416
417 JPPyBuffer::JPPyBuffer(PyObject* obj, int flags)
418 {
419 int ret = PyObject_GetBuffer(obj, &m_View, flags);
420 m_Valid = (ret != -1);
421 }
422
423 JPPyBuffer::~JPPyBuffer()
424 {
425 if (m_Valid)
426 PyBuffer_Release(&m_View);
427 }
428
429 char *JPPyBuffer::getBufferPtr(std::vector<Py_ssize_t>& indices) const
430 {
431 char *pointer = (char*) m_View.buf;
432 // No shape is just a 1D array
433 if (m_View.shape == nullptr)
434 {
435 return pointer;
436 }
437
438 // No strides is C contiguous ND array
439 if (m_View.strides == nullptr)
440 {
441 Py_ssize_t index = 0;
442 for (int i = 0; i < m_View.ndim; i++)
443 {
444 index = index * m_View.shape[i] + indices[i];
445 }
446 index *= m_View.itemsize;
447 return pointer + index;
448 }
449
450 // Otherwise we can be a full array
451 for (int i = 0; i < m_View.ndim; i++)
452 {
453 pointer += m_View.strides[i] * indices[i];
454 if (m_View.suboffsets != nullptr && m_View.suboffsets[i] >= 0 )
455 {
456 pointer = *((char**) pointer) + m_View.suboffsets[i];
457 }
458 }
459 return pointer;
460 }
461
462 JPPyErrFrame::JPPyErrFrame()
463 {
464 good = JPPyErr::fetch(m_ExceptionClass, m_ExceptionValue, m_ExceptionTrace);
465 }
466
467 JPPyErrFrame::~JPPyErrFrame()
468 {
469 try
470 {
471 if (good)
472 JPPyErr::restore(m_ExceptionClass, m_ExceptionValue, m_ExceptionTrace);
473 } catch (...) // GCOVR_EXCL_LINE
474 {
475 // No throw is allowed in dtor.
476 }
477 }
478
479 void JPPyErrFrame::clear()
480 {
481 good = false;
482 }
483
484 void JPPyErrFrame::normalize()
485 {
486 // Python uses lazy evaluation on exceptions thus we can't modify it until
487 // we have forced it to realize the exception.
488 if (!PyExceptionInstance_Check(m_ExceptionValue.get()))
489 {
490 JPPyObject args = JPPyTuple_Pack(m_ExceptionValue.get());
491 m_ExceptionValue = JPPyObject::call(PyObject_Call(m_ExceptionClass.get(), args.get(), nullptr));
492 PyException_SetTraceback(m_ExceptionValue.get(), m_ExceptionTrace.get());
493 JPPyErr::restore(m_ExceptionClass, m_ExceptionValue, m_ExceptionTrace);
494 JPPyErr::fetch(m_ExceptionClass, m_ExceptionValue, m_ExceptionTrace);
495 }
496 }