Debian Codegraph @

src/Base/PyObjectBase.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25 #include <sstream>
26
27 #include "PyObjectBase.h"
28 #include "Console.h"
29 #include "Interpreter.h"
30
31
32 #define ATTR_TRACKING
33
34 using namespace Base;
35
36 // clang-format off
37 PyObject* Base::PyExc_FC_GeneralError = nullptr;
38 PyObject* Base::PyExc_FC_FreeCADAbort = nullptr;
39 PyObject* Base::PyExc_FC_XMLBaseException = nullptr;
40 PyObject* Base::PyExc_FC_XMLParseException = nullptr;
41 PyObject* Base::PyExc_FC_XMLAttributeError = nullptr;
42 PyObject* Base::PyExc_FC_UnknownProgramOption = nullptr;
43 PyObject* Base::PyExc_FC_BadFormatError = nullptr;
44 PyObject* Base::PyExc_FC_BadGraphError = nullptr;
45 PyObject* Base::PyExc_FC_ExpressionError = nullptr;
46 PyObject* Base::PyExc_FC_ParserError = nullptr;
47 PyObject* Base::PyExc_FC_CADKernelError = nullptr;
48 PyObject* Base::PyExc_FC_PropertyError = nullptr;
49 PyObject* Base::PyExc_FC_AbortIOException = nullptr;
50
51 typedef struct { //NOLINT
52 PyObject_HEAD
53 PyObject* baseobject;
54 PyObject* weakreflist; /* List of weak references */
55 } PyBaseProxy;
56
57 // NOLINTNEXTLINE
58 PyObjectBase::PyObjectBase(void* voidp, PyTypeObject *T)
59 : _pcTwinPointer(voidp)
60 {
61 #if PY_VERSION_HEX < 0x030b0000
62 Py_TYPE(this) = T;
63 #else
64 this->ob_type = T;
65 #endif
66 _Py_NewReference(this);
67 #ifdef FC_LOGPYOBJECTS
68 Base::Console().log("PyO+: %s (%p)\n",T->tp_name, this);
69 #endif
70 StatusBits.set(Valid); // valid, the second bit is NOT set, i.e. it's mutable
71 StatusBits.set(Notify);
72 }
73
74 /// destructor
75 PyObjectBase::~PyObjectBase()
76 {
77 PyGILStateLocker lock;
78 #ifdef FC_LOGPYOBJECTS
79 Base::Console().log("PyO-: %s (%p)\n",Py_TYPE(this)->tp_name, this);
80 #endif
81 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
82 if (baseProxy && reinterpret_cast<PyBaseProxy*>(baseProxy)->baseobject == this) {
83 Py_DECREF(baseProxy);
84 }
85 Py_XDECREF(attrDict);
86 }
87
88 /*------------------------------
89 * PyObjectBase Type -- Every class, even the abstract one should have a Type
90 ------------------------------*/
91
92 /** \brief
93 * To prevent subclasses of PyTypeObject to be subclassed in Python we should remove
94 * the Py_TPFLAGS_BASETYPE flag. For example, the classes App::VectorPy and App::MatrixPy
95 * have removed this flag and its Python proxies App.Vector and App.Matrix cannot be subclassed.
96 * In case we want to allow a new class to derive from subclasses of PyTypeObject in Python
97 * we must either reimplement tp_new, tp_dealloc, tp_getattr, tp_setattr, tp_repr or set them to
98 * 0 and define tp_base as 0.
99 */
100
101 #if defined(__clang__)
102 # pragma clang diagnostic push
103 # pragma clang diagnostic ignored "-Wdeprecated-declarations"
104 #endif
105
106 static void
107 PyBaseProxy_dealloc(PyObject* self)
108 {
109 /* Clear weakrefs first before calling any destructors */
110 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
111 if (reinterpret_cast<PyBaseProxy*>(self)->weakreflist) {
112 PyObject_ClearWeakRefs(self);
113 }
114 Py_TYPE(self)->tp_free(self);
115 }
116 static PyTypeObject PyBaseProxyType = {
117 PyVarObject_HEAD_INIT(nullptr, 0)
118 "PyBaseProxy", /*tp_name*/
119 sizeof(PyBaseProxy), /*tp_basicsize*/
120 0, /*tp_itemsize*/
121 PyBaseProxy_dealloc, /*tp_dealloc*/
122 0, /*tp_vectorcall_offset*/
123 nullptr, /*tp_getattr*/
124 nullptr, /*tp_setattr*/
125 nullptr, /*tp_compare*/
126 nullptr, /*tp_repr*/
127 nullptr, /*tp_as_number*/
128 nullptr, /*tp_as_sequence*/
129 nullptr, /*tp_as_mapping*/
130 nullptr, /*tp_hash*/
131 nullptr, /*tp_call */
132 nullptr, /*tp_str */
133 nullptr, /*tp_getattro*/
134 nullptr, /*tp_setattro*/
135 nullptr, /*tp_as_buffer*/
136 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DEFAULT, /*tp_flags */
137 "Proxy class", /*tp_doc */
138 nullptr, /*tp_traverse */
139 nullptr, /*tp_clear */
140 nullptr, /*tp_richcompare */
141 offsetof(PyBaseProxy, weakreflist), /*tp_weaklistoffset */
142 nullptr, /*tp_iter */
143 nullptr, /*tp_iternext */
144 nullptr, /*tp_methods */
145 nullptr, /*tp_members */
146 nullptr, /*tp_getset */
147 nullptr, /*tp_base */
148 nullptr, /*tp_dict */
149 nullptr, /*tp_descr_get */
150 nullptr, /*tp_descr_set */
151 0, /*tp_dictoffset */
152 nullptr, /*tp_init */
153 nullptr, /*tp_alloc */
154 nullptr, /*tp_new */
155 nullptr, /*tp_free Low-level free-memory routine */
156 nullptr, /*tp_is_gc For PyObject_IS_GC */
157 nullptr, /*tp_bases */
158 nullptr, /*tp_mro method resolution order */
159 nullptr, /*tp_cache */
160 nullptr, /*tp_subclasses */
161 nullptr, /*tp_weaklist */
162 nullptr, /*tp_del */
163 0, /*tp_version_tag */
164 nullptr /*tp_finalize */
165 ,0 //NOLINT /*tp_vectorcall */
166 #if PY_VERSION_HEX >= 0x030c0000
167 ,0 /*tp_watched */
168 #endif
169 #if PY_VERSION_HEX >= 0x030d0000
170 ,0 /*tp_versions_used*/
171 #endif
172 };
173
174 PyTypeObject PyObjectBase::Type = {
175 PyVarObject_HEAD_INIT(&PyType_Type,0)
176 "PyObjectBase", /*tp_name*/
177 sizeof(PyObjectBase), /*tp_basicsize*/
178 0, /*tp_itemsize*/
179 /* --- methods ---------------------------------------------- */
180 PyDestructor, /*tp_dealloc*/
181 0, /*tp_vectorcall_offset*/
182 nullptr, /*tp_getattr*/
183 nullptr, /*tp_setattr*/
184 nullptr, /*tp_compare*/
185 __repr, /*tp_repr*/
186 nullptr, /*tp_as_number*/
187 nullptr, /*tp_as_sequence*/
188 nullptr, /*tp_as_mapping*/
189 nullptr, /*tp_hash*/
190 nullptr, /*tp_call */
191 nullptr, /*tp_str */
192 __getattro, /*tp_getattro*/
193 __setattro, /*tp_setattro*/
194 /* --- Functions to access object as input/output buffer ---------*/
195 nullptr, /* tp_as_buffer */
196 /* --- Flags to define presence of optional/expanded features */
197 Py_TPFLAGS_BASETYPE|Py_TPFLAGS_DEFAULT, /*tp_flags */
198 "The most base class for Python binding", /*tp_doc */
199 nullptr, /*tp_traverse */
200 nullptr, /*tp_clear */
201 nullptr, /*tp_richcompare */
202 0, /*tp_weaklistoffset */
203 nullptr, /*tp_iter */
204 nullptr, /*tp_iternext */
205 nullptr, /*tp_methods */
206 nullptr, /*tp_members */
207 nullptr, /*tp_getset */
208 nullptr, /*tp_base */
209 nullptr, /*tp_dict */
210 nullptr, /*tp_descr_get */
211 nullptr, /*tp_descr_set */
212 0, /*tp_dictoffset */
213 nullptr, /*tp_init */
214 nullptr, /*tp_alloc */
215 nullptr, /*tp_new */
216 nullptr, /*tp_free Low-level free-memory routine */
217 nullptr, /*tp_is_gc For PyObject_IS_GC */
218 nullptr, /*tp_bases */
219 nullptr, /*tp_mro method resolution order */
220 nullptr, /*tp_cache */
221 nullptr, /*tp_subclasses */
222 nullptr, /*tp_weaklist */
223 nullptr, /*tp_del */
224 0, /*tp_version_tag */
225 nullptr /*tp_finalize */
226 ,0 //NOLINT /*tp_vectorcall */
227 #if PY_VERSION_HEX >= 0x030c0000
228 ,0 /*tp_watched */
229 #endif
230 #if PY_VERSION_HEX >= 0x030d0000
231 ,0 /*tp_versions_used*/
232 #endif
233 };
234
235 #if defined(__clang__)
236 # pragma clang diagnostic pop
237 #endif
238
239 PyObject* createWeakRef(PyObjectBase* ptr)
240 {
241 static bool init = false;
242 if (!init) {
243 init = true;
244 if (PyType_Ready(&PyBaseProxyType) < 0) {
245 return nullptr;
246 }
247 }
248
249 PyObject* proxy = ptr->baseProxy;
250 if (!proxy) {
251 proxy = PyType_GenericAlloc(&PyBaseProxyType, 0);
252 ptr->baseProxy = proxy;
253 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
254 reinterpret_cast<PyBaseProxy*>(proxy)->baseobject = ptr;
255 }
256
257 PyObject* ref = PyWeakref_NewRef(proxy, nullptr);
258 return ref;
259 }
260
261 PyObjectBase* getFromWeakRef(PyObject* ref)
262 {
263 if (ref) {
264 #if PY_VERSION_HEX >= 0x030d0000
265 ::PyObject* proxy;
266 int returnCode = PyWeakref_GetRef(ref, &proxy);
267 if (returnCode != 1) {
268 return nullptr;
269 }
270 Py_DECREF(proxy);
271 #else
272 PyObject* proxy = PyWeakref_GetObject(ref);
273 #endif
274 if (proxy && PyObject_TypeCheck(proxy, &PyBaseProxyType)) {
275 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
276 return static_cast<PyObjectBase*>(reinterpret_cast<PyBaseProxy*>(proxy)->baseobject);
277 }
278 }
279
280 return nullptr;
281 }
282
283 /*------------------------------
284 * PyObjectBase Methods -- Every class, even the abstract one should have a Methods
285 ------------------------------*/
286 PyMethodDef PyObjectBase::Methods[] = {
287 {nullptr, nullptr, 0, nullptr} /* Sentinel */
288 };
289
290 PyObject* PyObjectBase::__getattro(PyObject * obj, PyObject *attro)
291 {
292 const char *attr{};
293 attr = PyUnicode_AsUTF8(attro);
294
295 // For the __class__ attribute get it directly as with
296 // ExtensionContainerPy::getCustomAttributes we may get
297 // the wrong type object (#0003311)
298 if (streq(attr, "__class__")) {
299 PyObject* res = PyObject_GenericGetAttr(obj, attro);
300 if (res) {
301 return res;
302 }
303 }
304
305 // This should be the entry in Type
306 PyObjectBase* pyObj = static_cast<PyObjectBase*>(obj);
307 if (!pyObj->isValid()){
308 PyErr_Format(PyExc_ReferenceError, "Cannot access attribute '%s' of deleted object", attr);
309 return nullptr;
310 }
311
312 #ifdef ATTR_TRACKING
313 // If an attribute references this as parent then reset it (bug #0002902)
314 PyObject* cur = pyObj->getTrackedAttribute(attr);
315 if (cur) {
316 if (PyObject_TypeCheck(cur, &(PyObjectBase::Type))) {
317 PyObjectBase* base = static_cast<PyObjectBase*>(cur);
318 base->resetAttribute();
319 pyObj->untrackAttribute(attr);
320 }
321 }
322 #endif
323
324 PyObject* value = pyObj->_getattr(attr);
325 #ifdef ATTR_TRACKING
326 if (value && PyObject_TypeCheck(value, &(PyObjectBase::Type))) {
327 if (!static_cast<PyObjectBase*>(value)->isConst() &&
328 !static_cast<PyObjectBase*>(value)->isNotTracking()) {
329 static_cast<PyObjectBase*>(value)->setAttributeOf(attr, pyObj);
330 pyObj->trackAttribute(attr, value);
331 }
332 }
333 else
334 #endif
335 if (value && PyCFunction_Check(value)) {
336 // ExtensionContainerPy::initialization() transfers the methods of an
337 // extension object by creating PyCFunction objects.
338 // At this point no 'self' object is passed but is handled and determined
339 // in ExtensionContainerPy::getCustomAttributes().
340 // So, if we come through this section then it's an indication that
341 // something is wrong with the Python types. For example, a C++ class
342 // that adds an extension uses the same Python type as a wrapper than
343 // another C++ class without this extension.
344 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
345 PyCFunctionObject* cfunc = reinterpret_cast<PyCFunctionObject*>(value);
346 if (!cfunc->m_self) {
347 Py_DECREF(cfunc);
348 value = nullptr;
349 PyErr_Format(PyExc_AttributeError, "<no object bound to built-in method %s>", attr);
350 }
351 }
352
353 return value;
354 }
355
356 int PyObjectBase::__setattro(PyObject *obj, PyObject *attro, PyObject *value)
357 {
358 const char *attr{};
359 attr = PyUnicode_AsUTF8(attro);
360
361 //Hint: In general we don't allow one to delete attributes (i.e. value=0). However, if we want to allow
362 //we must check then in _setattr() of all subclasses whether value is 0.
363 if (!value) {
364 PyErr_Format(PyExc_AttributeError, "Cannot delete attribute: '%s'", attr);
365 return -1;
366 }
367 if (!static_cast<PyObjectBase*>(obj)->isValid()){
368 PyErr_Format(PyExc_ReferenceError, "Cannot access attribute '%s' of deleted object", attr);
369 return -1;
370 }
371
372 #ifdef ATTR_TRACKING
373 // If an attribute references this as parent then reset it
374 // before setting the new attribute
375 PyObject* cur = static_cast<PyObjectBase*>(obj)->getTrackedAttribute(attr);
376 if (cur) {
377 if (PyObject_TypeCheck(cur, &(PyObjectBase::Type))) {
378 PyObjectBase* base = static_cast<PyObjectBase*>(cur);
379 base->resetAttribute();
380 static_cast<PyObjectBase*>(obj)->untrackAttribute(attr);
381 }
382 }
383 #endif
384
385 int ret = static_cast<PyObjectBase*>(obj)->_setattr(attr, value);
386 #ifdef ATTR_TRACKING
387 if (ret == 0) {
388 static_cast<PyObjectBase*>(obj)->startNotify();
389 }
390 #endif
391 return ret;
392 }
393
394 /*------------------------------
395 * PyObjectBase attributes -- attributes
396 ------------------------------*/
397 PyObject *PyObjectBase::_getattr(const char *attr)
398 {
399 if (streq(attr, "__class__")) {
400 // Note: We must return the type object here,
401 // so that our own types feel as really Python objects
402 Py_INCREF(Py_TYPE(this));
403 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
404 return reinterpret_cast<PyObject *>(Py_TYPE(this));
405 }
406 if (streq(attr, "__members__")) {
407 // Use __dict__ instead as __members__ is deprecated
408 return nullptr;
409 }
410 if (streq(attr,"__dict__")) {
411 // Return the default dict
412 PyTypeObject *tp = Py_TYPE(this);
413 Py_XINCREF(tp->tp_dict);
414 return tp->tp_dict;
415 }
416 if (streq(attr,"softspace")) {
417 // Internal Python stuff
418 return nullptr;
419 }
420 // As fallback solution use Python's default method to get generic attributes
421 PyObject *w{}, *res{};
422 w = PyUnicode_InternFromString(attr);
423 if (w) {
424 res = PyObject_GenericGetAttr(this, w);
425 Py_XDECREF(w);
426 return res;
427 }
428 // Throw an exception for unknown attributes
429 PyTypeObject *tp = Py_TYPE(this);
430 PyErr_Format(PyExc_AttributeError, "%.50s instance has no attribute '%.400s'", tp->tp_name, attr);
431 return nullptr;
432 }
433
434 int PyObjectBase::_setattr(const char *attr, PyObject *value)
435 {
436 if (streq(attr,"softspace")) {
437 return -1; // filter out softspace
438 }
439 PyObject *w{};
440 // As fallback solution use Python's default method to get generic attributes
441 w = PyUnicode_InternFromString(attr); // new reference
442 if (w) {
443 // call methods from tp_getset if defined
444 int res = PyObject_GenericSetAttr(this, w, value);
445 Py_DECREF(w);
446 return res;
447 }
448 // Throw an exception for unknown attributes
449 PyTypeObject *tp = Py_TYPE(this);
450 PyErr_Format(PyExc_AttributeError, "%.50s instance has no attribute '%.400s'", tp->tp_name, attr);
451 return -1;
452 }
453
454 /*------------------------------
455 * PyObjectBase repr representations
456 ------------------------------*/
457 PyObject *PyObjectBase::_repr()
458 {
459 std::stringstream a;
460 a << "<base object at " << _pcTwinPointer << ">";
461 # ifdef FCDebug
462 Console().log("PyObjectBase::_repr() not overwritten representation!");
463 # endif
464 return Py_BuildValue("s", a.str().c_str());
465 }
466
467 // Tracking functions
468
469 void PyObjectBase::resetAttribute()
470 {
471 if (attrDict) {
472 // This is the attribute name to the parent structure
473 // which we search for in the dict
474 PyObject* key1 = PyBytes_FromString("__attribute_of_parent__");
475 PyObject* key2 = PyBytes_FromString("__instance_of_parent__");
476 PyObject* attr = PyDict_GetItem(attrDict, key1);
477 PyObject* inst = PyDict_GetItem(attrDict, key2);
478 if (attr) {
479 PyDict_DelItem(attrDict, key1);
480 }
481 if (inst) {
482 PyDict_DelItem(attrDict, key2);
483 }
484 Py_DECREF(key1);
485 Py_DECREF(key2);
486 }
487 }
488
489 void PyObjectBase::setAttributeOf(const char* attr, PyObject* par)
490 {
491 if (!attrDict) {
492 attrDict = PyDict_New();
493 }
494
495 PyObject* key1 = PyBytes_FromString("__attribute_of_parent__");
496 PyObject* key2 = PyBytes_FromString("__instance_of_parent__");
497 PyObject* attro = PyUnicode_FromString(attr);
498 PyDict_SetItem(attrDict, key1, attro);
499 PyDict_SetItem(attrDict, key2, par);
500 Py_DECREF(attro);
501 Py_DECREF(key1);
502 Py_DECREF(key2);
503 }
504
505 void PyObjectBase::startNotify()
506 {
507 if (!shouldNotify()) {
508 return;
509 }
510
511 if (attrDict) {
512 // This is the attribute name to the parent structure
513 // which we search for in the dict
514 PyObject* key1 = PyBytes_FromString("__attribute_of_parent__");
515 PyObject* key2 = PyBytes_FromString("__instance_of_parent__");
516 PyObject* attr = PyDict_GetItem(attrDict, key1);
517 PyObject* parent = PyDict_GetItem(attrDict, key2);
518 if (attr && parent) {
519 // Inside __setattr of the parent structure the 'attr'
520 // is being removed from the dict and thus its reference
521 // counter will be decremented. To avoid to be deleted we
522 // must tmp. increment it and afterwards decrement it again.
523 Py_INCREF(parent);
524 Py_INCREF(attr);
525 Py_INCREF(this);
526
527 __setattro(parent, attr, this);
528
529 Py_DECREF(parent); // might be destroyed now
530 Py_DECREF(attr); // might be destroyed now
531 Py_DECREF(this); // might be destroyed now
532
533 if (PyErr_Occurred()) {
534 PyErr_Clear();
535 }
536 }
537 Py_DECREF(key1);
538 Py_DECREF(key2);
539 }
540 }
541
542 PyObject* PyObjectBase::getTrackedAttribute(const char* attr)
543 {
544 PyObject* obj = nullptr;
545 if (attrDict) {
546 obj = PyDict_GetItemString(attrDict, attr);
547 obj = getFromWeakRef(obj);
548 }
549 return obj;
550 }
551
552 void PyObjectBase::trackAttribute(const char* attr, PyObject* obj)
553 {
554 if (!attrDict) {
555 attrDict = PyDict_New();
556 }
557
558 PyObject* obj_ref = createWeakRef(static_cast<PyObjectBase*>(obj));
559 if (obj_ref) {
560 PyDict_SetItemString(attrDict, attr, obj_ref);
561 }
562 }
563
564 void PyObjectBase::untrackAttribute(const char* attr)
565 {
566 if (attrDict) {
567 PyDict_DelItemString(attrDict, attr);
568 }
569 }
570
571 void PyObjectBase::clearAttributes()
572 {
573 if (attrDict) {
574 PyDict_Clear(attrDict);
575 }
576 }
577 // clang-format on