_testcppext.cpp 6.6 KB

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