Ananthusajeev190 commited on
Commit
1cd8342
·
verified ·
1 Parent(s): b39fe3e

Upload 3 files

Browse files
Files changed (3) hide show
  1. cpython_chunk_29.py +3242 -0
  2. cpython_chunk_33.py +0 -0
  3. cpython_chunk_4.py +0 -0
cpython_chunk_29.py ADDED
@@ -0,0 +1,3242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated from cpython_chunk_29.txt
2
+
3
+ TEXT_DATA = r"""
4
+ /*
5
+ * C Extension module to test Python interpreter C APIs.
6
+ *
7
+ * The 'test_*' functions exported by this module are run as part of the
8
+ * standard Python regression test, via Lib/test/test_capi.py.
9
+ */
10
+ // Include parts.h first since it takes care of NDEBUG and Py_BUILD_CORE macros
11
+ // and including Python.h.
12
+ //
13
+ // Several parts of this module are broken out into files in _testcapi/.
14
+ // Include definitions from there.
15
+ #include "_testcapi/parts.h"
16
+ #include "frameobject.h" // PyFrame_New()
17
+ #include "marshal.h" // PyMarshal_WriteLongToFile()
18
+ #include <float.h> // FLT_MAX
19
+ #include <signal.h>
20
+ #include <stddef.h> // offsetof()
21
+ #ifdef HAVE_SYS_WAIT_H
22
+ # include <sys/wait.h> // W_STOPCODE
23
+ #endif
24
+ #ifdef bool
25
+ # error "The public headers should not include <stdbool.h>, see gh-48924"
26
+ #endif
27
+ #include "_testcapi/util.h"
28
+ // Forward declarations
29
+ static struct PyModuleDef _testcapimodule;
30
+ // Module state
31
+ typedef struct {
32
+ PyObject *error; // _testcapi.error object
33
+ } testcapistate_t;
34
+ static testcapistate_t*
35
+ get_testcapi_state(PyObject *module)
36
+ {
37
+ void *state = PyModule_GetState(module);
38
+ assert(state != NULL);
39
+ return (testcapistate_t *)state;
40
+ }
41
+ static PyObject *
42
+ get_testerror(PyObject *self) {
43
+ testcapistate_t *state = get_testcapi_state(self);
44
+ return state->error;
45
+ }
46
+ static void
47
+ simple_object_dealloc(PyObject *self)
48
+ {
49
+ PyObject_Free(self);
50
+ }
51
+ /* Raise _testcapi.error with test_name + ": " + msg, and return NULL. */
52
+ static PyObject *
53
+ raiseTestError(PyObject *self, const char* test_name, const char* msg)
54
+ {
55
+ PyErr_Format(get_testerror(self), "%s: %s", test_name, msg);
56
+ return NULL;
57
+ }
58
+ /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
59
+ The ones derived from autoconf on the UNIX-like OSes can be relied
60
+ upon (in the absence of sloppy cross-compiling), but the Windows
61
+ platforms have these hardcoded. Better safe than sorry.
62
+ */
63
+ static PyObject*
64
+ sizeof_error(PyObject *self, const char* fatname, const char* typname,
65
+ int expected, int got)
66
+ {
67
+ PyErr_Format(get_testerror(self),
68
+ "%s #define == %d but sizeof(%s) == %d",
69
+ fatname, expected, typname, got);
70
+ return (PyObject*)NULL;
71
+ }
72
+ static PyObject*
73
+ test_config(PyObject *self, PyObject *Py_UNUSED(ignored))
74
+ {
75
+ #define CHECK_SIZEOF(FATNAME, TYPE) \
76
+ do { \
77
+ if (FATNAME != sizeof(TYPE)) { \
78
+ return sizeof_error(self, #FATNAME, #TYPE, FATNAME, sizeof(TYPE)); \
79
+ } \
80
+ } while (0)
81
+ CHECK_SIZEOF(SIZEOF_SHORT, short);
82
+ CHECK_SIZEOF(SIZEOF_INT, int);
83
+ CHECK_SIZEOF(SIZEOF_LONG, long);
84
+ CHECK_SIZEOF(SIZEOF_VOID_P, void*);
85
+ CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
86
+ CHECK_SIZEOF(SIZEOF_LONG_LONG, long long);
87
+ #undef CHECK_SIZEOF
88
+ Py_RETURN_NONE;
89
+ }
90
+ static PyObject*
91
+ test_sizeof_c_types(PyObject *self, PyObject *Py_UNUSED(ignored))
92
+ {
93
+ #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
94
+ #pragma GCC diagnostic push
95
+ #pragma GCC diagnostic ignored "-Wtype-limits"
96
+ #endif
97
+ #define CHECK_SIZEOF(TYPE, EXPECTED) \
98
+ do { \
99
+ if (EXPECTED != sizeof(TYPE)) { \
100
+ PyErr_Format(get_testerror(self), \
101
+ "sizeof(%s) = %u instead of %u", \
102
+ #TYPE, sizeof(TYPE), EXPECTED); \
103
+ return (PyObject*)NULL; \
104
+ } \
105
+ } while (0)
106
+ #define IS_SIGNED(TYPE) (((TYPE)-1) < (TYPE)0)
107
+ #define CHECK_SIGNNESS(TYPE, SIGNED) \
108
+ do { \
109
+ if (IS_SIGNED(TYPE) != SIGNED) { \
110
+ PyErr_Format(get_testerror(self), \
111
+ "%s signness is %i, instead of %i", \
112
+ #TYPE, IS_SIGNED(TYPE), SIGNED); \
113
+ return (PyObject*)NULL; \
114
+ } \
115
+ } while (0)
116
+ /* integer types */
117
+ CHECK_SIZEOF(Py_UCS1, 1);
118
+ CHECK_SIZEOF(Py_UCS2, 2);
119
+ CHECK_SIZEOF(Py_UCS4, 4);
120
+ CHECK_SIGNNESS(Py_UCS1, 0);
121
+ CHECK_SIGNNESS(Py_UCS2, 0);
122
+ CHECK_SIGNNESS(Py_UCS4, 0);
123
+ CHECK_SIZEOF(int32_t, 4);
124
+ CHECK_SIGNNESS(int32_t, 1);
125
+ CHECK_SIZEOF(uint32_t, 4);
126
+ CHECK_SIGNNESS(uint32_t, 0);
127
+ CHECK_SIZEOF(int64_t, 8);
128
+ CHECK_SIGNNESS(int64_t, 1);
129
+ CHECK_SIZEOF(uint64_t, 8);
130
+ CHECK_SIGNNESS(uint64_t, 0);
131
+ /* pointer/size types */
132
+ CHECK_SIZEOF(size_t, sizeof(void *));
133
+ CHECK_SIGNNESS(size_t, 0);
134
+ CHECK_SIZEOF(Py_ssize_t, sizeof(void *));
135
+ CHECK_SIGNNESS(Py_ssize_t, 1);
136
+ CHECK_SIZEOF(uintptr_t, sizeof(void *));
137
+ CHECK_SIGNNESS(uintptr_t, 0);
138
+ CHECK_SIZEOF(intptr_t, sizeof(void *));
139
+ CHECK_SIGNNESS(intptr_t, 1);
140
+ Py_RETURN_NONE;
141
+ #undef IS_SIGNED
142
+ #undef CHECK_SIGNESS
143
+ #undef CHECK_SIZEOF
144
+ #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
145
+ #pragma GCC diagnostic pop
146
+ #endif
147
+ }
148
+ /* Issue #4701: Check that PyObject_Hash implicitly calls
149
+ * PyType_Ready if it hasn't already been called
150
+ */
151
+ static PyTypeObject _HashInheritanceTester_Type = {
152
+ PyVarObject_HEAD_INIT(NULL, 0)
153
+ "hashinheritancetester", /* Name of this type */
154
+ sizeof(PyObject), /* Basic object size */
155
+ 0, /* Item size for varobject */
156
+ simple_object_dealloc, /* tp_dealloc */
157
+ 0, /* tp_vectorcall_offset */
158
+ 0, /* tp_getattr */
159
+ 0, /* tp_setattr */
160
+ 0, /* tp_as_async */
161
+ 0, /* tp_repr */
162
+ 0, /* tp_as_number */
163
+ 0, /* tp_as_sequence */
164
+ 0, /* tp_as_mapping */
165
+ 0, /* tp_hash */
166
+ 0, /* tp_call */
167
+ 0, /* tp_str */
168
+ PyObject_GenericGetAttr, /* tp_getattro */
169
+ 0, /* tp_setattro */
170
+ 0, /* tp_as_buffer */
171
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
172
+ 0, /* tp_doc */
173
+ 0, /* tp_traverse */
174
+ 0, /* tp_clear */
175
+ 0, /* tp_richcompare */
176
+ 0, /* tp_weaklistoffset */
177
+ 0, /* tp_iter */
178
+ 0, /* tp_iternext */
179
+ 0, /* tp_methods */
180
+ 0, /* tp_members */
181
+ 0, /* tp_getset */
182
+ 0, /* tp_base */
183
+ 0, /* tp_dict */
184
+ 0, /* tp_descr_get */
185
+ 0, /* tp_descr_set */
186
+ 0, /* tp_dictoffset */
187
+ 0, /* tp_init */
188
+ 0, /* tp_alloc */
189
+ PyType_GenericNew, /* tp_new */
190
+ };
191
+ static PyObject*
192
+ pycompilestring(PyObject* self, PyObject *obj) {
193
+ if (PyBytes_CheckExact(obj) == 0) {
194
+ PyErr_SetString(PyExc_ValueError, "Argument must be a bytes object");
195
+ return NULL;
196
+ }
197
+ const char *the_string = PyBytes_AsString(obj);
198
+ if (the_string == NULL) {
199
+ return NULL;
200
+ }
201
+ return Py_CompileString(the_string, "<string>", Py_file_input);
202
+ }
203
+ static PyObject*
204
+ test_lazy_hash_inheritance(PyObject* self, PyObject *Py_UNUSED(ignored))
205
+ {
206
+ PyTypeObject *type;
207
+ PyObject *obj;
208
+ Py_hash_t hash;
209
+ type = &_HashInheritanceTester_Type;
210
+ if (type->tp_dict != NULL)
211
+ /* The type has already been initialized. This probably means
212
+ -R is being used. */
213
+ Py_RETURN_NONE;
214
+ obj = PyObject_New(PyObject, type);
215
+ if (obj == NULL) {
216
+ PyErr_Clear();
217
+ PyErr_SetString(
218
+ get_testerror(self),
219
+ "test_lazy_hash_inheritance: failed to create object");
220
+ return NULL;
221
+ }
222
+ if (type->tp_dict != NULL) {
223
+ PyErr_SetString(
224
+ get_testerror(self),
225
+ "test_lazy_hash_inheritance: type initialised too soon");
226
+ Py_DECREF(obj);
227
+ return NULL;
228
+ }
229
+ hash = PyObject_Hash(obj);
230
+ if ((hash == -1) && PyErr_Occurred()) {
231
+ PyErr_Clear();
232
+ PyErr_SetString(
233
+ get_testerror(self),
234
+ "test_lazy_hash_inheritance: could not hash object");
235
+ Py_DECREF(obj);
236
+ return NULL;
237
+ }
238
+ if (type->tp_dict == NULL) {
239
+ PyErr_SetString(
240
+ get_testerror(self),
241
+ "test_lazy_hash_inheritance: type not initialised by hash()");
242
+ Py_DECREF(obj);
243
+ return NULL;
244
+ }
245
+ if (type->tp_hash != PyType_Type.tp_hash) {
246
+ PyErr_SetString(
247
+ get_testerror(self),
248
+ "test_lazy_hash_inheritance: unexpected hash function");
249
+ Py_DECREF(obj);
250
+ return NULL;
251
+ }
252
+ Py_DECREF(obj);
253
+ Py_RETURN_NONE;
254
+ }
255
+ static PyObject *
256
+ return_none(void *unused)
257
+ {
258
+ Py_RETURN_NONE;
259
+ }
260
+ static PyObject *
261
+ raise_error(void *unused)
262
+ {
263
+ PyErr_SetNone(PyExc_ValueError);
264
+ return NULL;
265
+ }
266
+ static PyObject *
267
+ py_buildvalue(PyObject *self, PyObject *args)
268
+ {
269
+ const char *fmt;
270
+ PyObject *objs[10] = {NULL};
271
+ if (!PyArg_ParseTuple(args, "s|OOOOOOOOOO", &fmt,
272
+ &objs[0], &objs[1], &objs[2], &objs[3], &objs[4],
273
+ &objs[5], &objs[6], &objs[7], &objs[8], &objs[9]))
274
+ {
275
+ return NULL;
276
+ }
277
+ for(int i = 0; i < 10; i++) {
278
+ NULLABLE(objs[i]);
279
+ }
280
+ return Py_BuildValue(fmt,
281
+ objs[0], objs[1], objs[2], objs[3], objs[4],
282
+ objs[5], objs[6], objs[7], objs[8], objs[9]);
283
+ }
284
+ static PyObject *
285
+ py_buildvalue_ints(PyObject *self, PyObject *args)
286
+ {
287
+ const char *fmt;
288
+ unsigned int values[10] = {0};
289
+ if (!PyArg_ParseTuple(args, "s|IIIIIIIIII", &fmt,
290
+ &values[0], &values[1], &values[2], &values[3], &values[4],
291
+ &values[5], &values[6], &values[7], &values[8], &values[9]))
292
+ {
293
+ return NULL;
294
+ }
295
+ return Py_BuildValue(fmt,
296
+ values[0], values[1], values[2], values[3], values[4],
297
+ values[5], values[6], values[7], values[8], values[9]);
298
+ }
299
+ static int
300
+ test_buildvalue_N_error(PyObject *self, const char *fmt)
301
+ {
302
+ PyObject *arg, *res;
303
+ arg = PyList_New(0);
304
+ if (arg == NULL) {
305
+ return -1;
306
+ }
307
+ Py_INCREF(arg);
308
+ res = Py_BuildValue(fmt, return_none, NULL, arg);
309
+ if (res == NULL) {
310
+ return -1;
311
+ }
312
+ Py_DECREF(res);
313
+ if (Py_REFCNT(arg) != 1) {
314
+ PyErr_Format(get_testerror(self), "test_buildvalue_N: "
315
+ "arg was not decrefed in successful "
316
+ "Py_BuildValue(\"%s\")", fmt);
317
+ return -1;
318
+ }
319
+ Py_INCREF(arg);
320
+ res = Py_BuildValue(fmt, raise_error, NULL, arg);
321
+ if (res != NULL || !PyErr_Occurred()) {
322
+ PyErr_Format(get_testerror(self), "test_buildvalue_N: "
323
+ "Py_BuildValue(\"%s\") didn't complain", fmt);
324
+ return -1;
325
+ }
326
+ PyErr_Clear();
327
+ if (Py_REFCNT(arg) != 1) {
328
+ PyErr_Format(get_testerror(self), "test_buildvalue_N: "
329
+ "arg was not decrefed in failed "
330
+ "Py_BuildValue(\"%s\")", fmt);
331
+ return -1;
332
+ }
333
+ Py_DECREF(arg);
334
+ return 0;
335
+ }
336
+ static PyObject *
337
+ test_buildvalue_N(PyObject *self, PyObject *Py_UNUSED(ignored))
338
+ {
339
+ PyObject *arg, *res;
340
+ arg = PyList_New(0);
341
+ if (arg == NULL) {
342
+ return NULL;
343
+ }
344
+ Py_INCREF(arg);
345
+ res = Py_BuildValue("N", arg);
346
+ if (res == NULL) {
347
+ return NULL;
348
+ }
349
+ if (res != arg) {
350
+ return raiseTestError(self, "test_buildvalue_N",
351
+ "Py_BuildValue(\"N\") returned wrong result");
352
+ }
353
+ if (Py_REFCNT(arg) != 2) {
354
+ return raiseTestError(self, "test_buildvalue_N",
355
+ "arg was not decrefed in Py_BuildValue(\"N\")");
356
+ }
357
+ Py_DECREF(res);
358
+ Py_DECREF(arg);
359
+ if (test_buildvalue_N_error(self, "O&N") < 0)
360
+ return NULL;
361
+ if (test_buildvalue_N_error(self, "(O&N)") < 0)
362
+ return NULL;
363
+ if (test_buildvalue_N_error(self, "[O&N]") < 0)
364
+ return NULL;
365
+ if (test_buildvalue_N_error(self, "{O&N}") < 0)
366
+ return NULL;
367
+ if (test_buildvalue_N_error(self, "{()O&(())N}") < 0)
368
+ return NULL;
369
+ Py_RETURN_NONE;
370
+ }
371
+ static PyObject *
372
+ test_buildvalue_p(PyObject *self, PyObject *Py_UNUSED(ignored))
373
+ {
374
+ PyObject *res = Py_BuildValue("p", 3);
375
+ if (res == NULL) {
376
+ return NULL;
377
+ }
378
+ if (!Py_IsTrue(res)) {
379
+ Py_DECREF(res);
380
+ return raiseTestError(self, "test_buildvalue_p", "Py_BuildValue(\"p\", 3) returned wrong result");
381
+ }
382
+ Py_DECREF(res);
383
+ res = Py_BuildValue("p", 0);
384
+ if (res == NULL) {
385
+ return NULL;
386
+ }
387
+ if (!Py_IsFalse(res)) {
388
+ Py_DECREF(res);
389
+ return raiseTestError(self, "test_buildvalue_p", "Py_BuildValue(\"p\", 0) returned wrong result");
390
+ }
391
+ Py_DECREF(res);
392
+ Py_RETURN_NONE;
393
+ }
394
+ static PyObject *
395
+ pyobject_repr_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
396
+ {
397
+ return PyObject_Repr(NULL);
398
+ }
399
+ static PyObject *
400
+ pyobject_str_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
401
+ {
402
+ return PyObject_Str(NULL);
403
+ }
404
+ static PyObject *
405
+ pyobject_bytes_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
406
+ {
407
+ return PyObject_Bytes(NULL);
408
+ }
409
+ static PyObject *
410
+ set_errno(PyObject *self, PyObject *args)
411
+ {
412
+ int new_errno;
413
+ if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
414
+ return NULL;
415
+ errno = new_errno;
416
+ Py_RETURN_NONE;
417
+ }
418
+ /* test_thread_state spawns a thread of its own, and that thread releases
419
+ * `thread_done` when it's finished. The driver code has to know when the
420
+ * thread finishes, because the thread uses a PyObject (the callable) that
421
+ * may go away when the driver finishes. The former lack of this explicit
422
+ * synchronization caused rare segfaults, so rare that they were seen only
423
+ * on a Mac buildbot (although they were possible on any box).
424
+ */
425
+ static PyThread_type_lock thread_done = NULL;
426
+ static int
427
+ _make_call(void *callable)
428
+ {
429
+ PyObject *rc;
430
+ int success;
431
+ PyGILState_STATE s = PyGILState_Ensure();
432
+ rc = PyObject_CallNoArgs((PyObject *)callable);
433
+ success = (rc != NULL);
434
+ Py_XDECREF(rc);
435
+ PyGILState_Release(s);
436
+ return success;
437
+ }
438
+ /* Same thing, but releases `thread_done` when it returns. This variant
439
+ * should be called only from threads spawned by test_thread_state().
440
+ */
441
+ static void
442
+ _make_call_from_thread(void *callable)
443
+ {
444
+ _make_call(callable);
445
+ PyThread_release_lock(thread_done);
446
+ }
447
+ static PyObject *
448
+ test_thread_state(PyObject *self, PyObject *args)
449
+ {
450
+ PyObject *fn;
451
+ int success = 1;
452
+ if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
453
+ return NULL;
454
+ if (!PyCallable_Check(fn)) {
455
+ PyErr_Format(PyExc_TypeError, "'%T' object is not callable", fn);
456
+ return NULL;
457
+ }
458
+ thread_done = PyThread_allocate_lock();
459
+ if (thread_done == NULL)
460
+ return PyErr_NoMemory();
461
+ PyThread_acquire_lock(thread_done, 1);
462
+ /* Start a new thread with our callback. */
463
+ PyThread_start_new_thread(_make_call_from_thread, fn);
464
+ /* Make the callback with the thread lock held by this thread */
465
+ success &= _make_call(fn);
466
+ /* Do it all again, but this time with the thread-lock released */
467
+ Py_BEGIN_ALLOW_THREADS
468
+ success &= _make_call(fn);
469
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
470
+ Py_END_ALLOW_THREADS
471
+ /* And once more with and without a thread
472
+ XXX - should use a lock and work out exactly what we are trying
473
+ to test <wink>
474
+ */
475
+ Py_BEGIN_ALLOW_THREADS
476
+ PyThread_start_new_thread(_make_call_from_thread, fn);
477
+ success &= _make_call(fn);
478
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
479
+ Py_END_ALLOW_THREADS
480
+ /* Release lock we acquired above. This is required on HP-UX. */
481
+ PyThread_release_lock(thread_done);
482
+ PyThread_free_lock(thread_done);
483
+ if (!success)
484
+ return NULL;
485
+ Py_RETURN_NONE;
486
+ }
487
+ static PyObject *
488
+ gilstate_ensure_release(PyObject *module, PyObject *Py_UNUSED(ignored))
489
+ {
490
+ PyGILState_STATE state = PyGILState_Ensure();
491
+ PyGILState_Release(state);
492
+ Py_RETURN_NONE;
493
+ }
494
+ #ifndef MS_WINDOWS
495
+ static PyThread_type_lock wait_done = NULL;
496
+ static void wait_for_lock(void *unused) {
497
+ PyThread_acquire_lock(wait_done, 1);
498
+ PyThread_release_lock(wait_done);
499
+ PyThread_free_lock(wait_done);
500
+ wait_done = NULL;
501
+ }
502
+ // These can be used to test things that care about the existence of another
503
+ // thread that the threading module doesn't know about.
504
+ static PyObject *
505
+ spawn_pthread_waiter(PyObject *self, PyObject *Py_UNUSED(ignored))
506
+ {
507
+ if (wait_done) {
508
+ PyErr_SetString(PyExc_RuntimeError, "thread already running");
509
+ return NULL;
510
+ }
511
+ wait_done = PyThread_allocate_lock();
512
+ if (wait_done == NULL)
513
+ return PyErr_NoMemory();
514
+ PyThread_acquire_lock(wait_done, 1);
515
+ PyThread_start_new_thread(wait_for_lock, NULL);
516
+ Py_RETURN_NONE;
517
+ }
518
+ static PyObject *
519
+ end_spawned_pthread(PyObject *self, PyObject *Py_UNUSED(ignored))
520
+ {
521
+ if (!wait_done) {
522
+ PyErr_SetString(PyExc_RuntimeError, "call _spawn_pthread_waiter 1st");
523
+ return NULL;
524
+ }
525
+ PyThread_release_lock(wait_done);
526
+ Py_RETURN_NONE;
527
+ }
528
+ #endif // not MS_WINDOWS
529
+ /* test Py_AddPendingCalls using threads */
530
+ static int _pending_callback(void *arg)
531
+ {
532
+ /* we assume the argument is callable object to which we own a reference */
533
+ PyObject *callable = (PyObject *)arg;
534
+ PyObject *r = PyObject_CallNoArgs(callable);
535
+ Py_DECREF(callable);
536
+ Py_XDECREF(r);
537
+ return r != NULL ? 0 : -1;
538
+ }
539
+ /* The following requests n callbacks to _pending_callback. It can be
540
+ * run from any python thread.
541
+ */
542
+ static PyObject *
543
+ pending_threadfunc(PyObject *self, PyObject *arg, PyObject *kwargs)
544
+ {
545
+ static char *kwlist[] = {"callback", "num",
546
+ "blocking", "ensure_added", NULL};
547
+ PyObject *callable;
548
+ unsigned int num = 1;
549
+ int blocking = 0;
550
+ int ensure_added = 0;
551
+ if (!PyArg_ParseTupleAndKeywords(arg, kwargs,
552
+ "O|I$pp:_pending_threadfunc", kwlist,
553
+ &callable, &num, &blocking, &ensure_added))
554
+ {
555
+ return NULL;
556
+ }
557
+ /* create the reference for the callbackwhile we hold the lock */
558
+ for (unsigned int i = 0; i < num; i++) {
559
+ Py_INCREF(callable);
560
+ }
561
+ PyThreadState *save_tstate = NULL;
562
+ if (!blocking) {
563
+ save_tstate = PyEval_SaveThread();
564
+ }
565
+ unsigned int num_added = 0;
566
+ for (; num_added < num; num_added++) {
567
+ if (ensure_added) {
568
+ int r;
569
+ do {
570
+ r = Py_AddPendingCall(&_pending_callback, callable);
571
+ } while (r < 0);
572
+ }
573
+ else {
574
+ if (Py_AddPendingCall(&_pending_callback, callable) < 0) {
575
+ break;
576
+ }
577
+ }
578
+ }
579
+ if (!blocking) {
580
+ PyEval_RestoreThread(save_tstate);
581
+ }
582
+ for (unsigned int i = num_added; i < num; i++) {
583
+ Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
584
+ }
585
+ /* The callable is decref'ed above in each added _pending_callback(). */
586
+ return PyLong_FromUnsignedLong((unsigned long)num_added);
587
+ }
588
+ /* Coverage testing of capsule objects. */
589
+ static const char *capsule_name = "capsule name";
590
+ static char *capsule_pointer = "capsule pointer";
591
+ static char *capsule_context = "capsule context";
592
+ static const char *capsule_error = NULL;
593
+ static int
594
+ capsule_destructor_call_count = 0;
595
+ static void
596
+ capsule_destructor(PyObject *o) {
597
+ capsule_destructor_call_count++;
598
+ if (PyCapsule_GetContext(o) != capsule_context) {
599
+ capsule_error = "context did not match in destructor!";
600
+ } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
601
+ capsule_error = "destructor did not match in destructor! (woah!)";
602
+ } else if (PyCapsule_GetName(o) != capsule_name) {
603
+ capsule_error = "name did not match in destructor!";
604
+ } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
605
+ capsule_error = "pointer did not match in destructor!";
606
+ }
607
+ }
608
+ typedef struct {
609
+ char *name;
610
+ char *module;
611
+ char *attribute;
612
+ } known_capsule;
613
+ static PyObject *
614
+ test_capsule(PyObject *self, PyObject *Py_UNUSED(ignored))
615
+ {
616
+ PyObject *object;
617
+ const char *error = NULL;
618
+ void *pointer;
619
+ void *pointer2;
620
+ known_capsule known_capsules[] = {
621
+ #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
622
+ KNOWN_CAPSULE("_socket", "CAPI"),
623
+ KNOWN_CAPSULE("_curses", "_C_API"),
624
+ KNOWN_CAPSULE("datetime", "datetime_CAPI"),
625
+ { NULL, NULL },
626
+ };
627
+ known_capsule *known = &known_capsules[0];
628
+ #define FAIL(x) \
629
+ do { \
630
+ error = (x); \
631
+ goto exit; \
632
+ } while (0)
633
+ #define CHECK_DESTRUCTOR \
634
+ do { \
635
+ if (capsule_error) { \
636
+ FAIL(capsule_error); \
637
+ } \
638
+ else if (!capsule_destructor_call_count) { \
639
+ FAIL("destructor not called!"); \
640
+ } \
641
+ capsule_destructor_call_count = 0; \
642
+ } while (0)
643
+ object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
644
+ PyCapsule_SetContext(object, capsule_context);
645
+ capsule_destructor(object);
646
+ CHECK_DESTRUCTOR;
647
+ Py_DECREF(object);
648
+ CHECK_DESTRUCTOR;
649
+ object = PyCapsule_New(known, "ignored", NULL);
650
+ PyCapsule_SetPointer(object, capsule_pointer);
651
+ PyCapsule_SetName(object, capsule_name);
652
+ PyCapsule_SetDestructor(object, capsule_destructor);
653
+ PyCapsule_SetContext(object, capsule_context);
654
+ capsule_destructor(object);
655
+ CHECK_DESTRUCTOR;
656
+ /* intentionally access using the wrong name */
657
+ pointer2 = PyCapsule_GetPointer(object, "the wrong name");
658
+ if (!PyErr_Occurred()) {
659
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
660
+ }
661
+ PyErr_Clear();
662
+ if (pointer2) {
663
+ if (pointer2 == capsule_pointer) {
664
+ FAIL("PyCapsule_GetPointer should not have"
665
+ " returned the internal pointer!");
666
+ } else {
667
+ FAIL("PyCapsule_GetPointer should have "
668
+ "returned NULL pointer but did not!");
669
+ }
670
+ }
671
+ PyCapsule_SetDestructor(object, NULL);
672
+ Py_DECREF(object);
673
+ if (capsule_destructor_call_count) {
674
+ FAIL("destructor called when it should not have been!");
675
+ }
676
+ for (known = &known_capsules[0]; known->module != NULL; known++) {
677
+ /* yeah, ordinarily I wouldn't do this either,
678
+ but it's fine for this test harness.
679
+ */
680
+ static char buffer[256];
681
+ #undef FAIL
682
+ #define FAIL(x) \
683
+ do { \
684
+ sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
685
+ x, known->module, known->attribute); \
686
+ error = buffer; \
687
+ goto exit; \
688
+ } while (0)
689
+ PyObject *module = PyImport_ImportModule(known->module);
690
+ if (module) {
691
+ pointer = PyCapsule_Import(known->name, 0);
692
+ if (!pointer) {
693
+ Py_DECREF(module);
694
+ FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
695
+ }
696
+ object = PyObject_GetAttrString(module, known->attribute);
697
+ if (!object) {
698
+ Py_DECREF(module);
699
+ return NULL;
700
+ }
701
+ pointer2 = PyCapsule_GetPointer(object,
702
+ "weebles wobble but they don't fall down");
703
+ if (!PyErr_Occurred()) {
704
+ Py_DECREF(object);
705
+ Py_DECREF(module);
706
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
707
+ }
708
+ PyErr_Clear();
709
+ if (pointer2) {
710
+ Py_DECREF(module);
711
+ Py_DECREF(object);
712
+ if (pointer2 == pointer) {
713
+ FAIL("PyCapsule_GetPointer should not have"
714
+ " returned its internal pointer!");
715
+ } else {
716
+ FAIL("PyCapsule_GetPointer should have"
717
+ " returned NULL pointer but did not!");
718
+ }
719
+ }
720
+ Py_DECREF(object);
721
+ Py_DECREF(module);
722
+ }
723
+ else
724
+ PyErr_Clear();
725
+ }
726
+ exit:
727
+ if (error) {
728
+ return raiseTestError(self, "test_capsule", error);
729
+ }
730
+ Py_RETURN_NONE;
731
+ #undef FAIL
732
+ }
733
+ #ifdef HAVE_GETTIMEOFDAY
734
+ /* Profiling of integer performance */
735
+ static void print_delta(int test, struct timeval *s, struct timeval *e)
736
+ {
737
+ e->tv_sec -= s->tv_sec;
738
+ e->tv_usec -= s->tv_usec;
739
+ if (e->tv_usec < 0) {
740
+ e->tv_sec -=1;
741
+ e->tv_usec += 1000000;
742
+ }
743
+ printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
744
+ }
745
+ static PyObject *
746
+ profile_int(PyObject *self, PyObject* args)
747
+ {
748
+ int i, k;
749
+ struct timeval start, stop;
750
+ PyObject *single, **multiple, *op1, *result;
751
+ /* Test 1: Allocate and immediately deallocate
752
+ many small integers */
753
+ gettimeofday(&start, NULL);
754
+ for(k=0; k < 20000; k++)
755
+ for(i=0; i < 1000; i++) {
756
+ single = PyLong_FromLong(i);
757
+ Py_DECREF(single);
758
+ }
759
+ gettimeofday(&stop, NULL);
760
+ print_delta(1, &start, &stop);
761
+ /* Test 2: Allocate and immediately deallocate
762
+ many large integers */
763
+ gettimeofday(&start, NULL);
764
+ for(k=0; k < 20000; k++)
765
+ for(i=0; i < 1000; i++) {
766
+ single = PyLong_FromLong(i+1000000);
767
+ Py_DECREF(single);
768
+ }
769
+ gettimeofday(&stop, NULL);
770
+ print_delta(2, &start, &stop);
771
+ /* Test 3: Allocate a few integers, then release
772
+ them all simultaneously. */
773
+ multiple = malloc(sizeof(PyObject*) * 1000);
774
+ if (multiple == NULL)
775
+ return PyErr_NoMemory();
776
+ gettimeofday(&start, NULL);
777
+ for(k=0; k < 20000; k++) {
778
+ for(i=0; i < 1000; i++) {
779
+ multiple[i] = PyLong_FromLong(i+1000000);
780
+ }
781
+ for(i=0; i < 1000; i++) {
782
+ Py_DECREF(multiple[i]);
783
+ }
784
+ }
785
+ gettimeofday(&stop, NULL);
786
+ print_delta(3, &start, &stop);
787
+ free(multiple);
788
+ /* Test 4: Allocate many integers, then release
789
+ them all simultaneously. */
790
+ multiple = malloc(sizeof(PyObject*) * 1000000);
791
+ if (multiple == NULL)
792
+ return PyErr_NoMemory();
793
+ gettimeofday(&start, NULL);
794
+ for(k=0; k < 20; k++) {
795
+ for(i=0; i < 1000000; i++) {
796
+ multiple[i] = PyLong_FromLong(i+1000000);
797
+ }
798
+ for(i=0; i < 1000000; i++) {
799
+ Py_DECREF(multiple[i]);
800
+ }
801
+ }
802
+ gettimeofday(&stop, NULL);
803
+ print_delta(4, &start, &stop);
804
+ free(multiple);
805
+ /* Test 5: Allocate many integers < 32000 */
806
+ multiple = malloc(sizeof(PyObject*) * 1000000);
807
+ if (multiple == NULL)
808
+ return PyErr_NoMemory();
809
+ gettimeofday(&start, NULL);
810
+ for(k=0; k < 10; k++) {
811
+ for(i=0; i < 1000000; i++) {
812
+ multiple[i] = PyLong_FromLong(i+1000);
813
+ }
814
+ for(i=0; i < 1000000; i++) {
815
+ Py_DECREF(multiple[i]);
816
+ }
817
+ }
818
+ gettimeofday(&stop, NULL);
819
+ print_delta(5, &start, &stop);
820
+ free(multiple);
821
+ /* Test 6: Perform small int addition */
822
+ op1 = PyLong_FromLong(1);
823
+ gettimeofday(&start, NULL);
824
+ for(i=0; i < 10000000; i++) {
825
+ result = PyNumber_Add(op1, op1);
826
+ Py_DECREF(result);
827
+ }
828
+ gettimeofday(&stop, NULL);
829
+ Py_DECREF(op1);
830
+ print_delta(6, &start, &stop);
831
+ /* Test 7: Perform medium int addition */
832
+ op1 = PyLong_FromLong(1000);
833
+ if (op1 == NULL)
834
+ return NULL;
835
+ gettimeofday(&start, NULL);
836
+ for(i=0; i < 10000000; i++) {
837
+ result = PyNumber_Add(op1, op1);
838
+ Py_XDECREF(result);
839
+ }
840
+ gettimeofday(&stop, NULL);
841
+ Py_DECREF(op1);
842
+ print_delta(7, &start, &stop);
843
+ Py_RETURN_NONE;
844
+ }
845
+ #endif
846
+ /* Issue 6012 */
847
+ static PyObject *str1, *str2;
848
+ static int
849
+ failing_converter(PyObject *obj, void *arg)
850
+ {
851
+ /* Clone str1, then let the conversion fail. */
852
+ assert(str1);
853
+ str2 = Py_NewRef(str1);
854
+ return 0;
855
+ }
856
+ static PyObject*
857
+ argparsing(PyObject *o, PyObject *args)
858
+ {
859
+ PyObject *res;
860
+ str1 = str2 = NULL;
861
+ if (!PyArg_ParseTuple(args, "O&O&",
862
+ PyUnicode_FSConverter, &str1,
863
+ failing_converter, &str2)) {
864
+ if (!str2)
865
+ /* argument converter not called? */
866
+ return NULL;
867
+ /* Should be 1 */
868
+ res = PyLong_FromSsize_t(Py_REFCNT(str2));
869
+ Py_DECREF(str2);
870
+ PyErr_Clear();
871
+ return res;
872
+ }
873
+ Py_RETURN_NONE;
874
+ }
875
+ /* To test that the result of PyCode_NewEmpty has the right members. */
876
+ static PyObject *
877
+ code_newempty(PyObject *self, PyObject *args)
878
+ {
879
+ const char *filename;
880
+ const char *funcname;
881
+ int firstlineno;
882
+ if (!PyArg_ParseTuple(args, "ssi:code_newempty",
883
+ &filename, &funcname, &firstlineno))
884
+ return NULL;
885
+ return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
886
+ }
887
+ static PyObject *
888
+ make_memoryview_from_NULL_pointer(PyObject *self, PyObject *Py_UNUSED(ignored))
889
+ {
890
+ Py_buffer info;
891
+ if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
892
+ return NULL;
893
+ return PyMemoryView_FromBuffer(&info);
894
+ }
895
+ static PyObject *
896
+ buffer_fill_info(PyObject *self, PyObject *args)
897
+ {
898
+ Py_buffer info;
899
+ const char *data;
900
+ Py_ssize_t size;
901
+ int readonly;
902
+ int flags;
903
+ if (!PyArg_ParseTuple(args, "s#ii:buffer_fill_info",
904
+ &data, &size, &readonly, &flags)) {
905
+ return NULL;
906
+ }
907
+ if (PyBuffer_FillInfo(&info, NULL, (void *)data, size, readonly, flags) < 0) {
908
+ return NULL;
909
+ }
910
+ return PyMemoryView_FromBuffer(&info);
911
+ }
912
+ static PyObject *
913
+ test_from_contiguous(PyObject* self, PyObject *Py_UNUSED(ignored))
914
+ {
915
+ int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
916
+ int init[5] = {0, 1, 2, 3, 4};
917
+ Py_ssize_t itemsize = sizeof(int);
918
+ Py_ssize_t shape = 5;
919
+ Py_ssize_t strides = 2 * itemsize;
920
+ Py_buffer view = {
921
+ data,
922
+ NULL,
923
+ 5 * itemsize,
924
+ itemsize,
925
+ 1,
926
+ 1,
927
+ NULL,
928
+ &shape,
929
+ &strides,
930
+ NULL,
931
+ NULL
932
+ };
933
+ int *ptr;
934
+ int i;
935
+ PyBuffer_FromContiguous(&view, init, view.len, 'C');
936
+ ptr = view.buf;
937
+ for (i = 0; i < 5; i++) {
938
+ if (ptr[2*i] != i) {
939
+ PyErr_SetString(get_testerror(self),
940
+ "test_from_contiguous: incorrect result");
941
+ return NULL;
942
+ }
943
+ }
944
+ view.buf = &data[8];
945
+ view.strides[0] = -2 * itemsize;
946
+ PyBuffer_FromContiguous(&view, init, view.len, 'C');
947
+ ptr = view.buf;
948
+ for (i = 0; i < 5; i++) {
949
+ if (*(ptr-2*i) != i) {
950
+ PyErr_SetString(get_testerror(self),
951
+ "test_from_contiguous: incorrect result");
952
+ return NULL;
953
+ }
954
+ }
955
+ Py_RETURN_NONE;
956
+ }
957
+ #if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
958
+ static PyObject *
959
+ test_pep3118_obsolete_write_locks(PyObject* self, PyObject *Py_UNUSED(ignored))
960
+ {
961
+ PyObject *b;
962
+ char *dummy[1];
963
+ int ret, match;
964
+ /* PyBuffer_FillInfo() */
965
+ ret = PyBuffer_FillInfo(NULL, NULL, dummy, 1, 0, PyBUF_SIMPLE);
966
+ match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
967
+ PyErr_Clear();
968
+ if (ret != -1 || match == 0)
969
+ goto error;
970
+ /* bytesiobuf_getbuffer() */
971
+ PyTypeObject *type = (PyTypeObject *)PyImport_ImportModuleAttrString(
972
+ "_io",
973
+ "_BytesIOBuffer");
974
+ if (type == NULL) {
975
+ return NULL;
976
+ }
977
+ b = type->tp_alloc(type, 0);
978
+ Py_DECREF(type);
979
+ if (b == NULL) {
980
+ return NULL;
981
+ }
982
+ ret = PyObject_GetBuffer(b, NULL, PyBUF_SIMPLE);
983
+ Py_DECREF(b);
984
+ match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
985
+ PyErr_Clear();
986
+ if (ret != -1 || match == 0)
987
+ goto error;
988
+ Py_RETURN_NONE;
989
+ error:
990
+ PyErr_SetString(get_testerror(self),
991
+ "test_pep3118_obsolete_write_locks: failure");
992
+ return NULL;
993
+ }
994
+ #endif
995
+ /* This tests functions that historically supported write locks. It is
996
+ wrong to call getbuffer() with view==NULL and a compliant getbufferproc
997
+ is entitled to segfault in that case. */
998
+ static PyObject *
999
+ getbuffer_with_null_view(PyObject* self, PyObject *obj)
1000
+ {
1001
+ if (PyObject_GetBuffer(obj, NULL, PyBUF_SIMPLE) < 0)
1002
+ return NULL;
1003
+ Py_RETURN_NONE;
1004
+ }
1005
+ /* PyBuffer_SizeFromFormat() */
1006
+ static PyObject *
1007
+ test_PyBuffer_SizeFromFormat(PyObject *self, PyObject *args)
1008
+ {
1009
+ const char *format;
1010
+ if (!PyArg_ParseTuple(args, "s:test_PyBuffer_SizeFromFormat",
1011
+ &format)) {
1012
+ return NULL;
1013
+ }
1014
+ RETURN_SIZE(PyBuffer_SizeFromFormat(format));
1015
+ }
1016
+ /* Test that the fatal error from not having a current thread doesn't
1017
+ cause an infinite loop. Run via Lib/test/test_capi.py */
1018
+ static PyObject *
1019
+ crash_no_current_thread(PyObject *self, PyObject *Py_UNUSED(ignored))
1020
+ {
1021
+ Py_BEGIN_ALLOW_THREADS
1022
+ /* Using PyThreadState_Get() directly allows the test to pass in
1023
+ !pydebug mode. However, the test only actually tests anything
1024
+ in pydebug mode, since that's where the infinite loop was in
1025
+ the first place. */
1026
+ PyThreadState_Get();
1027
+ Py_END_ALLOW_THREADS
1028
+ return NULL;
1029
+ }
1030
+ /* Test that the GILState thread and the "current" thread match. */
1031
+ static PyObject *
1032
+ test_current_tstate_matches(PyObject *self, PyObject *Py_UNUSED(ignored))
1033
+ {
1034
+ PyThreadState *orig_tstate = PyThreadState_Get();
1035
+ if (orig_tstate != PyGILState_GetThisThreadState()) {
1036
+ PyErr_SetString(PyExc_RuntimeError,
1037
+ "current thread state doesn't match GILState");
1038
+ return NULL;
1039
+ }
1040
+ const char *err = NULL;
1041
+ PyThreadState_Swap(NULL);
1042
+ PyThreadState *substate = Py_NewInterpreter();
1043
+ if (substate != PyThreadState_Get()) {
1044
+ err = "subinterpreter thread state not current";
1045
+ goto finally;
1046
+ }
1047
+ if (substate != PyGILState_GetThisThreadState()) {
1048
+ err = "subinterpreter thread state doesn't match GILState";
1049
+ goto finally;
1050
+ }
1051
+ finally:
1052
+ Py_EndInterpreter(substate);
1053
+ PyThreadState_Swap(orig_tstate);
1054
+ if (err != NULL) {
1055
+ PyErr_SetString(PyExc_RuntimeError, err);
1056
+ return NULL;
1057
+ }
1058
+ Py_RETURN_NONE;
1059
+ }
1060
+ /* To run some code in a sub-interpreter. */
1061
+ static PyObject *
1062
+ run_in_subinterp(PyObject *self, PyObject *args)
1063
+ {
1064
+ const char *code;
1065
+ int r;
1066
+ PyThreadState *substate, *mainstate;
1067
+ /* only initialise 'cflags.cf_flags' to test backwards compatibility */
1068
+ PyCompilerFlags cflags = {0};
1069
+ if (!PyArg_ParseTuple(args, "s:run_in_subinterp",
1070
+ &code))
1071
+ return NULL;
1072
+ mainstate = PyThreadState_Get();
1073
+ PyThreadState_Swap(NULL);
1074
+ substate = Py_NewInterpreter();
1075
+ if (substate == NULL) {
1076
+ /* Since no new thread state was created, there is no exception to
1077
+ propagate; raise a fresh one after swapping in the old thread
1078
+ state. */
1079
+ PyThreadState_Swap(mainstate);
1080
+ PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
1081
+ return NULL;
1082
+ }
1083
+ r = PyRun_SimpleStringFlags(code, &cflags);
1084
+ Py_EndInterpreter(substate);
1085
+ PyThreadState_Swap(mainstate);
1086
+ return PyLong_FromLong(r);
1087
+ }
1088
+ static PyMethodDef ml;
1089
+ static PyObject *
1090
+ create_cfunction(PyObject *self, PyObject *args)
1091
+ {
1092
+ return PyCFunction_NewEx(&ml, self, NULL);
1093
+ }
1094
+ static PyMethodDef ml = {
1095
+ "create_cfunction",
1096
+ create_cfunction,
1097
+ METH_NOARGS,
1098
+ NULL
1099
+ };
1100
+ static PyObject *
1101
+ test_structseq_newtype_doesnt_leak(PyObject *Py_UNUSED(self),
1102
+ PyObject *Py_UNUSED(args))
1103
+ {
1104
+ PyStructSequence_Desc descr;
1105
+ PyStructSequence_Field descr_fields[3];
1106
+ descr_fields[0] = (PyStructSequence_Field){"foo", "foo value"};
1107
+ descr_fields[1] = (PyStructSequence_Field){NULL, "some hidden value"};
1108
+ descr_fields[2] = (PyStructSequence_Field){0, NULL};
1109
+ descr.name = "_testcapi.test_descr";
1110
+ descr.doc = "This is used to test for memory leaks in NewType";
1111
+ descr.fields = descr_fields;
1112
+ descr.n_in_sequence = 1;
1113
+ PyTypeObject* structseq_type = PyStructSequence_NewType(&descr);
1114
+ if (structseq_type == NULL) {
1115
+ return NULL;
1116
+ }
1117
+ assert(PyType_Check(structseq_type));
1118
+ assert(PyType_FastSubclass(structseq_type, Py_TPFLAGS_TUPLE_SUBCLASS));
1119
+ Py_DECREF(structseq_type);
1120
+ Py_RETURN_NONE;
1121
+ }
1122
+ static PyObject *
1123
+ test_structseq_newtype_null_descr_doc(PyObject *Py_UNUSED(self),
1124
+ PyObject *Py_UNUSED(args))
1125
+ {
1126
+ PyStructSequence_Field descr_fields[1] = {
1127
+ (PyStructSequence_Field){NULL, NULL}
1128
+ };
1129
+ // Test specifically for NULL .doc field.
1130
+ PyStructSequence_Desc descr = {"_testcapi.test_descr", NULL, &descr_fields[0], 0};
1131
+ PyTypeObject* structseq_type = PyStructSequence_NewType(&descr);
1132
+ assert(structseq_type != NULL);
1133
+ assert(PyType_Check(structseq_type));
1134
+ assert(PyType_FastSubclass(structseq_type, Py_TPFLAGS_TUPLE_SUBCLASS));
1135
+ Py_DECREF(structseq_type);
1136
+ Py_RETURN_NONE;
1137
+ }
1138
+ typedef struct {
1139
+ PyThread_type_lock start_event;
1140
+ PyThread_type_lock exit_event;
1141
+ PyObject *callback;
1142
+ } test_c_thread_t;
1143
+ static void
1144
+ temporary_c_thread(void *data)
1145
+ {
1146
+ test_c_thread_t *test_c_thread = data;
1147
+ PyGILState_STATE state;
1148
+ PyObject *res;
1149
+ PyThread_release_lock(test_c_thread->start_event);
1150
+ /* Allocate a Python thread state for this thread */
1151
+ state = PyGILState_Ensure();
1152
+ res = PyObject_CallNoArgs(test_c_thread->callback);
1153
+ Py_CLEAR(test_c_thread->callback);
1154
+ if (res == NULL) {
1155
+ PyErr_Print();
1156
+ }
1157
+ else {
1158
+ Py_DECREF(res);
1159
+ }
1160
+ /* Destroy the Python thread state for this thread */
1161
+ PyGILState_Release(state);
1162
+ PyThread_release_lock(test_c_thread->exit_event);
1163
+ }
1164
+ static test_c_thread_t test_c_thread;
1165
+ static PyObject *
1166
+ call_in_temporary_c_thread(PyObject *self, PyObject *args)
1167
+ {
1168
+ PyObject *res = NULL;
1169
+ PyObject *callback = NULL;
1170
+ long thread;
1171
+ int wait = 1;
1172
+ if (!PyArg_ParseTuple(args, "O|i", &callback, &wait))
1173
+ {
1174
+ return NULL;
1175
+ }
1176
+ test_c_thread.start_event = PyThread_allocate_lock();
1177
+ test_c_thread.exit_event = PyThread_allocate_lock();
1178
+ test_c_thread.callback = NULL;
1179
+ if (!test_c_thread.start_event || !test_c_thread.exit_event) {
1180
+ PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
1181
+ goto exit;
1182
+ }
1183
+ test_c_thread.callback = Py_NewRef(callback);
1184
+ PyThread_acquire_lock(test_c_thread.start_event, 1);
1185
+ PyThread_acquire_lock(test_c_thread.exit_event, 1);
1186
+ thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
1187
+ if (thread == -1) {
1188
+ PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1189
+ PyThread_release_lock(test_c_thread.start_event);
1190
+ PyThread_release_lock(test_c_thread.exit_event);
1191
+ goto exit;
1192
+ }
1193
+ PyThread_acquire_lock(test_c_thread.start_event, 1);
1194
+ PyThread_release_lock(test_c_thread.start_event);
1195
+ if (!wait) {
1196
+ Py_RETURN_NONE;
1197
+ }
1198
+ Py_BEGIN_ALLOW_THREADS
1199
+ PyThread_acquire_lock(test_c_thread.exit_event, 1);
1200
+ PyThread_release_lock(test_c_thread.exit_event);
1201
+ Py_END_ALLOW_THREADS
1202
+ res = Py_NewRef(Py_None);
1203
+ exit:
1204
+ Py_CLEAR(test_c_thread.callback);
1205
+ if (test_c_thread.start_event) {
1206
+ PyThread_free_lock(test_c_thread.start_event);
1207
+ test_c_thread.start_event = NULL;
1208
+ }
1209
+ if (test_c_thread.exit_event) {
1210
+ PyThread_free_lock(test_c_thread.exit_event);
1211
+ test_c_thread.exit_event = NULL;
1212
+ }
1213
+ return res;
1214
+ }
1215
+ static PyObject *
1216
+ join_temporary_c_thread(PyObject *self, PyObject *Py_UNUSED(ignored))
1217
+ {
1218
+ Py_BEGIN_ALLOW_THREADS
1219
+ PyThread_acquire_lock(test_c_thread.exit_event, 1);
1220
+ PyThread_release_lock(test_c_thread.exit_event);
1221
+ Py_END_ALLOW_THREADS
1222
+ Py_CLEAR(test_c_thread.callback);
1223
+ PyThread_free_lock(test_c_thread.start_event);
1224
+ test_c_thread.start_event = NULL;
1225
+ PyThread_free_lock(test_c_thread.exit_event);
1226
+ test_c_thread.exit_event = NULL;
1227
+ Py_RETURN_NONE;
1228
+ }
1229
+ /* marshal */
1230
+ static PyObject*
1231
+ pymarshal_write_long_to_file(PyObject* self, PyObject *args)
1232
+ {
1233
+ long value;
1234
+ PyObject *filename;
1235
+ int version;
1236
+ FILE *fp;
1237
+ if (!PyArg_ParseTuple(args, "lOi:pymarshal_write_long_to_file",
1238
+ &value, &filename, &version))
1239
+ return NULL;
1240
+ fp = Py_fopen(filename, "wb");
1241
+ if (fp == NULL) {
1242
+ PyErr_SetFromErrno(PyExc_OSError);
1243
+ return NULL;
1244
+ }
1245
+ PyMarshal_WriteLongToFile(value, fp, version);
1246
+ assert(!PyErr_Occurred());
1247
+ fclose(fp);
1248
+ Py_RETURN_NONE;
1249
+ }
1250
+ static PyObject*
1251
+ pymarshal_write_object_to_file(PyObject* self, PyObject *args)
1252
+ {
1253
+ PyObject *obj;
1254
+ PyObject *filename;
1255
+ int version;
1256
+ FILE *fp;
1257
+ if (!PyArg_ParseTuple(args, "OOi:pymarshal_write_object_to_file",
1258
+ &obj, &filename, &version))
1259
+ return NULL;
1260
+ fp = Py_fopen(filename, "wb");
1261
+ if (fp == NULL) {
1262
+ PyErr_SetFromErrno(PyExc_OSError);
1263
+ return NULL;
1264
+ }
1265
+ PyMarshal_WriteObjectToFile(obj, fp, version);
1266
+ assert(!PyErr_Occurred());
1267
+ fclose(fp);
1268
+ Py_RETURN_NONE;
1269
+ }
1270
+ static PyObject*
1271
+ pymarshal_read_short_from_file(PyObject* self, PyObject *args)
1272
+ {
1273
+ int value;
1274
+ long pos;
1275
+ PyObject *filename;
1276
+ FILE *fp;
1277
+ if (!PyArg_ParseTuple(args, "O:pymarshal_read_short_from_file", &filename))
1278
+ return NULL;
1279
+ fp = Py_fopen(filename, "rb");
1280
+ if (fp == NULL) {
1281
+ PyErr_SetFromErrno(PyExc_OSError);
1282
+ return NULL;
1283
+ }
1284
+ value = PyMarshal_ReadShortFromFile(fp);
1285
+ pos = ftell(fp);
1286
+ fclose(fp);
1287
+ if (PyErr_Occurred())
1288
+ return NULL;
1289
+ return Py_BuildValue("il", value, pos);
1290
+ }
1291
+ static PyObject*
1292
+ pymarshal_read_long_from_file(PyObject* self, PyObject *args)
1293
+ {
1294
+ long value, pos;
1295
+ PyObject *filename;
1296
+ FILE *fp;
1297
+ if (!PyArg_ParseTuple(args, "O:pymarshal_read_long_from_file", &filename))
1298
+ return NULL;
1299
+ fp = Py_fopen(filename, "rb");
1300
+ if (fp == NULL) {
1301
+ PyErr_SetFromErrno(PyExc_OSError);
1302
+ return NULL;
1303
+ }
1304
+ value = PyMarshal_ReadLongFromFile(fp);
1305
+ pos = ftell(fp);
1306
+ fclose(fp);
1307
+ if (PyErr_Occurred())
1308
+ return NULL;
1309
+ return Py_BuildValue("ll", value, pos);
1310
+ }
1311
+ static PyObject*
1312
+ pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
1313
+ {
1314
+ PyObject *filename;
1315
+ if (!PyArg_ParseTuple(args, "O:pymarshal_read_last_object_from_file", &filename))
1316
+ return NULL;
1317
+ FILE *fp = Py_fopen(filename, "rb");
1318
+ if (fp == NULL) {
1319
+ PyErr_SetFromErrno(PyExc_OSError);
1320
+ return NULL;
1321
+ }
1322
+ PyObject *obj = PyMarshal_ReadLastObjectFromFile(fp);
1323
+ long pos = ftell(fp);
1324
+ fclose(fp);
1325
+ if (obj == NULL) {
1326
+ return NULL;
1327
+ }
1328
+ return Py_BuildValue("Nl", obj, pos);
1329
+ }
1330
+ static PyObject*
1331
+ pymarshal_read_object_from_file(PyObject* self, PyObject *args)
1332
+ {
1333
+ PyObject *filename;
1334
+ if (!PyArg_ParseTuple(args, "O:pymarshal_read_object_from_file", &filename))
1335
+ return NULL;
1336
+ FILE *fp = Py_fopen(filename, "rb");
1337
+ if (fp == NULL) {
1338
+ PyErr_SetFromErrno(PyExc_OSError);
1339
+ return NULL;
1340
+ }
1341
+ PyObject *obj = PyMarshal_ReadObjectFromFile(fp);
1342
+ long pos = ftell(fp);
1343
+ fclose(fp);
1344
+ if (obj == NULL) {
1345
+ return NULL;
1346
+ }
1347
+ return Py_BuildValue("Nl", obj, pos);
1348
+ }
1349
+ static PyObject*
1350
+ return_null_without_error(PyObject *self, PyObject *args)
1351
+ {
1352
+ /* invalid call: return NULL without setting an error,
1353
+ * _Py_CheckFunctionResult() must detect such bug at runtime. */
1354
+ PyErr_Clear();
1355
+ return NULL;
1356
+ }
1357
+ static PyObject*
1358
+ return_result_with_error(PyObject *self, PyObject *args)
1359
+ {
1360
+ /* invalid call: return a result with an error set,
1361
+ * _Py_CheckFunctionResult() must detect such bug at runtime. */
1362
+ PyErr_SetNone(PyExc_ValueError);
1363
+ Py_RETURN_NONE;
1364
+ }
1365
+ static PyObject *
1366
+ getitem_with_error(PyObject *self, PyObject *args)
1367
+ {
1368
+ PyObject *map, *key;
1369
+ if (!PyArg_ParseTuple(args, "OO", &map, &key)) {
1370
+ return NULL;
1371
+ }
1372
+ PyErr_SetString(PyExc_ValueError, "bug");
1373
+ return PyObject_GetItem(map, key);
1374
+ }
1375
+ static PyObject *
1376
+ raise_SIGINT_then_send_None(PyObject *self, PyObject *args)
1377
+ {
1378
+ PyObject *gen;
1379
+ if (!PyArg_ParseTuple(args, "O", &gen))
1380
+ return NULL;
1381
+ /* This is used in a test to check what happens if a signal arrives just
1382
+ as we're in the process of entering a yield from chain (see
1383
+ bpo-30039).
1384
+ Needs to be done in C, because:
1385
+ - we don't have a Python wrapper for raise()
1386
+ - we need to make sure that the Python-level signal handler doesn't run
1387
+ *before* we enter the generator frame, which is impossible in Python
1388
+ because we check for signals before every bytecode operation.
1389
+ */
1390
+ raise(SIGINT);
1391
+ return PyObject_CallMethod(gen, "send", "O", Py_None);
1392
+ }
1393
+ static PyObject*
1394
+ stack_pointer(PyObject *self, PyObject *args)
1395
+ {
1396
+ int v = 5;
1397
+ return PyLong_FromVoidPtr(&v);
1398
+ }
1399
+ #ifdef W_STOPCODE
1400
+ static PyObject*
1401
+ py_w_stopcode(PyObject *self, PyObject *args)
1402
+ {
1403
+ int sig, status;
1404
+ if (!PyArg_ParseTuple(args, "i", &sig)) {
1405
+ return NULL;
1406
+ }
1407
+ status = W_STOPCODE(sig);
1408
+ return PyLong_FromLong(status);
1409
+ }
1410
+ #endif
1411
+ static PyObject *
1412
+ test_pythread_tss_key_state(PyObject *self, PyObject *args)
1413
+ {
1414
+ Py_tss_t tss_key = Py_tss_NEEDS_INIT;
1415
+ if (PyThread_tss_is_created(&tss_key)) {
1416
+ return raiseTestError(self, "test_pythread_tss_key_state",
1417
+ "TSS key not in an uninitialized state at "
1418
+ "creation time");
1419
+ }
1420
+ if (PyThread_tss_create(&tss_key) != 0) {
1421
+ PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_create failed");
1422
+ return NULL;
1423
+ }
1424
+ if (!PyThread_tss_is_created(&tss_key)) {
1425
+ return raiseTestError(self, "test_pythread_tss_key_state",
1426
+ "PyThread_tss_create succeeded, "
1427
+ "but with TSS key in an uninitialized state");
1428
+ }
1429
+ if (PyThread_tss_create(&tss_key) != 0) {
1430
+ return raiseTestError(self, "test_pythread_tss_key_state",
1431
+ "PyThread_tss_create unsuccessful with "
1432
+ "an already initialized key");
1433
+ }
1434
+ #define CHECK_TSS_API(expr) \
1435
+ do { \
1436
+ (void)(expr); \
1437
+ if (!PyThread_tss_is_created(&tss_key)) { \
1438
+ return raiseTestError(self, "test_pythread_tss_key_state", \
1439
+ "TSS key initialization state was not " \
1440
+ "preserved after calling " #expr); \
1441
+ } \
1442
+ } while (0)
1443
+ CHECK_TSS_API(PyThread_tss_set(&tss_key, NULL));
1444
+ CHECK_TSS_API(PyThread_tss_get(&tss_key));
1445
+ #undef CHECK_TSS_API
1446
+ PyThread_tss_delete(&tss_key);
1447
+ if (PyThread_tss_is_created(&tss_key)) {
1448
+ return raiseTestError(self, "test_pythread_tss_key_state",
1449
+ "PyThread_tss_delete called, but did not "
1450
+ "set the key state to uninitialized");
1451
+ }
1452
+ Py_tss_t *ptr_key = PyThread_tss_alloc();
1453
+ if (ptr_key == NULL) {
1454
+ PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_alloc failed");
1455
+ return NULL;
1456
+ }
1457
+ if (PyThread_tss_is_created(ptr_key)) {
1458
+ return raiseTestError(self, "test_pythread_tss_key_state",
1459
+ "TSS key not in an uninitialized state at "
1460
+ "allocation time");
1461
+ }
1462
+ PyThread_tss_free(ptr_key);
1463
+ ptr_key = NULL;
1464
+ Py_RETURN_NONE;
1465
+ }
1466
+ /* def bad_get(self, obj, cls):
1467
+ cls()
1468
+ return repr(self)
1469
+ */
1470
+ static PyObject*
1471
+ bad_get(PyObject *module, PyObject *args)
1472
+ {
1473
+ PyObject *self, *obj, *cls;
1474
+ if (!PyArg_ParseTuple(args, "OOO", &self, &obj, &cls)) {
1475
+ return NULL;
1476
+ }
1477
+ PyObject *res = PyObject_CallNoArgs(cls);
1478
+ if (res == NULL) {
1479
+ return NULL;
1480
+ }
1481
+ Py_DECREF(res);
1482
+ return PyObject_Repr(self);
1483
+ }
1484
+ /* Functions for testing C calling conventions (METH_*) are named meth_*,
1485
+ * e.g. "meth_varargs" for METH_VARARGS.
1486
+ *
1487
+ * They all return a tuple of their C-level arguments, with None instead
1488
+ * of NULL and Python tuples instead of C arrays.
1489
+ */
1490
+ static PyObject*
1491
+ _null_to_none(PyObject* obj)
1492
+ {
1493
+ if (obj == NULL) {
1494
+ Py_RETURN_NONE;
1495
+ }
1496
+ return Py_NewRef(obj);
1497
+ }
1498
+ static PyObject*
1499
+ meth_varargs(PyObject* self, PyObject* args)
1500
+ {
1501
+ return Py_BuildValue("NO", _null_to_none(self), args);
1502
+ }
1503
+ static PyObject*
1504
+ meth_varargs_keywords(PyObject* self, PyObject* args, PyObject* kwargs)
1505
+ {
1506
+ return Py_BuildValue("NON", _null_to_none(self), args, _null_to_none(kwargs));
1507
+ }
1508
+ static PyObject*
1509
+ meth_o(PyObject* self, PyObject* obj)
1510
+ {
1511
+ return Py_BuildValue("NO", _null_to_none(self), obj);
1512
+ }
1513
+ static PyObject*
1514
+ meth_noargs(PyObject* self, PyObject *Py_UNUSED(dummy))
1515
+ {
1516
+ return _null_to_none(self);
1517
+ }
1518
+ static PyObject*
1519
+ _fastcall_to_tuple(PyObject* const* args, Py_ssize_t nargs)
1520
+ {
1521
+ PyObject *tuple = PyTuple_New(nargs);
1522
+ if (tuple == NULL) {
1523
+ return NULL;
1524
+ }
1525
+ for (Py_ssize_t i=0; i < nargs; i++) {
1526
+ Py_INCREF(args[i]);
1527
+ PyTuple_SET_ITEM(tuple, i, args[i]);
1528
+ }
1529
+ return tuple;
1530
+ }
1531
+ static PyObject*
1532
+ meth_fastcall(PyObject* self, PyObject* const* args, Py_ssize_t nargs)
1533
+ {
1534
+ return Py_BuildValue(
1535
+ "NN", _null_to_none(self), _fastcall_to_tuple(args, nargs)
1536
+ );
1537
+ }
1538
+ static PyObject*
1539
+ meth_fastcall_keywords(PyObject* self, PyObject* const* args,
1540
+ Py_ssize_t nargs, PyObject* kwargs)
1541
+ {
1542
+ PyObject *pyargs = _fastcall_to_tuple(args, nargs);
1543
+ if (pyargs == NULL) {
1544
+ return NULL;
1545
+ }
1546
+ assert(args != NULL || nargs == 0);
1547
+ PyObject* const* args_offset = args == NULL ? NULL : args + nargs;
1548
+ PyObject *pykwargs = PyObject_Vectorcall((PyObject*)&PyDict_Type,
1549
+ args_offset, 0, kwargs);
1550
+ return Py_BuildValue("NNN", _null_to_none(self), pyargs, pykwargs);
1551
+ }
1552
+ static PyObject*
1553
+ test_pycfunction_call(PyObject *module, PyObject *args)
1554
+ {
1555
+ // Function removed in the Python 3.13 API but was kept in the stable ABI.
1556
+ extern PyObject* PyCFunction_Call(PyObject *callable, PyObject *args, PyObject *kwargs);
1557
+ PyObject *func, *pos_args, *kwargs = NULL;
1558
+ if (!PyArg_ParseTuple(args, "OO!|O!", &func, &PyTuple_Type, &pos_args, &PyDict_Type, &kwargs)) {
1559
+ return NULL;
1560
+ }
1561
+ return PyCFunction_Call(func, pos_args, kwargs);
1562
+ }
1563
+ static PyObject*
1564
+ pynumber_tobase(PyObject *module, PyObject *args)
1565
+ {
1566
+ PyObject *obj;
1567
+ int base;
1568
+ if (!PyArg_ParseTuple(args, "Oi:pynumber_tobase",
1569
+ &obj, &base)) {
1570
+ return NULL;
1571
+ }
1572
+ return PyNumber_ToBase(obj, base);
1573
+ }
1574
+ /* We only use 2 in test_capi/test_misc.py. */
1575
+ #define NUM_BASIC_STATIC_TYPES 2
1576
+ static PyTypeObject BasicStaticTypes[NUM_BASIC_STATIC_TYPES] = {
1577
+ #define INIT_BASIC_STATIC_TYPE \
1578
+ { \
1579
+ PyVarObject_HEAD_INIT(NULL, 0) \
1580
+ .tp_name = "BasicStaticType", \
1581
+ .tp_basicsize = sizeof(PyObject), \
1582
+ }
1583
+ INIT_BASIC_STATIC_TYPE,
1584
+ INIT_BASIC_STATIC_TYPE,
1585
+ #undef INIT_BASIC_STATIC_TYPE
1586
+ };
1587
+ static int num_basic_static_types_used = 0;
1588
+ static PyObject *
1589
+ get_basic_static_type(PyObject *self, PyObject *args)
1590
+ {
1591
+ PyObject *base = NULL;
1592
+ if (!PyArg_ParseTuple(args, "|O", &base)) {
1593
+ return NULL;
1594
+ }
1595
+ assert(base == NULL || PyType_Check(base));
1596
+ if(num_basic_static_types_used >= NUM_BASIC_STATIC_TYPES) {
1597
+ PyErr_SetString(PyExc_RuntimeError, "no more available basic static types");
1598
+ return NULL;
1599
+ }
1600
+ PyTypeObject *cls = &BasicStaticTypes[num_basic_static_types_used++];
1601
+ if (base != NULL) {
1602
+ cls->tp_bases = PyTuple_Pack(1, base);
1603
+ if (cls->tp_bases == NULL) {
1604
+ return NULL;
1605
+ }
1606
+ cls->tp_base = (PyTypeObject *)Py_NewRef(base);
1607
+ }
1608
+ if (PyType_Ready(cls) < 0) {
1609
+ Py_DECREF(cls->tp_bases);
1610
+ Py_DECREF(cls->tp_base);
1611
+ return NULL;
1612
+ }
1613
+ return (PyObject *)cls;
1614
+ }
1615
+ // Test PyThreadState C API
1616
+ static PyObject *
1617
+ test_tstate_capi(PyObject *self, PyObject *Py_UNUSED(args))
1618
+ {
1619
+ // PyThreadState_Get()
1620
+ PyThreadState *tstate = PyThreadState_Get();
1621
+ assert(tstate != NULL);
1622
+ // PyThreadState_GET()
1623
+ PyThreadState *tstate2 = PyThreadState_Get();
1624
+ assert(tstate2 == tstate);
1625
+ // PyThreadState_GetUnchecked()
1626
+ PyThreadState *tstate3 = PyThreadState_GetUnchecked();
1627
+ assert(tstate3 == tstate);
1628
+ // PyThreadState_EnterTracing(), PyThreadState_LeaveTracing()
1629
+ PyThreadState_EnterTracing(tstate);
1630
+ PyThreadState_LeaveTracing(tstate);
1631
+ // PyThreadState_GetDict(): no tstate argument
1632
+ PyObject *dict = PyThreadState_GetDict();
1633
+ // PyThreadState_GetDict() API can return NULL if PyDict_New() fails,
1634
+ // but it should not occur in practice.
1635
+ assert(dict != NULL);
1636
+ assert(PyDict_Check(dict));
1637
+ // dict is a borrowed reference
1638
+ // PyThreadState_GetInterpreter()
1639
+ PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
1640
+ assert(interp != NULL);
1641
+ // PyThreadState_GetFrame()
1642
+ PyFrameObject*frame = PyThreadState_GetFrame(tstate);
1643
+ assert(frame != NULL);
1644
+ assert(PyFrame_Check(frame));
1645
+ Py_DECREF(frame);
1646
+ // PyThreadState_GetID()
1647
+ uint64_t id = PyThreadState_GetID(tstate);
1648
+ assert(id >= 1);
1649
+ Py_RETURN_NONE;
1650
+ }
1651
+ static PyObject *
1652
+ gen_get_code(PyObject *self, PyObject *gen)
1653
+ {
1654
+ if (!PyGen_Check(gen)) {
1655
+ PyErr_SetString(PyExc_TypeError, "argument must be a generator object");
1656
+ return NULL;
1657
+ }
1658
+ return (PyObject *)PyGen_GetCode((PyGenObject *)gen);
1659
+ }
1660
+ static PyObject *
1661
+ eval_eval_code_ex(PyObject *mod, PyObject *pos_args)
1662
+ {
1663
+ PyObject *result = NULL;
1664
+ PyObject *code;
1665
+ PyObject *globals;
1666
+ PyObject *locals = NULL;
1667
+ PyObject *args = NULL;
1668
+ PyObject *kwargs = NULL;
1669
+ PyObject *defaults = NULL;
1670
+ PyObject *kw_defaults = NULL;
1671
+ PyObject *closure = NULL;
1672
+ PyObject **c_kwargs = NULL;
1673
+ if (!PyArg_ParseTuple(pos_args,
1674
+ "OO|OO!O!O!OO:eval_code_ex",
1675
+ &code,
1676
+ &globals,
1677
+ &locals,
1678
+ &PyTuple_Type, &args,
1679
+ &PyDict_Type, &kwargs,
1680
+ &PyTuple_Type, &defaults,
1681
+ &kw_defaults,
1682
+ &closure))
1683
+ {
1684
+ goto exit;
1685
+ }
1686
+ NULLABLE(code);
1687
+ NULLABLE(globals);
1688
+ NULLABLE(locals);
1689
+ NULLABLE(kw_defaults);
1690
+ NULLABLE(closure);
1691
+ PyObject **c_args = NULL;
1692
+ Py_ssize_t c_args_len = 0;
1693
+ if (args) {
1694
+ c_args = &PyTuple_GET_ITEM(args, 0);
1695
+ c_args_len = PyTuple_Size(args);
1696
+ }
1697
+ Py_ssize_t c_kwargs_len = 0;
1698
+ if (kwargs) {
1699
+ c_kwargs_len = PyDict_Size(kwargs);
1700
+ if (c_kwargs_len > 0) {
1701
+ c_kwargs = PyMem_NEW(PyObject*, 2 * c_kwargs_len);
1702
+ if (!c_kwargs) {
1703
+ PyErr_NoMemory();
1704
+ goto exit;
1705
+ }
1706
+ Py_ssize_t i = 0;
1707
+ Py_ssize_t pos = 0;
1708
+ while (PyDict_Next(kwargs, &pos, &c_kwargs[i], &c_kwargs[i + 1])) {
1709
+ i += 2;
1710
+ }
1711
+ c_kwargs_len = i / 2;
1712
+ /* XXX This is broken if the caller deletes dict items! */
1713
+ }
1714
+ }
1715
+ PyObject **c_defaults = NULL;
1716
+ Py_ssize_t c_defaults_len = 0;
1717
+ if (defaults) {
1718
+ c_defaults = &PyTuple_GET_ITEM(defaults, 0);
1719
+ c_defaults_len = PyTuple_Size(defaults);
1720
+ }
1721
+ result = PyEval_EvalCodeEx(
1722
+ code,
1723
+ globals,
1724
+ locals,
1725
+ c_args,
1726
+ (int)c_args_len,
1727
+ c_kwargs,
1728
+ (int)c_kwargs_len,
1729
+ c_defaults,
1730
+ (int)c_defaults_len,
1731
+ kw_defaults,
1732
+ closure
1733
+ );
1734
+ exit:
1735
+ if (c_kwargs) {
1736
+ PyMem_DEL(c_kwargs);
1737
+ }
1738
+ return result;
1739
+ }
1740
+ static PyObject *
1741
+ get_feature_macros(PyObject *self, PyObject *Py_UNUSED(args))
1742
+ {
1743
+ PyObject *result = PyDict_New();
1744
+ if (!result) {
1745
+ return NULL;
1746
+ }
1747
+ int res;
1748
+ #include "_testcapi_feature_macros.inc"
1749
+ return result;
1750
+ }
1751
+ static PyObject *
1752
+ test_code_api(PyObject *self, PyObject *Py_UNUSED(args))
1753
+ {
1754
+ PyCodeObject *co = PyCode_NewEmpty("_testcapi", "dummy", 1);
1755
+ if (co == NULL) {
1756
+ return NULL;
1757
+ }
1758
+ /* co_code */
1759
+ {
1760
+ PyObject *co_code = PyCode_GetCode(co);
1761
+ if (co_code == NULL) {
1762
+ goto fail;
1763
+ }
1764
+ assert(PyBytes_CheckExact(co_code));
1765
+ if (PyObject_Length(co_code) == 0) {
1766
+ PyErr_SetString(PyExc_ValueError, "empty co_code");
1767
+ Py_DECREF(co_code);
1768
+ goto fail;
1769
+ }
1770
+ Py_DECREF(co_code);
1771
+ }
1772
+ /* co_varnames */
1773
+ {
1774
+ PyObject *co_varnames = PyCode_GetVarnames(co);
1775
+ if (co_varnames == NULL) {
1776
+ goto fail;
1777
+ }
1778
+ if (!PyTuple_CheckExact(co_varnames)) {
1779
+ PyErr_SetString(PyExc_TypeError, "co_varnames not tuple");
1780
+ Py_DECREF(co_varnames);
1781
+ goto fail;
1782
+ }
1783
+ if (PyTuple_GET_SIZE(co_varnames) != 0) {
1784
+ PyErr_SetString(PyExc_ValueError, "non-empty co_varnames");
1785
+ Py_DECREF(co_varnames);
1786
+ goto fail;
1787
+ }
1788
+ Py_DECREF(co_varnames);
1789
+ }
1790
+ /* co_cellvars */
1791
+ {
1792
+ PyObject *co_cellvars = PyCode_GetCellvars(co);
1793
+ if (co_cellvars == NULL) {
1794
+ goto fail;
1795
+ }
1796
+ if (!PyTuple_CheckExact(co_cellvars)) {
1797
+ PyErr_SetString(PyExc_TypeError, "co_cellvars not tuple");
1798
+ Py_DECREF(co_cellvars);
1799
+ goto fail;
1800
+ }
1801
+ if (PyTuple_GET_SIZE(co_cellvars) != 0) {
1802
+ PyErr_SetString(PyExc_ValueError, "non-empty co_cellvars");
1803
+ Py_DECREF(co_cellvars);
1804
+ goto fail;
1805
+ }
1806
+ Py_DECREF(co_cellvars);
1807
+ }
1808
+ /* co_freevars */
1809
+ {
1810
+ PyObject *co_freevars = PyCode_GetFreevars(co);
1811
+ if (co_freevars == NULL) {
1812
+ goto fail;
1813
+ }
1814
+ if (!PyTuple_CheckExact(co_freevars)) {
1815
+ PyErr_SetString(PyExc_TypeError, "co_freevars not tuple");
1816
+ Py_DECREF(co_freevars);
1817
+ goto fail;
1818
+ }
1819
+ if (PyTuple_GET_SIZE(co_freevars) != 0) {
1820
+ PyErr_SetString(PyExc_ValueError, "non-empty co_freevars");
1821
+ Py_DECREF(co_freevars);
1822
+ goto fail;
1823
+ }
1824
+ Py_DECREF(co_freevars);
1825
+ }
1826
+ Py_DECREF(co);
1827
+ Py_RETURN_NONE;
1828
+ fail:
1829
+ Py_DECREF(co);
1830
+ return NULL;
1831
+ }
1832
+ static int
1833
+ record_func(PyObject *obj, PyFrameObject *f, int what, PyObject *arg)
1834
+ {
1835
+ assert(PyList_Check(obj));
1836
+ PyObject *what_obj = NULL;
1837
+ PyObject *line_obj = NULL;
1838
+ PyObject *tuple = NULL;
1839
+ int res = -1;
1840
+ what_obj = PyLong_FromLong(what);
1841
+ if (what_obj == NULL) {
1842
+ goto error;
1843
+ }
1844
+ int line = PyFrame_GetLineNumber(f);
1845
+ line_obj = PyLong_FromLong(line);
1846
+ if (line_obj == NULL) {
1847
+ goto error;
1848
+ }
1849
+ tuple = PyTuple_Pack(3, what_obj, line_obj, arg);
1850
+ if (tuple == NULL) {
1851
+ goto error;
1852
+ }
1853
+ PyTuple_SET_ITEM(tuple, 0, what_obj);
1854
+ if (PyList_Append(obj, tuple)) {
1855
+ goto error;
1856
+ }
1857
+ res = 0;
1858
+ error:
1859
+ Py_XDECREF(what_obj);
1860
+ Py_XDECREF(line_obj);
1861
+ Py_XDECREF(tuple);
1862
+ return res;
1863
+ }
1864
+ static PyObject *
1865
+ settrace_to_record(PyObject *self, PyObject *list)
1866
+ {
1867
+ if (!PyList_Check(list)) {
1868
+ PyErr_SetString(PyExc_TypeError, "argument must be a list");
1869
+ return NULL;
1870
+ }
1871
+ PyEval_SetTrace(record_func, list);
1872
+ Py_RETURN_NONE;
1873
+ }
1874
+ static int
1875
+ error_func(PyObject *obj, PyFrameObject *f, int what, PyObject *arg)
1876
+ {
1877
+ assert(PyList_Check(obj));
1878
+ /* Only raise if list is empty, otherwise append None
1879
+ * This ensures that we only raise once */
1880
+ if (PyList_GET_SIZE(obj)) {
1881
+ return 0;
1882
+ }
1883
+ if (PyList_Append(obj, Py_None)) {
1884
+ return -1;
1885
+ }
1886
+ PyErr_SetString(PyExc_Exception, "an exception");
1887
+ return -1;
1888
+ }
1889
+ static PyObject *
1890
+ settrace_to_error(PyObject *self, PyObject *list)
1891
+ {
1892
+ if (!PyList_Check(list)) {
1893
+ PyErr_SetString(PyExc_TypeError, "argument must be a list");
1894
+ return NULL;
1895
+ }
1896
+ PyEval_SetTrace(error_func, list);
1897
+ Py_RETURN_NONE;
1898
+ }
1899
+ static PyObject *
1900
+ test_macros(PyObject *self, PyObject *Py_UNUSED(args))
1901
+ {
1902
+ struct MyStruct {
1903
+ int x;
1904
+ };
1905
+ wchar_t array[3];
1906
+ // static_assert(), Py_BUILD_ASSERT()
1907
+ static_assert(1 == 1, "bug");
1908
+ Py_BUILD_ASSERT(1 == 1);
1909
+ // Py_MIN(), Py_MAX(), Py_ABS()
1910
+ assert(Py_MIN(5, 11) == 5);
1911
+ assert(Py_MAX(5, 11) == 11);
1912
+ assert(Py_ABS(-5) == 5);
1913
+ // Py_STRINGIFY()
1914
+ assert(strcmp(Py_STRINGIFY(123), "123") == 0);
1915
+ // Py_MEMBER_SIZE(), Py_ARRAY_LENGTH()
1916
+ assert(Py_MEMBER_SIZE(struct MyStruct, x) == sizeof(int));
1917
+ assert(Py_ARRAY_LENGTH(array) == 3);
1918
+ // Py_CHARMASK()
1919
+ int c = 0xab00 | 7;
1920
+ assert(Py_CHARMASK(c) == 7);
1921
+ // _Py_IS_TYPE_SIGNED()
1922
+ assert(_Py_IS_TYPE_SIGNED(int));
1923
+ assert(!_Py_IS_TYPE_SIGNED(unsigned int));
1924
+ Py_RETURN_NONE;
1925
+ }
1926
+ static PyObject *
1927
+ test_weakref_capi(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
1928
+ {
1929
+ // Get the function (removed in 3.15) from the stable ABI.
1930
+ PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *);
1931
+ // Create a new heap type, create an instance of this type, and delete the
1932
+ // type. This object supports weak references.
1933
+ PyObject *new_type = PyObject_CallFunction((PyObject*)&PyType_Type,
1934
+ "s(){}", "TypeName");
1935
+ if (new_type == NULL) {
1936
+ return NULL;
1937
+ }
1938
+ PyObject *obj = PyObject_CallNoArgs(new_type);
1939
+ Py_DECREF(new_type);
1940
+ if (obj == NULL) {
1941
+ return NULL;
1942
+ }
1943
+ Py_ssize_t refcnt = Py_REFCNT(obj);
1944
+ // test PyWeakref_NewRef(), reference is alive
1945
+ PyObject *weakref = PyWeakref_NewRef(obj, NULL);
1946
+ if (weakref == NULL) {
1947
+ Py_DECREF(obj);
1948
+ return NULL;
1949
+ }
1950
+ // test PyWeakref_Check(), valid weakref object
1951
+ assert(PyWeakref_Check(weakref));
1952
+ assert(PyWeakref_CheckRefExact(weakref));
1953
+ assert(PyWeakref_CheckRefExact(weakref));
1954
+ assert(Py_REFCNT(obj) == refcnt);
1955
+ // test PyWeakref_GetRef(), reference is alive
1956
+ PyObject *ref = UNINITIALIZED_PTR;
1957
+ assert(PyWeakref_GetRef(weakref, &ref) == 1);
1958
+ assert(ref == obj);
1959
+ assert(!PyWeakref_IsDead(weakref));
1960
+ assert(Py_REFCNT(obj) == (refcnt + 1));
1961
+ Py_DECREF(ref);
1962
+ // test PyWeakref_GetObject(), reference is alive
1963
+ ref = PyWeakref_GetObject(weakref); // borrowed ref
1964
+ assert(ref == obj);
1965
+ // delete the referenced object: clear the weakref
1966
+ assert(Py_REFCNT(obj) == 1);
1967
+ Py_DECREF(obj);
1968
+ assert(PyWeakref_IsDead(weakref));
1969
+ // test PyWeakref_GetRef(), reference is dead
1970
+ ref = UNINITIALIZED_PTR;
1971
+ assert(PyWeakref_GetRef(weakref, &ref) == 0);
1972
+ assert(ref == NULL);
1973
+ // test PyWeakref_Check(), not a weakref object
1974
+ PyObject *invalid_weakref = Py_None;
1975
+ assert(!PyWeakref_Check(invalid_weakref));
1976
+ assert(!PyWeakref_CheckRefExact(invalid_weakref));
1977
+ assert(!PyWeakref_CheckRefExact(invalid_weakref));
1978
+ // test PyWeakref_GetRef(), invalid type
1979
+ assert(!PyErr_Occurred());
1980
+ ref = UNINITIALIZED_PTR;
1981
+ assert(PyWeakref_GetRef(invalid_weakref, &ref) == -1);
1982
+ assert(PyErr_ExceptionMatches(PyExc_TypeError));
1983
+ PyErr_Clear();
1984
+ assert(ref == NULL);
1985
+ // test PyWeakRef_IsDead(), invalid type
1986
+ assert(!PyErr_Occurred());
1987
+ assert(PyWeakref_IsDead(invalid_weakref) == -1);
1988
+ assert(PyErr_ExceptionMatches(PyExc_TypeError));
1989
+ PyErr_Clear();
1990
+ // test PyWeakref_GetObject(), invalid type
1991
+ assert(PyWeakref_GetObject(invalid_weakref) == NULL);
1992
+ assert(PyErr_ExceptionMatches(PyExc_SystemError));
1993
+ PyErr_Clear();
1994
+ // test PyWeakref_GetRef(NULL)
1995
+ ref = UNINITIALIZED_PTR;
1996
+ assert(PyWeakref_GetRef(NULL, &ref) == -1);
1997
+ assert(PyErr_ExceptionMatches(PyExc_SystemError));
1998
+ assert(ref == NULL);
1999
+ PyErr_Clear();
2000
+ // test PyWeakref_IsDead(NULL)
2001
+ assert(PyWeakref_IsDead(NULL) == -1);
2002
+ assert(PyErr_ExceptionMatches(PyExc_SystemError));
2003
+ PyErr_Clear();
2004
+ // test PyWeakref_GetObject(NULL)
2005
+ assert(PyWeakref_GetObject(NULL) == NULL);
2006
+ assert(PyErr_ExceptionMatches(PyExc_SystemError));
2007
+ PyErr_Clear();
2008
+ Py_DECREF(weakref);
2009
+ Py_RETURN_NONE;
2010
+ }
2011
+ struct simpletracer_data {
2012
+ int create_count;
2013
+ int destroy_count;
2014
+ int tracker_removed;
2015
+ void* addresses[10];
2016
+ };
2017
+ static int _simpletracer(PyObject *obj, PyRefTracerEvent event, void* data) {
2018
+ struct simpletracer_data* the_data = (struct simpletracer_data*)data;
2019
+ assert(the_data->create_count + the_data->destroy_count < (int)Py_ARRAY_LENGTH(the_data->addresses));
2020
+ the_data->addresses[the_data->create_count + the_data->destroy_count] = obj;
2021
+ switch (event) {
2022
+ case PyRefTracer_CREATE:
2023
+ the_data->create_count++;
2024
+ break;
2025
+ case PyRefTracer_DESTROY:
2026
+ the_data->destroy_count++;
2027
+ break;
2028
+ case PyRefTracer_TRACKER_REMOVED:
2029
+ the_data->tracker_removed++;
2030
+ break;
2031
+ default:
2032
+ return -1;
2033
+ }
2034
+ return 0;
2035
+ }
2036
+ static PyObject *
2037
+ test_reftracer(PyObject *ob, PyObject *Py_UNUSED(ignored))
2038
+ {
2039
+ // Save the current tracer and data to restore it later
2040
+ void* current_data;
2041
+ PyRefTracer current_tracer = PyRefTracer_GetTracer(&current_data);
2042
+ struct simpletracer_data tracer_data = {0};
2043
+ void* the_data = &tracer_data;
2044
+ // Install a simple tracer function
2045
+ if (PyRefTracer_SetTracer(_simpletracer, the_data) != 0) {
2046
+ goto failed;
2047
+ }
2048
+ // Check that the tracer was correctly installed
2049
+ void* data;
2050
+ if (PyRefTracer_GetTracer(&data) != _simpletracer || data != the_data) {
2051
+ PyErr_SetString(PyExc_AssertionError, "The reftracer not correctly installed");
2052
+ (void)PyRefTracer_SetTracer(NULL, NULL);
2053
+ goto failed;
2054
+ }
2055
+ // Create a bunch of objects
2056
+ PyObject* obj = PyList_New(0);
2057
+ if (obj == NULL) {
2058
+ goto failed;
2059
+ }
2060
+ PyObject* obj2 = PyDict_New();
2061
+ if (obj2 == NULL) {
2062
+ Py_DECREF(obj);
2063
+ goto failed;
2064
+ }
2065
+ // Kill all objects
2066
+ Py_DECREF(obj);
2067
+ Py_DECREF(obj2);
2068
+ // Remove the tracer
2069
+ (void)PyRefTracer_SetTracer(NULL, NULL);
2070
+ // Check that the tracer was removed
2071
+ if (PyRefTracer_GetTracer(&data) != NULL || data != NULL) {
2072
+ PyErr_SetString(PyExc_ValueError, "The reftracer was not correctly removed");
2073
+ goto failed;
2074
+ }
2075
+ if (tracer_data.create_count != 2 ||
2076
+ tracer_data.addresses[0] != obj ||
2077
+ tracer_data.addresses[1] != obj2) {
2078
+ PyErr_SetString(PyExc_ValueError, "The object creation was not correctly traced");
2079
+ goto failed;
2080
+ }
2081
+ if (tracer_data.destroy_count != 2 ||
2082
+ tracer_data.addresses[2] != obj ||
2083
+ tracer_data.addresses[3] != obj2) {
2084
+ PyErr_SetString(PyExc_ValueError, "The object destruction was not correctly traced");
2085
+ goto failed;
2086
+ }
2087
+ if (tracer_data.tracker_removed != 1) {
2088
+ PyErr_SetString(PyExc_ValueError, "The tracker removal was not correctly traced");
2089
+ goto failed;
2090
+ }
2091
+ PyRefTracer_SetTracer(current_tracer, current_data);
2092
+ Py_RETURN_NONE;
2093
+ failed:
2094
+ PyRefTracer_SetTracer(current_tracer, current_data);
2095
+ return NULL;
2096
+ }
2097
+ static PyObject *
2098
+ function_set_warning(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
2099
+ {
2100
+ if (PyErr_WarnEx(PyExc_RuntimeWarning, "Testing PyErr_WarnEx", 2)) {
2101
+ return NULL;
2102
+ }
2103
+ Py_RETURN_NONE;
2104
+ }
2105
+ static PyObject *
2106
+ test_critical_sections(PyObject *module, PyObject *Py_UNUSED(args))
2107
+ {
2108
+ Py_BEGIN_CRITICAL_SECTION(module);
2109
+ Py_END_CRITICAL_SECTION();
2110
+ Py_BEGIN_CRITICAL_SECTION2(module, module);
2111
+ Py_END_CRITICAL_SECTION2();
2112
+ #ifdef Py_GIL_DISABLED
2113
+ // avoid unused variable compiler warning on GIL-enabled build
2114
+ PyMutex mut = {0};
2115
+ Py_BEGIN_CRITICAL_SECTION_MUTEX(&mut);
2116
+ Py_END_CRITICAL_SECTION();
2117
+ Py_BEGIN_CRITICAL_SECTION2_MUTEX(&mut, &mut);
2118
+ Py_END_CRITICAL_SECTION2();
2119
+ #endif
2120
+ Py_RETURN_NONE;
2121
+ }
2122
+ // Used by `finalize_thread_hang`.
2123
+ #if defined(_POSIX_THREADS) && !defined(__wasi__)
2124
+ static void finalize_thread_hang_cleanup_callback(void *Py_UNUSED(arg)) {
2125
+ // Should not reach here.
2126
+ Py_FatalError("pthread thread termination was triggered unexpectedly");
2127
+ }
2128
+ #endif
2129
+ // Tests that finalization does not trigger pthread cleanup.
2130
+ //
2131
+ // Must be called with a single nullary callable function that should block
2132
+ // (with GIL released) until finalization is in progress.
2133
+ static PyObject *
2134
+ finalize_thread_hang(PyObject *self, PyObject *callback)
2135
+ {
2136
+ // WASI builds some pthread stuff but doesn't have these APIs today?
2137
+ #if defined(_POSIX_THREADS) && !defined(__wasi__)
2138
+ pthread_cleanup_push(finalize_thread_hang_cleanup_callback, NULL);
2139
+ #endif
2140
+ PyObject_CallNoArgs(callback);
2141
+ // Should not reach here.
2142
+ Py_FatalError("thread unexpectedly did not hang");
2143
+ #if defined(_POSIX_THREADS) && !defined(__wasi__)
2144
+ pthread_cleanup_pop(0);
2145
+ #endif
2146
+ Py_RETURN_NONE;
2147
+ }
2148
+ struct atexit_data {
2149
+ int called;
2150
+ PyThreadState *tstate;
2151
+ PyInterpreterState *interp;
2152
+ };
2153
+ static void
2154
+ atexit_callback(void *data)
2155
+ {
2156
+ struct atexit_data *at_data = (struct atexit_data *)data;
2157
+ // Ensure that the callback is from the same interpreter
2158
+ assert(PyThreadState_Get() == at_data->tstate);
2159
+ assert(PyInterpreterState_Get() == at_data->interp);
2160
+ ++at_data->called;
2161
+ }
2162
+ static PyObject *
2163
+ test_atexit(PyObject *self, PyObject *Py_UNUSED(args))
2164
+ {
2165
+ PyThreadState *oldts = PyThreadState_Swap(NULL);
2166
+ PyThreadState *tstate = Py_NewInterpreter();
2167
+ struct atexit_data data = {0};
2168
+ data.tstate = PyThreadState_Get();
2169
+ data.interp = PyInterpreterState_Get();
2170
+ int amount = 10;
2171
+ for (int i = 0; i < amount; ++i)
2172
+ {
2173
+ int res = PyUnstable_AtExit(tstate->interp, atexit_callback, (void *)&data);
2174
+ if (res < 0) {
2175
+ Py_EndInterpreter(tstate);
2176
+ PyThreadState_Swap(oldts);
2177
+ PyErr_SetString(PyExc_RuntimeError, "atexit callback failed");
2178
+ return NULL;
2179
+ }
2180
+ }
2181
+ Py_EndInterpreter(tstate);
2182
+ PyThreadState_Swap(oldts);
2183
+ if (data.called != amount) {
2184
+ PyErr_SetString(PyExc_RuntimeError, "atexit callback not called");
2185
+ return NULL;
2186
+ }
2187
+ Py_RETURN_NONE;
2188
+ }
2189
+ static PyObject*
2190
+ code_offset_to_line(PyObject* self, PyObject* const* args, Py_ssize_t nargsf)
2191
+ {
2192
+ Py_ssize_t nargs = _PyVectorcall_NARGS(nargsf);
2193
+ if (nargs != 2) {
2194
+ PyErr_SetString(PyExc_TypeError, "code_offset_to_line takes 2 arguments");
2195
+ return NULL;
2196
+ }
2197
+ int offset;
2198
+ if (PyLong_AsInt32(args[1], &offset) < 0) {
2199
+ return NULL;
2200
+ }
2201
+ PyCodeObject *code = (PyCodeObject *)args[0];
2202
+ if (!PyCode_Check(code)) {
2203
+ PyErr_SetString(PyExc_TypeError, "first arg must be a code object");
2204
+ return NULL;
2205
+ }
2206
+ return PyLong_FromInt32(PyCode_Addr2Line(code, offset));
2207
+ }
2208
+ static int
2209
+ _reftrace_printer(PyObject *obj, PyRefTracerEvent event, void *counter_data)
2210
+ {
2211
+ switch (event) {
2212
+ case PyRefTracer_CREATE:
2213
+ printf("CREATE %s\n", Py_TYPE(obj)->tp_name);
2214
+ break;
2215
+ case PyRefTracer_DESTROY:
2216
+ printf("DESTROY %s\n", Py_TYPE(obj)->tp_name);
2217
+ break;
2218
+ case PyRefTracer_TRACKER_REMOVED:
2219
+ return 0;
2220
+ }
2221
+ return 0;
2222
+ }
2223
+ // A simple reftrace printer for very simple tests
2224
+ static PyObject *
2225
+ toggle_reftrace_printer(PyObject *ob, PyObject *arg)
2226
+ {
2227
+ if (arg == Py_True) {
2228
+ PyRefTracer_SetTracer(_reftrace_printer, NULL);
2229
+ }
2230
+ else {
2231
+ PyRefTracer_SetTracer(NULL, NULL);
2232
+ }
2233
+ Py_RETURN_NONE;
2234
+ }
2235
+ typedef struct {
2236
+ PyObject_HEAD
2237
+ } ManagedWeakrefNoGCObject;
2238
+ static void
2239
+ ManagedWeakrefNoGC_dealloc(PyObject *self)
2240
+ {
2241
+ PyObject_ClearWeakRefs(self);
2242
+ PyTypeObject *tp = Py_TYPE(self);
2243
+ tp->tp_free(self);
2244
+ Py_DECREF(tp);
2245
+ }
2246
+ static PyType_Slot ManagedWeakrefNoGC_slots[] = {
2247
+ {Py_tp_dealloc, ManagedWeakrefNoGC_dealloc},
2248
+ {0, 0}
2249
+ };
2250
+ static PyType_Spec ManagedWeakrefNoGC_spec = {
2251
+ .name = "_testcapi.ManagedWeakrefNoGCType",
2252
+ .basicsize = sizeof(ManagedWeakrefNoGCObject),
2253
+ .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_MANAGED_WEAKREF),
2254
+ .slots = ManagedWeakrefNoGC_slots,
2255
+ };
2256
+ static PyObject *
2257
+ create_managed_weakref_nogc_type(PyObject *self, PyObject *Py_UNUSED(args))
2258
+ {
2259
+ return PyType_FromSpec(&ManagedWeakrefNoGC_spec);
2260
+ }
2261
+ static PyMethodDef TestMethods[] = {
2262
+ {"set_errno", set_errno, METH_VARARGS},
2263
+ {"test_config", test_config, METH_NOARGS},
2264
+ {"test_sizeof_c_types", test_sizeof_c_types, METH_NOARGS},
2265
+ {"test_lazy_hash_inheritance", test_lazy_hash_inheritance,METH_NOARGS},
2266
+ {"test_structseq_newtype_doesnt_leak",
2267
+ test_structseq_newtype_doesnt_leak, METH_NOARGS},
2268
+ {"test_structseq_newtype_null_descr_doc",
2269
+ test_structseq_newtype_null_descr_doc, METH_NOARGS},
2270
+ {"pyobject_repr_from_null", pyobject_repr_from_null, METH_NOARGS},
2271
+ {"pyobject_str_from_null", pyobject_str_from_null, METH_NOARGS},
2272
+ {"pyobject_bytes_from_null", pyobject_bytes_from_null, METH_NOARGS},
2273
+ {"test_capsule", test_capsule, METH_NOARGS},
2274
+ {"test_from_contiguous", test_from_contiguous, METH_NOARGS},
2275
+ #if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
2276
+ {"test_pep3118_obsolete_write_locks", test_pep3118_obsolete_write_locks, METH_NOARGS},
2277
+ #endif
2278
+ {"getbuffer_with_null_view", getbuffer_with_null_view, METH_O},
2279
+ {"PyBuffer_SizeFromFormat", test_PyBuffer_SizeFromFormat, METH_VARARGS},
2280
+ {"py_buildvalue", py_buildvalue, METH_VARARGS},
2281
+ {"py_buildvalue_ints", py_buildvalue_ints, METH_VARARGS},
2282
+ {"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
2283
+ {"test_buildvalue_p", test_buildvalue_p, METH_NOARGS},
2284
+ {"test_reftracer", test_reftracer, METH_NOARGS},
2285
+ {"_test_thread_state", test_thread_state, METH_VARARGS},
2286
+ {"gilstate_ensure_release", gilstate_ensure_release, METH_NOARGS},
2287
+ #ifndef MS_WINDOWS
2288
+ {"_spawn_pthread_waiter", spawn_pthread_waiter, METH_NOARGS},
2289
+ {"_end_spawned_pthread", end_spawned_pthread, METH_NOARGS},
2290
+ #endif
2291
+ {"_pending_threadfunc", _PyCFunction_CAST(pending_threadfunc),
2292
+ METH_VARARGS|METH_KEYWORDS},
2293
+ #ifdef HAVE_GETTIMEOFDAY
2294
+ {"profile_int", profile_int, METH_NOARGS},
2295
+ #endif
2296
+ {"argparsing", argparsing, METH_VARARGS},
2297
+ {"code_newempty", code_newempty, METH_VARARGS},
2298
+ {"eval_code_ex", eval_eval_code_ex, METH_VARARGS},
2299
+ {"make_memoryview_from_NULL_pointer", make_memoryview_from_NULL_pointer,
2300
+ METH_NOARGS},
2301
+ {"buffer_fill_info", buffer_fill_info, METH_VARARGS},
2302
+ {"crash_no_current_thread", crash_no_current_thread, METH_NOARGS},
2303
+ {"test_current_tstate_matches", test_current_tstate_matches, METH_NOARGS},
2304
+ {"run_in_subinterp", run_in_subinterp, METH_VARARGS},
2305
+ {"create_cfunction", create_cfunction, METH_NOARGS},
2306
+ {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_VARARGS,
2307
+ PyDoc_STR("set_error_class(error_class) -> None")},
2308
+ {"join_temporary_c_thread", join_temporary_c_thread, METH_NOARGS},
2309
+ {"pymarshal_write_long_to_file",
2310
+ pymarshal_write_long_to_file, METH_VARARGS},
2311
+ {"pymarshal_write_object_to_file",
2312
+ pymarshal_write_object_to_file, METH_VARARGS},
2313
+ {"pymarshal_read_short_from_file",
2314
+ pymarshal_read_short_from_file, METH_VARARGS},
2315
+ {"pymarshal_read_long_from_file",
2316
+ pymarshal_read_long_from_file, METH_VARARGS},
2317
+ {"pymarshal_read_last_object_from_file",
2318
+ pymarshal_read_last_object_from_file, METH_VARARGS},
2319
+ {"pymarshal_read_object_from_file",
2320
+ pymarshal_read_object_from_file, METH_VARARGS},
2321
+ {"return_null_without_error", return_null_without_error, METH_NOARGS},
2322
+ {"return_result_with_error", return_result_with_error, METH_NOARGS},
2323
+ {"getitem_with_error", getitem_with_error, METH_VARARGS},
2324
+ {"Py_CompileString", pycompilestring, METH_O},
2325
+ {"raise_SIGINT_then_send_None", raise_SIGINT_then_send_None, METH_VARARGS},
2326
+ {"stack_pointer", stack_pointer, METH_NOARGS},
2327
+ #ifdef W_STOPCODE
2328
+ {"W_STOPCODE", py_w_stopcode, METH_VARARGS},
2329
+ #endif
2330
+ {"test_pythread_tss_key_state", test_pythread_tss_key_state, METH_VARARGS},
2331
+ {"bad_get", bad_get, METH_VARARGS},
2332
+ {"meth_varargs", meth_varargs, METH_VARARGS},
2333
+ {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
2334
+ {"meth_o", meth_o, METH_O},
2335
+ {"meth_noargs", meth_noargs, METH_NOARGS},
2336
+ {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL},
2337
+ {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS},
2338
+ {"pycfunction_call", test_pycfunction_call, METH_VARARGS},
2339
+ {"pynumber_tobase", pynumber_tobase, METH_VARARGS},
2340
+ {"get_basic_static_type", get_basic_static_type, METH_VARARGS, NULL},
2341
+ {"test_tstate_capi", test_tstate_capi, METH_NOARGS, NULL},
2342
+ {"gen_get_code", gen_get_code, METH_O, NULL},
2343
+ {"get_feature_macros", get_feature_macros, METH_NOARGS, NULL},
2344
+ {"test_code_api", test_code_api, METH_NOARGS, NULL},
2345
+ {"settrace_to_error", settrace_to_error, METH_O, NULL},
2346
+ {"settrace_to_record", settrace_to_record, METH_O, NULL},
2347
+ {"test_macros", test_macros, METH_NOARGS, NULL},
2348
+ {"test_weakref_capi", test_weakref_capi, METH_NOARGS},
2349
+ {"function_set_warning", function_set_warning, METH_NOARGS},
2350
+ {"test_critical_sections", test_critical_sections, METH_NOARGS},
2351
+ {"finalize_thread_hang", finalize_thread_hang, METH_O, NULL},
2352
+ {"test_atexit", test_atexit, METH_NOARGS},
2353
+ {"code_offset_to_line", _PyCFunction_CAST(code_offset_to_line), METH_FASTCALL},
2354
+ {"toggle_reftrace_printer", toggle_reftrace_printer, METH_O},
2355
+ {"create_managed_weakref_nogc_type",
2356
+ create_managed_weakref_nogc_type, METH_NOARGS},
2357
+ {NULL, NULL} /* sentinel */
2358
+ };
2359
+ typedef struct {
2360
+ PyObject_HEAD
2361
+ } matmulObject;
2362
+ static PyObject *
2363
+ matmulType_matmul(PyObject *self, PyObject *other)
2364
+ {
2365
+ return Py_BuildValue("(sOO)", "matmul", self, other);
2366
+ }
2367
+ static PyObject *
2368
+ matmulType_imatmul(PyObject *self, PyObject *other)
2369
+ {
2370
+ return Py_BuildValue("(sOO)", "imatmul", self, other);
2371
+ }
2372
+ static void
2373
+ matmulType_dealloc(PyObject *self)
2374
+ {
2375
+ Py_TYPE(self)->tp_free(self);
2376
+ }
2377
+ static PyNumberMethods matmulType_as_number = {
2378
+ 0, /* nb_add */
2379
+ 0, /* nb_subtract */
2380
+ 0, /* nb_multiply */
2381
+ 0, /* nb_remainde r*/
2382
+ 0, /* nb_divmod */
2383
+ 0, /* nb_power */
2384
+ 0, /* nb_negative */
2385
+ 0, /* tp_positive */
2386
+ 0, /* tp_absolute */
2387
+ 0, /* tp_bool */
2388
+ 0, /* nb_invert */
2389
+ 0, /* nb_lshift */
2390
+ 0, /* nb_rshift */
2391
+ 0, /* nb_and */
2392
+ 0, /* nb_xor */
2393
+ 0, /* nb_or */
2394
+ 0, /* nb_int */
2395
+ 0, /* nb_reserved */
2396
+ 0, /* nb_float */
2397
+ 0, /* nb_inplace_add */
2398
+ 0, /* nb_inplace_subtract */
2399
+ 0, /* nb_inplace_multiply */
2400
+ 0, /* nb_inplace_remainder */
2401
+ 0, /* nb_inplace_power */
2402
+ 0, /* nb_inplace_lshift */
2403
+ 0, /* nb_inplace_rshift */
2404
+ 0, /* nb_inplace_and */
2405
+ 0, /* nb_inplace_xor */
2406
+ 0, /* nb_inplace_or */
2407
+ 0, /* nb_floor_divide */
2408
+ 0, /* nb_true_divide */
2409
+ 0, /* nb_inplace_floor_divide */
2410
+ 0, /* nb_inplace_true_divide */
2411
+ 0, /* nb_index */
2412
+ matmulType_matmul, /* nb_matrix_multiply */
2413
+ matmulType_imatmul /* nb_matrix_inplace_multiply */
2414
+ };
2415
+ static PyTypeObject matmulType = {
2416
+ PyVarObject_HEAD_INIT(NULL, 0)
2417
+ "matmulType",
2418
+ sizeof(matmulObject), /* tp_basicsize */
2419
+ 0, /* tp_itemsize */
2420
+ matmulType_dealloc, /* destructor tp_dealloc */
2421
+ 0, /* tp_vectorcall_offset */
2422
+ 0, /* tp_getattr */
2423
+ 0, /* tp_setattr */
2424
+ 0, /* tp_as_async */
2425
+ 0, /* tp_repr */
2426
+ &matmulType_as_number, /* tp_as_number */
2427
+ 0, /* tp_as_sequence */
2428
+ 0, /* tp_as_mapping */
2429
+ 0, /* tp_hash */
2430
+ 0, /* tp_call */
2431
+ 0, /* tp_str */
2432
+ PyObject_GenericGetAttr, /* tp_getattro */
2433
+ PyObject_GenericSetAttr, /* tp_setattro */
2434
+ 0, /* tp_as_buffer */
2435
+ 0, /* tp_flags */
2436
+ "C level type with matrix operations defined",
2437
+ 0, /* traverseproc tp_traverse */
2438
+ 0, /* tp_clear */
2439
+ 0, /* tp_richcompare */
2440
+ 0, /* tp_weaklistoffset */
2441
+ 0, /* tp_iter */
2442
+ 0, /* tp_iternext */
2443
+ 0, /* tp_methods */
2444
+ 0, /* tp_members */
2445
+ 0,
2446
+ 0,
2447
+ 0,
2448
+ 0,
2449
+ 0,
2450
+ 0,
2451
+ 0,
2452
+ 0,
2453
+ PyType_GenericNew, /* tp_new */
2454
+ PyObject_Free, /* tp_free */
2455
+ };
2456
+ typedef struct {
2457
+ PyObject_HEAD
2458
+ } ipowObject;
2459
+ static PyObject *
2460
+ ipowType_ipow(PyObject *self, PyObject *other, PyObject *mod)
2461
+ {
2462
+ return PyTuple_Pack(2, other, mod);
2463
+ }
2464
+ static PyNumberMethods ipowType_as_number = {
2465
+ .nb_inplace_power = ipowType_ipow
2466
+ };
2467
+ static PyTypeObject ipowType = {
2468
+ PyVarObject_HEAD_INIT(NULL, 0)
2469
+ .tp_name = "ipowType",
2470
+ .tp_basicsize = sizeof(ipowObject),
2471
+ .tp_as_number = &ipowType_as_number,
2472
+ .tp_new = PyType_GenericNew
2473
+ };
2474
+ typedef struct {
2475
+ PyObject_HEAD
2476
+ PyObject *ao_iterator;
2477
+ } awaitObject;
2478
+ #define awaitObject_CAST(op) ((awaitObject *)(op))
2479
+ static PyObject *
2480
+ awaitObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2481
+ {
2482
+ PyObject *v;
2483
+ awaitObject *ao;
2484
+ if (!PyArg_UnpackTuple(args, "awaitObject", 1, 1, &v))
2485
+ return NULL;
2486
+ ao = (awaitObject *)type->tp_alloc(type, 0);
2487
+ if (ao == NULL) {
2488
+ return NULL;
2489
+ }
2490
+ ao->ao_iterator = Py_NewRef(v);
2491
+ return (PyObject *)ao;
2492
+ }
2493
+ static void
2494
+ awaitObject_dealloc(PyObject *op)
2495
+ {
2496
+ awaitObject *ao = awaitObject_CAST(op);
2497
+ Py_CLEAR(ao->ao_iterator);
2498
+ Py_TYPE(ao)->tp_free(ao);
2499
+ }
2500
+ static PyObject *
2501
+ awaitObject_await(PyObject *op)
2502
+ {
2503
+ awaitObject *ao = awaitObject_CAST(op);
2504
+ return Py_NewRef(ao->ao_iterator);
2505
+ }
2506
+ static PyAsyncMethods awaitType_as_async = {
2507
+ awaitObject_await, /* am_await */
2508
+ 0, /* am_aiter */
2509
+ 0, /* am_anext */
2510
+ 0, /* am_send */
2511
+ };
2512
+ static PyTypeObject awaitType = {
2513
+ PyVarObject_HEAD_INIT(NULL, 0)
2514
+ "awaitType",
2515
+ sizeof(awaitObject), /* tp_basicsize */
2516
+ 0, /* tp_itemsize */
2517
+ awaitObject_dealloc, /* tp_dealloc */
2518
+ 0, /* tp_vectorcall_offset */
2519
+ 0, /* tp_getattr */
2520
+ 0, /* tp_setattr */
2521
+ &awaitType_as_async, /* tp_as_async */
2522
+ 0, /* tp_repr */
2523
+ 0, /* tp_as_number */
2524
+ 0, /* tp_as_sequence */
2525
+ 0, /* tp_as_mapping */
2526
+ 0, /* tp_hash */
2527
+ 0, /* tp_call */
2528
+ 0, /* tp_str */
2529
+ PyObject_GenericGetAttr, /* tp_getattro */
2530
+ PyObject_GenericSetAttr, /* tp_setattro */
2531
+ 0, /* tp_as_buffer */
2532
+ 0, /* tp_flags */
2533
+ "C level type with tp_as_async",
2534
+ 0, /* traverseproc tp_traverse */
2535
+ 0, /* tp_clear */
2536
+ 0, /* tp_richcompare */
2537
+ 0, /* tp_weaklistoffset */
2538
+ 0, /* tp_iter */
2539
+ 0, /* tp_iternext */
2540
+ 0, /* tp_methods */
2541
+ 0, /* tp_members */
2542
+ 0,
2543
+ 0,
2544
+ 0,
2545
+ 0,
2546
+ 0,
2547
+ 0,
2548
+ 0,
2549
+ 0,
2550
+ awaitObject_new, /* tp_new */
2551
+ PyObject_Free, /* tp_free */
2552
+ };
2553
+ /* Test bpo-35983: create a subclass of "list" which checks that instances
2554
+ * are not deallocated twice */
2555
+ typedef struct {
2556
+ PyListObject list;
2557
+ int deallocated;
2558
+ } MyListObject;
2559
+ static PyObject *
2560
+ MyList_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2561
+ {
2562
+ PyObject* op = PyList_Type.tp_new(type, args, kwds);
2563
+ ((MyListObject*)op)->deallocated = 0;
2564
+ return op;
2565
+ }
2566
+ void
2567
+ MyList_dealloc(PyObject *self)
2568
+ {
2569
+ MyListObject *op = (MyListObject *)self;
2570
+ if (op->deallocated) {
2571
+ /* We cannot raise exceptions here but we still want the testsuite
2572
+ * to fail when we hit this */
2573
+ Py_FatalError("MyList instance deallocated twice");
2574
+ }
2575
+ op->deallocated = 1;
2576
+ PyList_Type.tp_dealloc((PyObject *)op);
2577
+ }
2578
+ static PyTypeObject MyList_Type = {
2579
+ PyVarObject_HEAD_INIT(NULL, 0)
2580
+ "MyList",
2581
+ sizeof(MyListObject),
2582
+ 0,
2583
+ MyList_dealloc, /* tp_dealloc */
2584
+ 0, /* tp_vectorcall_offset */
2585
+ 0, /* tp_getattr */
2586
+ 0, /* tp_setattr */
2587
+ 0, /* tp_as_async */
2588
+ 0, /* tp_repr */
2589
+ 0, /* tp_as_number */
2590
+ 0, /* tp_as_sequence */
2591
+ 0, /* tp_as_mapping */
2592
+ 0, /* tp_hash */
2593
+ 0, /* tp_call */
2594
+ 0, /* tp_str */
2595
+ 0, /* tp_getattro */
2596
+ 0, /* tp_setattro */
2597
+ 0, /* tp_as_buffer */
2598
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2599
+ 0, /* tp_doc */
2600
+ 0, /* tp_traverse */
2601
+ 0, /* tp_clear */
2602
+ 0, /* tp_richcompare */
2603
+ 0, /* tp_weaklistoffset */
2604
+ 0, /* tp_iter */
2605
+ 0, /* tp_iternext */
2606
+ 0, /* tp_methods */
2607
+ 0, /* tp_members */
2608
+ 0, /* tp_getset */
2609
+ 0, /* &PyList_Type */ /* tp_base */
2610
+ 0, /* tp_dict */
2611
+ 0, /* tp_descr_get */
2612
+ 0, /* tp_descr_set */
2613
+ 0, /* tp_dictoffset */
2614
+ 0, /* tp_init */
2615
+ 0, /* tp_alloc */
2616
+ MyList_new, /* tp_new */
2617
+ };
2618
+ /* Test PEP 560 */
2619
+ typedef struct {
2620
+ PyObject_HEAD
2621
+ PyObject *item;
2622
+ } PyGenericAliasObject;
2623
+ static void
2624
+ generic_alias_dealloc(PyObject *op)
2625
+ {
2626
+ PyGenericAliasObject *self = (PyGenericAliasObject*)op;
2627
+ Py_CLEAR(self->item);
2628
+ Py_TYPE(self)->tp_free(self);
2629
+ }
2630
+ static PyObject *
2631
+ generic_alias_mro_entries(PyObject *op, PyObject *Py_UNUSED(bases))
2632
+ {
2633
+ PyGenericAliasObject *self = (PyGenericAliasObject*)op;
2634
+ return PyTuple_Pack(1, self->item);
2635
+ }
2636
+ static PyMethodDef generic_alias_methods[] = {
2637
+ {"__mro_entries__", generic_alias_mro_entries, METH_O, NULL},
2638
+ {NULL} /* sentinel */
2639
+ };
2640
+ static PyTypeObject GenericAlias_Type = {
2641
+ PyVarObject_HEAD_INIT(NULL, 0)
2642
+ "GenericAlias",
2643
+ sizeof(PyGenericAliasObject),
2644
+ 0,
2645
+ .tp_dealloc = generic_alias_dealloc,
2646
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2647
+ .tp_methods = generic_alias_methods,
2648
+ };
2649
+ static PyObject *
2650
+ generic_alias_new(PyObject *item)
2651
+ {
2652
+ PyGenericAliasObject *o = PyObject_New(PyGenericAliasObject, &GenericAlias_Type);
2653
+ if (o == NULL) {
2654
+ return NULL;
2655
+ }
2656
+ o->item = Py_NewRef(item);
2657
+ return (PyObject*) o;
2658
+ }
2659
+ typedef struct {
2660
+ PyObject_HEAD
2661
+ } PyGenericObject;
2662
+ static PyObject *
2663
+ generic_class_getitem(PyObject *type, PyObject *item)
2664
+ {
2665
+ return generic_alias_new(item);
2666
+ }
2667
+ static PyMethodDef generic_methods[] = {
2668
+ {"__class_getitem__", generic_class_getitem, METH_O|METH_CLASS, NULL},
2669
+ {NULL} /* sentinel */
2670
+ };
2671
+ static PyTypeObject Generic_Type = {
2672
+ PyVarObject_HEAD_INIT(NULL, 0)
2673
+ "Generic",
2674
+ sizeof(PyGenericObject),
2675
+ 0,
2676
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2677
+ .tp_methods = generic_methods,
2678
+ };
2679
+ static PyMethodDef meth_instance_methods[] = {
2680
+ {"meth_varargs", meth_varargs, METH_VARARGS},
2681
+ {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
2682
+ {"meth_o", meth_o, METH_O},
2683
+ {"meth_noargs", meth_noargs, METH_NOARGS},
2684
+ {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL},
2685
+ {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS},
2686
+ {NULL, NULL} /* sentinel */
2687
+ };
2688
+ static PyTypeObject MethInstance_Type = {
2689
+ PyVarObject_HEAD_INIT(NULL, 0)
2690
+ "MethInstance",
2691
+ sizeof(PyObject),
2692
+ .tp_new = PyType_GenericNew,
2693
+ .tp_flags = Py_TPFLAGS_DEFAULT,
2694
+ .tp_methods = meth_instance_methods,
2695
+ .tp_doc = (char*)PyDoc_STR(
2696
+ "Class with normal (instance) methods to test calling conventions"),
2697
+ };
2698
+ static PyMethodDef meth_class_methods[] = {
2699
+ {"meth_varargs", meth_varargs, METH_VARARGS|METH_CLASS},
2700
+ {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS|METH_CLASS},
2701
+ {"meth_o", meth_o, METH_O|METH_CLASS},
2702
+ {"meth_noargs", meth_noargs, METH_NOARGS|METH_CLASS},
2703
+ {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL|METH_CLASS},
2704
+ {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS|METH_CLASS},
2705
+ {NULL, NULL} /* sentinel */
2706
+ };
2707
+ static PyTypeObject MethClass_Type = {
2708
+ PyVarObject_HEAD_INIT(NULL, 0)
2709
+ "MethClass",
2710
+ sizeof(PyObject),
2711
+ .tp_new = PyType_GenericNew,
2712
+ .tp_flags = Py_TPFLAGS_DEFAULT,
2713
+ .tp_methods = meth_class_methods,
2714
+ .tp_doc = PyDoc_STR(
2715
+ "Class with class methods to test calling conventions"),
2716
+ };
2717
+ static PyMethodDef meth_static_methods[] = {
2718
+ {"meth_varargs", meth_varargs, METH_VARARGS|METH_STATIC},
2719
+ {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS|METH_STATIC},
2720
+ {"meth_o", meth_o, METH_O|METH_STATIC},
2721
+ {"meth_noargs", meth_noargs, METH_NOARGS|METH_STATIC},
2722
+ {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL|METH_STATIC},
2723
+ {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS|METH_STATIC},
2724
+ {NULL, NULL} /* sentinel */
2725
+ };
2726
+ static PyTypeObject MethStatic_Type = {
2727
+ PyVarObject_HEAD_INIT(NULL, 0)
2728
+ "MethStatic",
2729
+ sizeof(PyObject),
2730
+ .tp_new = PyType_GenericNew,
2731
+ .tp_flags = Py_TPFLAGS_DEFAULT,
2732
+ .tp_methods = meth_static_methods,
2733
+ .tp_doc = PyDoc_STR(
2734
+ "Class with static methods to test calling conventions"),
2735
+ };
2736
+ /* ContainerNoGC -- a simple container without GC methods */
2737
+ typedef struct {
2738
+ PyObject_HEAD
2739
+ PyObject *value;
2740
+ } ContainerNoGCobject;
2741
+ static PyObject *
2742
+ ContainerNoGC_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2743
+ {
2744
+ PyObject *value;
2745
+ char *names[] = {"value", NULL};
2746
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", names, &value)) {
2747
+ return NULL;
2748
+ }
2749
+ PyObject *self = type->tp_alloc(type, 0);
2750
+ if (self == NULL) {
2751
+ return NULL;
2752
+ }
2753
+ Py_INCREF(value);
2754
+ ((ContainerNoGCobject *)self)->value = value;
2755
+ return self;
2756
+ }
2757
+ static void
2758
+ ContainerNoGC_dealloc(PyObject *op)
2759
+ {
2760
+ ContainerNoGCobject *self = (ContainerNoGCobject*)op;
2761
+ Py_DECREF(self->value);
2762
+ Py_TYPE(self)->tp_free(self);
2763
+ }
2764
+ static PyMemberDef ContainerNoGC_members[] = {
2765
+ {"value", _Py_T_OBJECT, offsetof(ContainerNoGCobject, value), Py_READONLY,
2766
+ PyDoc_STR("a container value for test purposes")},
2767
+ {0}
2768
+ };
2769
+ static PyTypeObject ContainerNoGC_type = {
2770
+ PyVarObject_HEAD_INIT(NULL, 0)
2771
+ "_testcapi.ContainerNoGC",
2772
+ sizeof(ContainerNoGCobject),
2773
+ .tp_dealloc = ContainerNoGC_dealloc,
2774
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2775
+ .tp_members = ContainerNoGC_members,
2776
+ .tp_new = ContainerNoGC_new,
2777
+ };
2778
+ /* Manually allocated heap type */
2779
+ typedef struct {
2780
+ PyObject_HEAD
2781
+ PyObject *dict;
2782
+ } ManualHeapType;
2783
+ static int
2784
+ ManualHeapType_traverse(PyObject *self, visitproc visit, void *arg)
2785
+ {
2786
+ ManualHeapType *mht = (ManualHeapType *)self;
2787
+ Py_VISIT(mht->dict);
2788
+ return 0;
2789
+ }
2790
+ static void
2791
+ ManualHeapType_dealloc(PyObject *self)
2792
+ {
2793
+ ManualHeapType *mht = (ManualHeapType *)self;
2794
+ PyObject_GC_UnTrack(self);
2795
+ Py_XDECREF(mht->dict);
2796
+ PyTypeObject *type = Py_TYPE(self);
2797
+ Py_TYPE(self)->tp_free(self);
2798
+ Py_DECREF(type);
2799
+ }
2800
+ static PyObject *
2801
+ create_manual_heap_type(void)
2802
+ {
2803
+ // gh-128923: Ensure that a heap type allocated through PyType_Type.tp_alloc
2804
+ // with minimal initialization works correctly.
2805
+ PyHeapTypeObject *heap_type = (PyHeapTypeObject *)PyType_Type.tp_alloc(&PyType_Type, 0);
2806
+ if (heap_type == NULL) {
2807
+ return NULL;
2808
+ }
2809
+ PyTypeObject* type = &heap_type->ht_type;
2810
+ type->tp_basicsize = sizeof(ManualHeapType);
2811
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | Py_TPFLAGS_HAVE_GC;
2812
+ type->tp_new = PyType_GenericNew;
2813
+ type->tp_name = "ManualHeapType";
2814
+ type->tp_dictoffset = offsetof(ManualHeapType, dict);
2815
+ type->tp_traverse = ManualHeapType_traverse;
2816
+ type->tp_dealloc = ManualHeapType_dealloc;
2817
+ heap_type->ht_name = PyUnicode_FromString(type->tp_name);
2818
+ if (!heap_type->ht_name) {
2819
+ Py_DECREF(type);
2820
+ return NULL;
2821
+ }
2822
+ heap_type->ht_qualname = Py_NewRef(heap_type->ht_name);
2823
+ if (PyType_Ready(type) < 0) {
2824
+ Py_DECREF(type);
2825
+ return NULL;
2826
+ }
2827
+ return (PyObject *)type;
2828
+ }
2829
+ typedef struct {
2830
+ PyObject_VAR_HEAD
2831
+ } ManagedDictObject;
2832
+ int ManagedDict_traverse(PyObject *self, visitproc visit, void *arg) {
2833
+ PyObject_VisitManagedDict(self, visit, arg);
2834
+ Py_VISIT(Py_TYPE(self));
2835
+ return 0;
2836
+ }
2837
+ int ManagedDict_clear(PyObject *self) {
2838
+ PyObject_ClearManagedDict(self);
2839
+ return 0;
2840
+ }
2841
+ static PyGetSetDef ManagedDict_getset[] = {
2842
+ {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
2843
+ {NULL, NULL, NULL, NULL, NULL},
2844
+ };
2845
+ static PyType_Slot ManagedDict_slots[] = {
2846
+ {Py_tp_new, (void *)PyType_GenericNew},
2847
+ {Py_tp_getset, (void *)ManagedDict_getset},
2848
+ {Py_tp_traverse, (void *)ManagedDict_traverse},
2849
+ {Py_tp_clear, (void *)ManagedDict_clear},
2850
+ {0}
2851
+ };
2852
+ static PyType_Spec ManagedDict_spec = {
2853
+ "_testcapi.ManagedDictType",
2854
+ sizeof(ManagedDictObject),
2855
+ 0, // itemsize
2856
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_MANAGED_DICT | Py_TPFLAGS_HEAPTYPE | Py_TPFLAGS_HAVE_GC,
2857
+ ManagedDict_slots
2858
+ };
2859
+ static PyObject *
2860
+ create_managed_dict_type(void)
2861
+ {
2862
+ return PyType_FromSpec(&ManagedDict_spec);
2863
+ }
2864
+ static int
2865
+ _testcapi_exec(PyObject *m)
2866
+ {
2867
+ Py_SET_TYPE(&_HashInheritanceTester_Type, &PyType_Type);
2868
+ if (PyType_Ready(&_HashInheritanceTester_Type) < 0) {
2869
+ return -1;
2870
+ }
2871
+ if (PyType_Ready(&matmulType) < 0)
2872
+ return -1;
2873
+ Py_INCREF(&matmulType);
2874
+ PyModule_AddObject(m, "matmulType", (PyObject *)&matmulType);
2875
+ if (PyType_Ready(&ipowType) < 0) {
2876
+ return -1;
2877
+ }
2878
+ Py_INCREF(&ipowType);
2879
+ PyModule_AddObject(m, "ipowType", (PyObject *)&ipowType);
2880
+ if (PyType_Ready(&awaitType) < 0)
2881
+ return -1;
2882
+ Py_INCREF(&awaitType);
2883
+ PyModule_AddObject(m, "awaitType", (PyObject *)&awaitType);
2884
+ MyList_Type.tp_base = &PyList_Type;
2885
+ if (PyType_Ready(&MyList_Type) < 0)
2886
+ return -1;
2887
+ Py_INCREF(&MyList_Type);
2888
+ PyModule_AddObject(m, "MyList", (PyObject *)&MyList_Type);
2889
+ if (PyType_Ready(&GenericAlias_Type) < 0)
2890
+ return -1;
2891
+ Py_INCREF(&GenericAlias_Type);
2892
+ PyModule_AddObject(m, "GenericAlias", (PyObject *)&GenericAlias_Type);
2893
+ if (PyType_Ready(&Generic_Type) < 0)
2894
+ return -1;
2895
+ Py_INCREF(&Generic_Type);
2896
+ PyModule_AddObject(m, "Generic", (PyObject *)&Generic_Type);
2897
+ if (PyType_Ready(&MethInstance_Type) < 0)
2898
+ return -1;
2899
+ Py_INCREF(&MethInstance_Type);
2900
+ PyModule_AddObject(m, "MethInstance", (PyObject *)&MethInstance_Type);
2901
+ if (PyType_Ready(&MethClass_Type) < 0)
2902
+ return -1;
2903
+ Py_INCREF(&MethClass_Type);
2904
+ PyModule_AddObject(m, "MethClass", (PyObject *)&MethClass_Type);
2905
+ if (PyType_Ready(&MethStatic_Type) < 0)
2906
+ return -1;
2907
+ Py_INCREF(&MethStatic_Type);
2908
+ PyModule_AddObject(m, "MethStatic", (PyObject *)&MethStatic_Type);
2909
+ PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
2910
+ PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
2911
+ PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
2912
+ PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
2913
+ PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
2914
+ PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
2915
+ PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
2916
+ PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
2917
+ PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
2918
+ PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
2919
+ PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
2920
+ PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
2921
+ PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
2922
+ PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
2923
+ PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
2924
+ PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
2925
+ PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(LLONG_MAX));
2926
+ PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(LLONG_MIN));
2927
+ PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(ULLONG_MAX));
2928
+ PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2929
+ PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
2930
+ PyModule_AddObject(m, "SIZE_MAX", PyLong_FromSize_t(SIZE_MAX));
2931
+ PyModule_AddObject(m, "SIZEOF_WCHAR_T", PyLong_FromSsize_t(sizeof(wchar_t)));
2932
+ PyModule_AddObject(m, "SIZEOF_VOID_P", PyLong_FromSsize_t(sizeof(void*)));
2933
+ PyModule_AddObject(m, "SIZEOF_TIME_T", PyLong_FromSsize_t(sizeof(time_t)));
2934
+ PyModule_AddObject(m, "SIZEOF_PID_T", PyLong_FromSsize_t(sizeof(pid_t)));
2935
+ PyModule_AddObject(m, "Py_Version", PyLong_FromUnsignedLong(Py_Version));
2936
+ Py_INCREF(&PyInstanceMethod_Type);
2937
+ PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
2938
+ PyModule_AddIntConstant(m, "the_number_three", 3);
2939
+ PyModule_AddObject(m, "INT32_MIN", PyLong_FromInt32(INT32_MIN));
2940
+ PyModule_AddObject(m, "INT32_MAX", PyLong_FromInt32(INT32_MAX));
2941
+ PyModule_AddObject(m, "UINT32_MAX", PyLong_FromUInt32(UINT32_MAX));
2942
+ PyModule_AddObject(m, "INT64_MIN", PyLong_FromInt64(INT64_MIN));
2943
+ PyModule_AddObject(m, "INT64_MAX", PyLong_FromInt64(INT64_MAX));
2944
+ PyModule_AddObject(m, "UINT64_MAX", PyLong_FromUInt64(UINT64_MAX));
2945
+ #ifdef HAVE_PPOLL
2946
+ if (PyModule_AddObjectRef(m, "HAVE_PPOLL", Py_True) < 0) {
2947
+ return -1;
2948
+ }
2949
+ #endif
2950
+ if (PyModule_AddIntMacro(m, _Py_STACK_GROWS_DOWN)) {
2951
+ return -1;
2952
+ }
2953
+ if (PyModule_AddIntMacro(m, Py_single_input)) {
2954
+ return -1;
2955
+ }
2956
+ if (PyModule_AddIntMacro(m, Py_file_input)) {
2957
+ return -1;
2958
+ }
2959
+ if (PyModule_AddIntMacro(m, Py_eval_input)) {
2960
+ return -1;
2961
+ }
2962
+ testcapistate_t *state = get_testcapi_state(m);
2963
+ state->error = PyErr_NewException("_testcapi.error", NULL, NULL);
2964
+ PyModule_AddObject(m, "error", state->error);
2965
+ if (PyType_Ready(&ContainerNoGC_type) < 0) {
2966
+ return -1;
2967
+ }
2968
+ Py_INCREF(&ContainerNoGC_type);
2969
+ if (PyModule_AddObject(m, "ContainerNoGC",
2970
+ (PyObject *) &ContainerNoGC_type) < 0)
2971
+ return -1;
2972
+ PyObject *manual_heap_type = create_manual_heap_type();
2973
+ if (manual_heap_type == NULL) {
2974
+ return -1;
2975
+ }
2976
+ if (PyModule_Add(m, "ManualHeapType", manual_heap_type) < 0) {
2977
+ return -1;
2978
+ }
2979
+ PyObject *managed_dict_type = create_managed_dict_type();
2980
+ if (managed_dict_type == NULL) {
2981
+ return -1;
2982
+ }
2983
+ if (PyModule_Add(m, "ManagedDictType", managed_dict_type) < 0) {
2984
+ return -1;
2985
+ }
2986
+ /* Include tests from the _testcapi/ directory */
2987
+ if (_PyTestCapi_Init_Vectorcall(m) < 0) {
2988
+ return -1;
2989
+ }
2990
+ if (_PyTestCapi_Init_Heaptype(m) < 0) {
2991
+ return -1;
2992
+ }
2993
+ if (_PyTestCapi_Init_Abstract(m) < 0) {
2994
+ return -1;
2995
+ }
2996
+ if (_PyTestCapi_Init_Bytes(m) < 0) {
2997
+ return -1;
2998
+ }
2999
+ if (_PyTestCapi_Init_Unicode(m) < 0) {
3000
+ return -1;
3001
+ }
3002
+ if (_PyTestCapi_Init_GetArgs(m) < 0) {
3003
+ return -1;
3004
+ }
3005
+ if (_PyTestCapi_Init_DateTime(m) < 0) {
3006
+ return -1;
3007
+ }
3008
+ if (_PyTestCapi_Init_Docstring(m) < 0) {
3009
+ return -1;
3010
+ }
3011
+ if (_PyTestCapi_Init_Mem(m) < 0) {
3012
+ return -1;
3013
+ }
3014
+ if (_PyTestCapi_Init_Watchers(m) < 0) {
3015
+ return -1;
3016
+ }
3017
+ if (_PyTestCapi_Init_Long(m) < 0) {
3018
+ return -1;
3019
+ }
3020
+ if (_PyTestCapi_Init_Float(m) < 0) {
3021
+ return -1;
3022
+ }
3023
+ if (_PyTestCapi_Init_Complex(m) < 0) {
3024
+ return -1;
3025
+ }
3026
+ if (_PyTestCapi_Init_Numbers(m) < 0) {
3027
+ return -1;
3028
+ }
3029
+ if (_PyTestCapi_Init_Dict(m) < 0) {
3030
+ return -1;
3031
+ }
3032
+ if (_PyTestCapi_Init_Set(m) < 0) {
3033
+ return -1;
3034
+ }
3035
+ if (_PyTestCapi_Init_List(m) < 0) {
3036
+ return -1;
3037
+ }
3038
+ if (_PyTestCapi_Init_Tuple(m) < 0) {
3039
+ return -1;
3040
+ }
3041
+ if (_PyTestCapi_Init_Structmember(m) < 0) {
3042
+ return -1;
3043
+ }
3044
+ if (_PyTestCapi_Init_Exceptions(m) < 0) {
3045
+ return -1;
3046
+ }
3047
+ if (_PyTestCapi_Init_Code(m) < 0) {
3048
+ return -1;
3049
+ }
3050
+ if (_PyTestCapi_Init_Buffer(m) < 0) {
3051
+ return -1;
3052
+ }
3053
+ if (_PyTestCapi_Init_File(m) < 0) {
3054
+ return -1;
3055
+ }
3056
+ if (_PyTestCapi_Init_Codec(m) < 0) {
3057
+ return -1;
3058
+ }
3059
+ if (_PyTestCapi_Init_Immortal(m) < 0) {
3060
+ return -1;
3061
+ }
3062
+ if (_PyTestCapi_Init_GC(m) < 0) {
3063
+ return -1;
3064
+ }
3065
+ if (_PyTestCapi_Init_PyAtomic(m) < 0) {
3066
+ return -1;
3067
+ }
3068
+ if (_PyTestCapi_Init_Run(m) < 0) {
3069
+ return -1;
3070
+ }
3071
+ if (_PyTestCapi_Init_Hash(m) < 0) {
3072
+ return -1;
3073
+ }
3074
+ if (_PyTestCapi_Init_Time(m) < 0) {
3075
+ return -1;
3076
+ }
3077
+ if (_PyTestCapi_Init_Modsupport(m) < 0) {
3078
+ return -1;
3079
+ }
3080
+ if (_PyTestCapi_Init_Monitoring(m) < 0) {
3081
+ return -1;
3082
+ }
3083
+ if (_PyTestCapi_Init_Object(m) < 0) {
3084
+ return -1;
3085
+ }
3086
+ if (_PyTestCapi_Init_Config(m) < 0) {
3087
+ return -1;
3088
+ }
3089
+ if (_PyTestCapi_Init_Import(m) < 0) {
3090
+ return -1;
3091
+ }
3092
+ if (_PyTestCapi_Init_Frame(m) < 0) {
3093
+ return -1;
3094
+ }
3095
+ if (_PyTestCapi_Init_Type(m) < 0) {
3096
+ return -1;
3097
+ }
3098
+ if (_PyTestCapi_Init_Function(m) < 0) {
3099
+ return -1;
3100
+ }
3101
+ if (_PyTestCapi_Init_Module(m) < 0) {
3102
+ return -1;
3103
+ }
3104
+ return 0;
3105
+ }
3106
+ PyABIInfo_VAR(abi_info);
3107
+ static PyModuleDef_Slot _testcapi_slots[] = {
3108
+ {Py_mod_abi, &abi_info},
3109
+ {Py_mod_exec, _testcapi_exec},
3110
+ {Py_mod_gil, Py_MOD_GIL_NOT_USED},
3111
+ {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
3112
+ {0, NULL},
3113
+ };
3114
+ static struct PyModuleDef _testcapimodule = {
3115
+ PyModuleDef_HEAD_INIT,
3116
+ .m_name = "_testcapi",
3117
+ .m_size = sizeof(testcapistate_t),
3118
+ .m_methods = TestMethods,
3119
+ .m_slots = _testcapi_slots
3120
+ };
3121
+ PyMODINIT_FUNC
3122
+ PyInit__testcapi(void)
3123
+ {
3124
+ return PyModuleDef_Init(&_testcapimodule);
3125
+ }
3126
+
3127
+ // _testclinic_limited can built with the Py_BUILD_CORE_BUILTIN macro defined
3128
+ // if one of the Modules/Setup files asks to build it as "static" (gh-109723).
3129
+ #undef Py_BUILD_CORE
3130
+ #undef Py_BUILD_CORE_MODULE
3131
+ #undef Py_BUILD_CORE_BUILTIN
3132
+ // For now, AC only supports the limited C API version 3.13
3133
+ #include "pyconfig.h" // Py_GIL_DISABLED
3134
+ #ifndef Py_GIL_DISABLED
3135
+ # define Py_LIMITED_API 0x030d0000
3136
+ #endif
3137
+ /* Always enable assertions */
3138
+ #undef NDEBUG
3139
+ #include "Python.h"
3140
+ #include "clinic/_testclinic_limited.c.h"
3141
+ /*[clinic input]
3142
+ module _testclinic_limited
3143
+ [clinic start generated code]*/
3144
+ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd408149a4fc0dbb]*/
3145
+ /*[clinic input]
3146
+ test_empty_function
3147
+ [clinic start generated code]*/
3148
+ static PyObject *
3149
+ test_empty_function_impl(PyObject *module)
3150
+ /*[clinic end generated code: output=0f8aeb3ddced55cb input=0dd7048651ad4ae4]*/
3151
+ {
3152
+ Py_RETURN_NONE;
3153
+ }
3154
+ /*[clinic input]
3155
+ my_int_func -> int
3156
+ arg: int
3157
+ /
3158
+ [clinic start generated code]*/
3159
+ static int
3160
+ my_int_func_impl(PyObject *module, int arg)
3161
+ /*[clinic end generated code: output=761cd54582f10e4f input=16eb8bba71d82740]*/
3162
+ {
3163
+ return arg;
3164
+ }
3165
+ /*[clinic input]
3166
+ my_int_sum -> int
3167
+ x: int
3168
+ y: int
3169
+ /
3170
+ [clinic start generated code]*/
3171
+ static int
3172
+ my_int_sum_impl(PyObject *module, int x, int y)
3173
+ /*[clinic end generated code: output=3e52db9ab5f37e2f input=0edb6796813bf2d3]*/
3174
+ {
3175
+ return x + y;
3176
+ }
3177
+ /*[clinic input]
3178
+ my_float_sum -> float
3179
+ x: float
3180
+ y: float
3181
+ /
3182
+ [clinic start generated code]*/
3183
+ static float
3184
+ my_float_sum_impl(PyObject *module, float x, float y)
3185
+ /*[clinic end generated code: output=634f59a5a419cad7 input=d4b5313bdf4dc377]*/
3186
+ {
3187
+ return x + y;
3188
+ }
3189
+ /*[clinic input]
3190
+ my_double_sum -> double
3191
+ x: double
3192
+ y: double
3193
+ /
3194
+ [clinic start generated code]*/
3195
+ static double
3196
+ my_double_sum_impl(PyObject *module, double x, double y)
3197
+ /*[clinic end generated code: output=a75576d9e4d8557f input=16b11c8aba172801]*/
3198
+ {
3199
+ return x + y;
3200
+ }
3201
+ /*[clinic input]
3202
+ get_file_descriptor -> int
3203
+ file as fd: fildes
3204
+ /
3205
+ Get a file descriptor.
3206
+ [clinic start generated code]*/
3207
+ static int
3208
+ get_file_descriptor_impl(PyObject *module, int fd)
3209
+ /*[clinic end generated code: output=80051ebad54db8a8 input=82e2a1418848cd5b]*/
3210
+ {
3211
+ return fd;
3212
+ }
3213
+ static PyMethodDef tester_methods[] = {
3214
+ TEST_EMPTY_FUNCTION_METHODDEF
3215
+ MY_INT_FUNC_METHODDEF
3216
+ MY_INT_SUM_METHODDEF
3217
+ MY_FLOAT_SUM_METHODDEF
3218
+ MY_DOUBLE_SUM_METHODDEF
3219
+ GET_FILE_DESCRIPTOR_METHODDEF
3220
+ {NULL, NULL}
3221
+ };
3222
+ static struct PyModuleDef _testclinic_module = {
3223
+ PyModuleDef_HEAD_INIT,
3224
+ .m_name = "_testclinic_limited",
3225
+ .m_size = 0,
3226
+ .m_methods = tester_methods,
3227
+ };
3228
+ PyMODINIT_FUNC
3229
+ PyInit__testclinic_limited(void)
3230
+ {
3231
+ PyObject *m = PyModule_Create(&_testclinic_module);
3232
+ if (m == NULL) {
3233
+ return NULL;
3234
+ }
3235
+ #ifdef Py_GIL_DISABLED
3236
+ PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
3237
+ #endif
3238
+ return m;
3239
+ }
3240
+
3241
+
3242
+ """
cpython_chunk_33.py ADDED
The diff for this file is too large to render. See raw diff
 
cpython_chunk_4.py ADDED
The diff for this file is too large to render. See raw diff