Debian Codegraph @

Lib/test/test_cppext/extension.cpp

raw
1 // gh-91321: Very basic C++ test extension to check that the Python C API is
2 // compatible with C++ and does not emit C++ compiler warnings.
3 //
4 // The code is only built, not executed.
5
6 // Always enable assertions
7 #undef NDEBUG
8
9 #include "Python.h"
10
11 #ifndef MODULE_NAME
12 # error "MODULE_NAME macro must be defined"
13 #endif
14
15 #define _STR(NAME) #NAME
16 #define STR(NAME) _STR(NAME)
17
18 PyDoc_STRVAR(_testcppext_add_doc,
19 "add(x, y)\n"
20 "\n"
21 "Return the sum of two integers: x + y.");
22
23 static PyObject *
24 _testcppext_add(PyObject *Py_UNUSED(module), PyObject *args)
25 {
26 long i, j;
27 if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) {
28 return _Py_NULL;
29 }
30 long res = i + j;
31 return PyLong_FromLong(res);
32 }
33
34
35 // Class to test operator casting an object to PyObject*
36 class StrongRef
37 {
38 public:
39 StrongRef(PyObject *obj) : m_obj(obj) {
40 Py_INCREF(this->m_obj);
41 }
42
43 ~StrongRef() {
44 Py_DECREF(this->m_obj);
45 }
46
47 // Cast to PyObject*: get a borrowed reference
48 inline operator PyObject*() const { return this->m_obj; }
49
50 private:
51 PyObject *m_obj; // Strong reference
52 };
53
54
55 static PyObject *
56 test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
57 {
58 PyObject *obj = Py_BuildValue("(ii)", 1, 2);
59 if (obj == _Py_NULL) {
60 return _Py_NULL;
61 }
62 Py_ssize_t refcnt = Py_REFCNT(obj);
63 assert(refcnt >= 1);
64
65 #ifndef Py_LIMITED_API
66 // gh-92138: For backward compatibility, functions of Python C API accepts
67 // "const PyObject*". Check that using it does not emit C++ compiler
68 // warnings.
69 const PyObject *const_obj = obj;
70 Py_INCREF(const_obj);
71 Py_DECREF(const_obj);
72 PyTypeObject *type = Py_TYPE(const_obj);
73 assert(Py_REFCNT(const_obj) == refcnt);
74 assert(type == &PyTuple_Type);
75 assert(PyTuple_GET_SIZE(const_obj) == 2);
76 PyObject *one = PyTuple_GET_ITEM(const_obj, 0);
77 assert(PyLong_AsLong(one) == 1);
78 #endif
79
80 // gh-92898: StrongRef doesn't inherit from PyObject but has an operator to
81 // cast to PyObject*.
82 StrongRef strong_ref(obj);
83 assert(Py_TYPE(strong_ref) == &PyTuple_Type);
84 assert(Py_REFCNT(strong_ref) == (refcnt + 1));
85 Py_INCREF(strong_ref);
86 Py_DECREF(strong_ref);
87
88 // gh-93442: Pass 0 as NULL for PyObject*
89 Py_XINCREF(0);
90 Py_XDECREF(0);
91 #if __cplusplus >= 201103
92 // Test nullptr passed as PyObject*
93 Py_XINCREF(nullptr);
94 Py_XDECREF(nullptr);
95 #endif
96
97 Py_DECREF(obj);
98 Py_RETURN_NONE;
99 }
100
101
102 static PyObject *
103 test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
104 {
105 PyObject *str = PyUnicode_FromString("abc");
106 if (str == _Py_NULL) {
107 return _Py_NULL;
108 }
109
110 assert(PyUnicode_Check(str));
111
112 assert(PyUnicode_GetLength(str) == 3);
113 assert(PyUnicode_ReadChar(str, 0) == 'a');
114 assert(PyUnicode_ReadChar(str, 1) == 'b');
115
116 #ifndef Py_LIMITED_API
117 assert(PyUnicode_GET_LENGTH(str) == 3);
118
119 // gh-92800: test PyUnicode_READ()
120 const void* data = PyUnicode_DATA(str);
121 assert(data != _Py_NULL);
122 int kind = PyUnicode_KIND(str);
123 assert(kind == PyUnicode_1BYTE_KIND);
124 assert(PyUnicode_READ(kind, data, 0) == 'a');
125
126 // gh-92800: test PyUnicode_READ() casts
127 const void* const_data = PyUnicode_DATA(str);
128 unsigned int ukind = static_cast<unsigned int>(kind);
129 assert(PyUnicode_READ(ukind, const_data, 2) == 'c');
130
131 assert(PyUnicode_READ_CHAR(str, 1) == 'b');
132 #endif
133
134 Py_DECREF(str);
135 Py_RETURN_NONE;
136 }
137
138 /* Test a `new`-allocated object with a virtual method.
139 * (https://github.com/python/cpython/issues/94731) */
140
141 class VirtualPyObject : public PyObject {
142 public:
143 VirtualPyObject();
144 virtual ~VirtualPyObject() {
145 delete [] internal_data;
146 --instance_count;
147 }
148 virtual void set_internal_data() {
149 internal_data[0] = 1;
150 }
151 static void dealloc(PyObject* o) {
152 delete static_cast<VirtualPyObject*>(o);
153 }
154
155 // Number of "living" instances
156 static int instance_count;
157 private:
158 // buffer that can get corrupted
159 int* internal_data;
160 };
161
162 int VirtualPyObject::instance_count = 0;
163
164 PyType_Slot VirtualPyObject_Slots[] = {
165 {Py_tp_free, (void*)VirtualPyObject::dealloc},
166 {0, _Py_NULL},
167 };
168
169 PyType_Spec VirtualPyObject_Spec = {
170 /* .name */ STR(MODULE_NAME) ".VirtualPyObject",
171 /* .basicsize */ sizeof(VirtualPyObject),
172 /* .itemsize */ 0,
173 /* .flags */ Py_TPFLAGS_DEFAULT,
174 /* .slots */ VirtualPyObject_Slots,
175 };
176
177 VirtualPyObject::VirtualPyObject() {
178 // Create a temporary type (just so we don't need to store it)
179 PyObject *type = PyType_FromSpec(&VirtualPyObject_Spec);
180 // no good way to signal failure from a C++ constructor, so use assert
181 // for error handling
182 assert(type);
183 assert(PyObject_Init(this, (PyTypeObject *)type));
184 Py_DECREF(type);
185 internal_data = new int[50];
186 ++instance_count;
187 }
188
189 static PyObject *
190 test_virtual_object(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
191 {
192 VirtualPyObject* obj = new VirtualPyObject();
193 obj->set_internal_data();
194 Py_DECREF(obj);
195 if (VirtualPyObject::instance_count != 0) {
196 return PyErr_Format(
197 PyExc_AssertionError,
198 "instance_count should be 0, got %d",
199 VirtualPyObject::instance_count);
200 }
201 Py_RETURN_NONE;
202 }
203
204 static PyMethodDef _testcppext_methods[] = {
205 {"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
206 {"test_api_casts", test_api_casts, METH_NOARGS, _Py_NULL},
207 {"test_unicode", test_unicode, METH_NOARGS, _Py_NULL},
208 {"test_virtual_object", test_virtual_object, METH_NOARGS, _Py_NULL},
209 // Note: _testcppext_exec currently runs all test functions directly.
210 // When adding a new one, add a call there.
211
212 {_Py_NULL, _Py_NULL, 0, _Py_NULL} /* sentinel */
213 };
214
215
216 static int
217 _testcppext_exec(PyObject *module)
218 {
219 if (PyModule_AddIntMacro(module, __cplusplus) < 0) {
220 return -1;
221 }
222
223 PyObject *result;
224
225 result = PyObject_CallMethod(module, "test_api_casts", "");
226 if (!result) return -1;
227 Py_DECREF(result);
228
229 result = PyObject_CallMethod(module, "test_unicode", "");
230 if (!result) return -1;
231 Py_DECREF(result);
232
233 result = PyObject_CallMethod(module, "test_virtual_object", "");
234 if (!result) return -1;
235 Py_DECREF(result);
236
237 // test Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR()
238 Py_BUILD_ASSERT(sizeof(int) == sizeof(unsigned int));
239 assert(Py_BUILD_ASSERT_EXPR(sizeof(int) == sizeof(unsigned int)) == 0);
240
241 return 0;
242 }
243
244 static PyModuleDef_Slot _testcppext_slots[] = {
245 {Py_mod_exec, reinterpret_cast<void*>(_testcppext_exec)},
246 {0, _Py_NULL}
247 };
248
249
250 PyDoc_STRVAR(_testcppext_doc, "C++ test extension.");
251
252 static struct PyModuleDef _testcppext_module = {
253 PyModuleDef_HEAD_INIT, // m_base
254 STR(MODULE_NAME), // m_name
255 _testcppext_doc, // m_doc
256 0, // m_size
257 _testcppext_methods, // m_methods
258 _testcppext_slots, // m_slots
259 _Py_NULL, // m_traverse
260 _Py_NULL, // m_clear
261 _Py_NULL, // m_free
262 };
263
264 #define _FUNC_NAME(NAME) PyInit_ ## NAME
265 #define FUNC_NAME(NAME) _FUNC_NAME(NAME)
266
267 PyMODINIT_FUNC
268 FUNC_NAME(MODULE_NAME)(void)
269 {
270 return PyModuleDef_Init(&_testcppext_module);
271 }