Debian Codegraph @

native/python/pyjp_value.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_stringtype.h"
19 #include <Python.h>
20 #include <mutex>
21
22 #ifdef __cplusplus
23 extern "C"
24 {
25 #endif
26
27 std::mutex mtx;
28
29 // Create a dummy type which we will use only for allocation
30 PyTypeObject* PyJPAlloc_Type = nullptr;
31
32 /**
33 * Allocate a new Python object with a slot for Java.
34 *
35 * We need extra space to store our values, but because there
36 * is no way to do so without disturbing the object layout.
37 * Fortunately, Python already handles this for dict and weakref.
38 * Python aligns the ends of the structure and increases the
39 * base type size to add additional slots to a standard object.
40 *
41 * We will use the same trick to add an additional slot for Java
42 * after the end of the object outside of where Python is looking.
43 * As the memory is aligned this is safe to do. We will use
44 * the alloc and finalize slot to recognize which objects have this
45 * extra slot appended.
46 */
47 PyObject* PyJPValue_alloc(PyTypeObject* type, Py_ssize_t nitems)
48 {
49 JP_PY_TRY("PyJPValue_alloc");
50
51 #if PY_VERSION_HEX >= 0x030d0000
52 // This flag will try to place the dictionary are part of the object which
53 // adds an unknown number of bytes to the end of the object making it impossible
54 // to attach our needed data. If we kill the flag then we get usable behavior.
55 if (PyType_HasFeature(type, Py_TPFLAGS_INLINE_VALUES)) {
56 PyErr_Format(PyExc_RuntimeError, "Unhandled object layout");
57 return 0;
58 }
59 #endif
60
61 PyObject* obj = nullptr;
62 {
63 std::lock_guard<std::mutex> lock(mtx);
64 // Mutate the allocator type
65 PyJPAlloc_Type->tp_flags = type->tp_flags;
66 PyJPAlloc_Type->tp_basicsize = type->tp_basicsize + sizeof (JPValue);
67 PyJPAlloc_Type->tp_itemsize = type->tp_itemsize;
68
69 // Create a new allocation for the dummy type
70 obj = PyType_GenericAlloc(PyJPAlloc_Type, nitems);
71 }
72
73 // Watch for memory errors
74 if (obj == nullptr)
75 return nullptr;
76
77 // Polymorph the type to match our desired type
78 obj->ob_type = type;
79 Py_INCREF(type);
80
81 JP_TRACE("alloc", type->tp_name, obj);
82 return obj;
83 JP_PY_CATCH(nullptr);
84 }
85
86 bool PyJPValue_hasJavaSlot(PyTypeObject* type)
87 {
88 if (type == nullptr
89 || type->tp_alloc != (allocfunc) PyJPValue_alloc
90 || type->tp_finalize != (destructor) PyJPValue_finalize)
91 return false; // GCOVR_EXCL_LINE
92 return true;
93 }
94
95 Py_ssize_t PyJPValue_getJavaSlotOffset(PyObject* self)
96 {
97 PyTypeObject *type = Py_TYPE(self);
98 if (type == nullptr
99 || type->tp_alloc != (allocfunc) PyJPValue_alloc
100 || type->tp_finalize != (destructor) PyJPValue_finalize)
101 {
102 return 0;
103 }
104
105 Py_ssize_t offset = 0;
106 Py_ssize_t sz = 0;
107
108 #if PY_VERSION_HEX>=0x030c0000
109 // starting in 3.12 there is no longer ob_size in PyLong
110 if (PyType_HasFeature(self->ob_type, Py_TPFLAGS_LONG_SUBCLASS))
111 sz = (((PyLongObject*)self)->long_value.lv_tag) >> 3; // Private NON_SIZE_BITS
112 else
113 #endif
114 if (type->tp_itemsize != 0)
115 sz = Py_SIZE(self);
116 // PyLong abuses ob_size with negative values prior to 3.12
117 if (sz < 0)
118 sz = -sz;
119 if (type->tp_itemsize == 0)
120 offset = _PyObject_VAR_SIZE(type, 1);
121 else
122 offset = _PyObject_VAR_SIZE(type, sz + 1);
123 return offset;
124 }
125
126 /**
127 * Get the Java value if attached.
128 *
129 * The Java class is guaranteed not to be nullptr on success.
130 *
131 * @param obj
132 * @return the Java value or 0 if not found.
133 */
134 JPValue* PyJPValue_getJavaSlot(PyObject* self)
135 {
136 Py_ssize_t offset = PyJPValue_getJavaSlotOffset(self);
137 if (offset == 0)
138 return nullptr;
139 auto value = (JPValue*) (((char*) self) + offset);
140 if (value->getClass() == nullptr)
141 return nullptr;
142 return value;
143 }
144
145 void PyJPValue_free(void* obj)
146 {
147 JP_PY_TRY("PyJPValue_free", obj);
148 // Normally finalize is not run on simple classes.
149 PyTypeObject *type = Py_TYPE(obj);
150 if (type->tp_finalize != nullptr)
151 type->tp_finalize((PyObject*) obj);
152 if (type->tp_flags & Py_TPFLAGS_HAVE_GC)
153 PyObject_GC_Del(obj);
154 else
155 PyObject_Free(obj); // GCOVR_EXCL_LINE
156 JP_PY_CATCH_NONE();
157 }
158
159 void PyJPValue_finalize(void* obj)
160 {
161 JP_PY_TRY("PyJPValue_finalize", obj);
162 JP_TRACE("type", Py_TYPE(obj)->tp_name);
163 JPValue* value = PyJPValue_getJavaSlot((PyObject*) obj);
164 if (value == nullptr)
165 return;
166
167 // We can skip if the JVM is stopped. No need for an exception here.
168 JPContext *context = JPContext_global;
169 if (context == nullptr || !context->isRunning())
170 return;
171
172 // JVM is running so set up the frame.
173 JPJavaFrame frame = JPJavaFrame::outer();
174 JPClass* cls = value->getClass();
175 // This one can't check for initialized because we may need to delete a stale
176 // resource after shutdown.
177 if (cls != nullptr && context->isRunning() && !cls->isPrimitive())
178 {
179 JP_TRACE("Value", cls->getCanonicalName(), &(value->getValue()));
180 JP_TRACE("Dereference object");
181 context->ReleaseGlobalRef(value->getValue().l);
182 *value = JPValue();
183 }
184 JP_PY_CATCH_NONE();
185 }
186
187 /** This is the way to convert an object into a python string. */
188 PyObject* PyJPValue_str(PyObject* self)
189 {
190 JP_PY_TRY("PyJPValue_str", self);
191 JPContext *context = PyJPModule_getContext();
192 JPJavaFrame frame = JPJavaFrame::outer();
193 JPValue* value = PyJPValue_getJavaSlot(self);
194 if (value == nullptr)
195 {
196 PyErr_SetString(PyExc_TypeError, "Not a Java value");
197 return nullptr;
198 }
199
200 JPClass* cls = value->getClass();
201 if (cls->isPrimitive())
202 {
203 PyErr_SetString(PyExc_TypeError, "toString requires a Java object");
204 return nullptr;
205 }
206
207 if (value->getValue().l == nullptr)
208 return JPPyString::fromStringUTF8("null").keep();
209
210 if (cls == context->_java_lang_String)
211 {
212 PyObject *cache;
213 JPPyObject dict = JPPyObject::accept(PyObject_GenericGetDict(self, nullptr));
214 if (!dict.isNull())
215 {
216 cache = PyDict_GetItemString(dict.get(), "_jstr");
217 if (cache)
218 {
219 Py_INCREF(cache);
220 return cache;
221 }
222 auto jstr = (jstring) value->getValue().l;
223 string str;
224 str = frame.toStringUTF8(jstr);
225 cache = JPPyString::fromStringUTF8(str).keep();
226 PyDict_SetItemString(dict.get(), "_jstr", cache);
227 return cache;
228 }
229 }
230
231 // In general toString is not immutable, so we won't cache it.
232 return JPPyString::fromStringUTF8(frame.toString(value->getValue().l)).keep();
233 JP_PY_CATCH(nullptr);
234 }
235
236 PyObject *PyJPValue_getattro(PyObject *obj, PyObject *name)
237 {
238 JP_PY_TRY("PyJPObject_getattro");
239 if (!PyUnicode_Check(name))
240 {
241 PyErr_Format(PyExc_TypeError,
242 "attribute name must be string, not '%.200s'",
243 Py_TYPE(name)->tp_name);
244 return nullptr;
245 }
246
247 // Private members are accessed directly
248 PyObject* pyattr = PyBaseObject_Type.tp_getattro(obj, name);
249 if (pyattr == nullptr)
250 return nullptr;
251 JPPyObject attr = JPPyObject::accept(pyattr);
252
253 // Private members go regardless
254 if (PyUnicode_GetLength(name) && PyUnicode_ReadChar(name, 0) == '_')
255 return attr.keep();
256
257 // Methods
258 if (Py_TYPE(attr.get()) == (PyTypeObject*) PyJPMethod_Type)
259 return attr.keep();
260
261 // Don't allow properties to be rewritten
262 if (!PyObject_IsInstance(attr.get(), (PyObject*) & PyProperty_Type))
263 return attr.keep();
264
265 PyErr_Format(PyExc_AttributeError, "Field '%U' is static", name);
266 return nullptr;
267 JP_PY_CATCH(nullptr);
268 }
269
270 int PyJPValue_setattro(PyObject *self, PyObject *name, PyObject *value)
271 {
272 JP_PY_TRY("PyJPObject_setattro");
273
274 // Private members are accessed directly
275 if (PyUnicode_GetLength(name) && PyUnicode_ReadChar(name, 0) == '_')
276 return PyObject_GenericSetAttr(self, name, value);
277 JPPyObject f = JPPyObject::accept(PyJP_GetAttrDescriptor(Py_TYPE(self), name));
278 if (f.isNull())
279 {
280 PyErr_Format(PyExc_AttributeError, "Field '%U' is not found", name);
281 return -1;
282 }
283 descrsetfunc desc = Py_TYPE(f.get())->tp_descr_set;
284 if (desc != nullptr)
285 return desc(f.get(), self, value);
286
287 // Not a descriptor
288 PyErr_Format(PyExc_AttributeError,
289 "Field '%U' is not settable on Java '%s' object", name, Py_TYPE(self)->tp_name);
290 return -1;
291 JP_PY_CATCH(-1);
292 }
293
294 #ifdef __cplusplus
295 }
296 #endif
297
298 // These are from the internal methods when we already have the jvalue
299
300 void PyJPValue_assignJavaSlot(JPJavaFrame &frame, PyObject* self, const JPValue& value)
301 {
302 Py_ssize_t offset = PyJPValue_getJavaSlotOffset(self);
303 // GCOVR_EXCL_START
304 if (offset == 0)
305 {
306 std::stringstream ss;
307 ss << "Missing Java slot on `" << Py_TYPE(self)->tp_name << "`";
308 JP_RAISE(PyExc_SystemError, ss.str());
309 }
310 // GCOVR_EXCL_STOP
311
312 auto* slot = (JPValue*) (((char*) self) + offset);
313 // GCOVR_EXCL_START
314 // This is a sanity check that should never trigger in normal operations.
315 if (slot->getClass() != nullptr)
316 {
317 JP_RAISE(PyExc_SystemError, "Slot assigned twice");
318 }
319 // GCOVR_EXCL_STOP
320 JPClass* cls = value.getClass();
321 if (cls != nullptr && !cls->isPrimitive())
322 {
323 jvalue q;
324 q.l = frame.NewGlobalRef(value.getValue().l);
325 *slot = JPValue(cls, q);
326 } else
327 *slot = value;
328 }
329
330 bool PyJPValue_isSetJavaSlot(PyObject* self)
331 {
332 Py_ssize_t offset = PyJPValue_getJavaSlotOffset(self);
333 if (offset == 0)
334 return false; // GCOVR_EXCL_LINE
335 auto* slot = (JPValue*) (((char*) self) + offset);
336 return slot->getClass() != nullptr;
337 }
338
339 /***************** Create a dummy type for use when allocating. ************************/
340 static int PyJPAlloc_traverse(PyObject *self, visitproc visit, void *arg)
341 {
342 return 0;
343 }
344
345 static int PyJPAlloc_clear(PyObject *self)
346 {
347 return 0;
348 }
349
350
351 static PyType_Slot allocSlots[] = {
352 { Py_tp_traverse, (void*) PyJPAlloc_traverse},
353 { Py_tp_clear, (void*) PyJPAlloc_clear},
354 {0, NULL} // Sentinel
355 };
356
357 static PyType_Spec allocSpec = {
358 "_jpype._JAlloc",
359 sizeof(PyObject),
360 0,
361 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
362 allocSlots
363 };
364
365 void PyJPValue_initType(PyObject* module)
366 {
367 PyObject *bases = PyTuple_Pack(1, &PyBaseObject_Type);
368 PyJPAlloc_Type = (PyTypeObject*) PyType_FromSpecWithBases(&allocSpec, bases);
369 Py_DECREF(bases);
370 Py_INCREF(PyJPAlloc_Type);
371 JP_PY_CHECK();
372 }