blob: 2b261b6c86dc4b0b1c5500f82c5eb1bfdcc093a5 [file] [log] [blame]
Tim Peters9ea17ac2001-02-02 05:57:15 +00001/*
2 * C Extension module to test Python interpreter C APIs.
3 *
4 * The 'test_*' functions exported by this module are run as part of the
5 * standard Python regression test, via Lib/test/test_capi.py.
6 */
7
Victor Stinner5c75f372019-04-17 23:02:26 +02008/* The Visual Studio projects builds _testcapi with Py_BUILD_CORE_MODULE
9 define, but we only want to test the public C API, not the internal
10 C API. */
11#undef Py_BUILD_CORE_MODULE
12
Neal Norwitz8866e0a2007-10-27 04:01:17 +000013#define PY_SSIZE_T_CLEAN
14
Tim Peters9ea17ac2001-02-02 05:57:15 +000015#include "Python.h"
Benjamin Peterson91d58bd2009-12-13 21:30:54 +000016#include "datetime.h"
Serhiy Storchakab5181342015-02-06 08:58:56 +020017#include "marshal.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010018#include "pythread.h"
19#include "structmember.h"
20#include <float.h>
Victor Stinner56e8c292014-07-21 12:30:22 +020021#include <signal.h>
Tim Peters9ea17ac2001-02-02 05:57:15 +000022
Victor Stinner95e9cef2015-03-28 01:26:47 +010023#ifdef MS_WINDOWS
Victor Stinner09e5cf22015-03-30 00:09:18 +020024# include <winsock2.h> /* struct timeval */
Victor Stinner95e9cef2015-03-28 01:26:47 +010025#endif
26
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020027#ifdef HAVE_SYS_WAIT_H
28#include <sys/wait.h> /* For W_STOPCODE */
29#endif
30
Victor Stinner5ed69952018-11-06 15:59:52 +010031#ifdef Py_BUILD_CORE
32# error "_testcapi must test the public Python C API, not CPython internal C API"
33#endif
34
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035static PyObject *TestError; /* set to exception object in init */
Tim Peters9ea17ac2001-02-02 05:57:15 +000036
Tim Peters91621db2001-06-12 20:10:01 +000037/* Raise TestError with test_name + ": " + msg, and return NULL. */
38
39static PyObject *
40raiseTestError(const char* test_name, const char* msg)
41{
Victor Stinner6ced7c42011-03-21 18:15:42 +010042 PyErr_Format(TestError, "%s: %s", test_name, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 return NULL;
Tim Peters91621db2001-06-12 20:10:01 +000044}
45
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +000046/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
Tim Peters9ea17ac2001-02-02 05:57:15 +000047
48 The ones derived from autoconf on the UNIX-like OSes can be relied
49 upon (in the absence of sloppy cross-compiling), but the Windows
50 platforms have these hardcoded. Better safe than sorry.
51*/
52static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +000053sizeof_error(const char* fatname, const char* typname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 int expected, int got)
Tim Peters9ea17ac2001-02-02 05:57:15 +000055{
Victor Stinner499dfcf2011-03-21 13:26:24 +010056 PyErr_Format(TestError,
57 "%s #define == %d but sizeof(%s) == %d",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 fatname, expected, typname, got);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 return (PyObject*)NULL;
Tim Peters9ea17ac2001-02-02 05:57:15 +000060}
61
62static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053063test_config(PyObject *self, PyObject *Py_UNUSED(ignored))
Tim Peters9ea17ac2001-02-02 05:57:15 +000064{
Tim Peters9ea17ac2001-02-02 05:57:15 +000065#define CHECK_SIZEOF(FATNAME, TYPE) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (FATNAME != sizeof(TYPE)) \
67 return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
Tim Peters9ea17ac2001-02-02 05:57:15 +000068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 CHECK_SIZEOF(SIZEOF_SHORT, short);
70 CHECK_SIZEOF(SIZEOF_INT, int);
71 CHECK_SIZEOF(SIZEOF_LONG, long);
72 CHECK_SIZEOF(SIZEOF_VOID_P, void*);
73 CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
Benjamin Petersonaf580df2016-09-06 10:46:49 -070074 CHECK_SIZEOF(SIZEOF_LONG_LONG, long long);
Tim Peters9ea17ac2001-02-02 05:57:15 +000075
76#undef CHECK_SIZEOF
77
Serhiy Storchaka228b12e2017-01-23 09:47:21 +020078 Py_RETURN_NONE;
Tim Peters9ea17ac2001-02-02 05:57:15 +000079}
80
Tim Peters5c4d5bf2001-02-12 22:13:26 +000081static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053082test_sizeof_c_types(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner01076552013-10-29 19:39:52 +010083{
Ned Deilye37a1942015-03-05 15:47:10 -080084#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
Serhiy Storchakab48af342015-02-26 15:27:57 +020085#pragma GCC diagnostic push
86#pragma GCC diagnostic ignored "-Wtype-limits"
87#endif
Victor Stinnerf866f972013-10-29 19:59:31 +010088#define CHECK_SIZEOF(TYPE, EXPECTED) \
Victor Stinner01076552013-10-29 19:39:52 +010089 if (EXPECTED != sizeof(TYPE)) { \
90 PyErr_Format(TestError, \
91 "sizeof(%s) = %u instead of %u", \
92 #TYPE, sizeof(TYPE), EXPECTED); \
93 return (PyObject*)NULL; \
94 }
Victor Stinnerf866f972013-10-29 19:59:31 +010095#define IS_SIGNED(TYPE) (((TYPE)-1) < (TYPE)0)
96#define CHECK_SIGNNESS(TYPE, SIGNED) \
97 if (IS_SIGNED(TYPE) != SIGNED) { \
98 PyErr_Format(TestError, \
99 "%s signness is, instead of %i", \
100 #TYPE, IS_SIGNED(TYPE), SIGNED); \
101 return (PyObject*)NULL; \
102 }
Victor Stinner01076552013-10-29 19:39:52 +0100103
104 /* integer types */
Victor Stinnerf866f972013-10-29 19:59:31 +0100105 CHECK_SIZEOF(Py_UCS1, 1);
106 CHECK_SIZEOF(Py_UCS2, 2);
107 CHECK_SIZEOF(Py_UCS4, 4);
108 CHECK_SIGNNESS(Py_UCS1, 0);
109 CHECK_SIGNNESS(Py_UCS2, 0);
110 CHECK_SIGNNESS(Py_UCS4, 0);
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700111 CHECK_SIZEOF(int32_t, 4);
112 CHECK_SIGNNESS(int32_t, 1);
113 CHECK_SIZEOF(uint32_t, 4);
114 CHECK_SIGNNESS(uint32_t, 0);
115 CHECK_SIZEOF(int64_t, 8);
116 CHECK_SIGNNESS(int64_t, 1);
117 CHECK_SIZEOF(uint64_t, 8);
118 CHECK_SIGNNESS(uint64_t, 0);
Victor Stinner01076552013-10-29 19:39:52 +0100119
120 /* pointer/size types */
Victor Stinnerf866f972013-10-29 19:59:31 +0100121 CHECK_SIZEOF(size_t, sizeof(void *));
122 CHECK_SIGNNESS(size_t, 0);
123 CHECK_SIZEOF(Py_ssize_t, sizeof(void *));
124 CHECK_SIGNNESS(Py_ssize_t, 1);
125
Benjamin Petersonca470632016-09-06 13:47:26 -0700126 CHECK_SIZEOF(uintptr_t, sizeof(void *));
127 CHECK_SIGNNESS(uintptr_t, 0);
128 CHECK_SIZEOF(intptr_t, sizeof(void *));
129 CHECK_SIGNNESS(intptr_t, 1);
Victor Stinner01076552013-10-29 19:39:52 +0100130
Serhiy Storchakad1302c02017-01-23 10:23:58 +0200131 Py_RETURN_NONE;
Victor Stinner01076552013-10-29 19:39:52 +0100132
Victor Stinnerf866f972013-10-29 19:59:31 +0100133#undef IS_SIGNED
134#undef CHECK_SIGNESS
Victor Stinner01076552013-10-29 19:39:52 +0100135#undef CHECK_SIZEOF
Ned Deilye37a1942015-03-05 15:47:10 -0800136#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
Serhiy Storchakab48af342015-02-26 15:27:57 +0200137#pragma GCC diagnostic pop
138#endif
Victor Stinner01076552013-10-29 19:39:52 +0100139}
140
141
142static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530143test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored))
Tim Peters5c4d5bf2001-02-12 22:13:26 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 PyObject* list;
146 int i;
Tim Peters5c4d5bf2001-02-12 22:13:26 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 /* SF bug 132008: PyList_Reverse segfaults */
Tim Peters5c4d5bf2001-02-12 22:13:26 +0000149#define NLIST 30
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 list = PyList_New(NLIST);
151 if (list == (PyObject*)NULL)
152 return (PyObject*)NULL;
153 /* list = range(NLIST) */
154 for (i = 0; i < NLIST; ++i) {
155 PyObject* anint = PyLong_FromLong(i);
156 if (anint == (PyObject*)NULL) {
157 Py_DECREF(list);
158 return (PyObject*)NULL;
159 }
160 PyList_SET_ITEM(list, i, anint);
161 }
162 /* list.reverse(), via PyList_Reverse() */
163 i = PyList_Reverse(list); /* should not blow up! */
164 if (i != 0) {
165 Py_DECREF(list);
166 return (PyObject*)NULL;
167 }
168 /* Check that list == range(29, -1, -1) now */
169 for (i = 0; i < NLIST; ++i) {
170 PyObject* anint = PyList_GET_ITEM(list, i);
171 if (PyLong_AS_LONG(anint) != NLIST-1-i) {
172 PyErr_SetString(TestError,
173 "test_list_api: reverse screwed up");
174 Py_DECREF(list);
175 return (PyObject*)NULL;
176 }
177 }
178 Py_DECREF(list);
Tim Peters5c4d5bf2001-02-12 22:13:26 +0000179#undef NLIST
180
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200181 Py_RETURN_NONE;
Tim Peters5c4d5bf2001-02-12 22:13:26 +0000182}
183
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000184static int
185test_dict_inner(int count)
186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 Py_ssize_t pos = 0, iterations = 0;
188 int i;
189 PyObject *dict = PyDict_New();
190 PyObject *v, *k;
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (dict == NULL)
193 return -1;
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 for (i = 0; i < count; i++) {
196 v = PyLong_FromLong(i);
Christian Heimesff369a52013-07-26 14:52:18 +0200197 if (v == NULL) {
Christian Heimesff369a52013-07-26 14:52:18 +0200198 return -1;
199 }
Christian Heimes97cb67b2013-07-20 15:01:26 +0200200 if (PyDict_SetItem(dict, v, v) < 0) {
201 Py_DECREF(v);
202 return -1;
203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Py_DECREF(v);
205 }
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 while (PyDict_Next(dict, &pos, &k, &v)) {
208 PyObject *o;
209 iterations++;
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 i = PyLong_AS_LONG(v) + 1;
212 o = PyLong_FromLong(i);
213 if (o == NULL)
214 return -1;
215 if (PyDict_SetItem(dict, k, o) < 0) {
216 Py_DECREF(o);
217 return -1;
218 }
219 Py_DECREF(o);
220 }
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_DECREF(dict);
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (iterations != count) {
225 PyErr_SetString(
226 TestError,
227 "test_dict_iteration: dict iteration went wrong ");
228 return -1;
229 } else {
230 return 0;
231 }
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000232}
233
234static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530235test_dict_iteration(PyObject* self, PyObject *Py_UNUSED(ignored))
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 int i;
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 for (i = 0; i < 200; i++) {
240 if (test_dict_inner(i) < 0) {
241 return NULL;
242 }
243 }
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000244
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200245 Py_RETURN_NONE;
Guido van Rossumeb0d9922001-04-13 17:08:15 +0000246}
247
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200248static PyObject*
249dict_getitem_knownhash(PyObject *self, PyObject *args)
250{
251 PyObject *mp, *key, *result;
252 Py_ssize_t hash;
253
254 if (!PyArg_ParseTuple(args, "OOn:dict_getitem_knownhash",
255 &mp, &key, &hash)) {
256 return NULL;
257 }
258
259 result = _PyDict_GetItem_KnownHash(mp, key, (Py_hash_t)hash);
260 if (result == NULL && !PyErr_Occurred()) {
261 _PyErr_SetKeyError(key);
262 return NULL;
263 }
264
265 Py_XINCREF(result);
266 return result;
267}
Tim Peters91621db2001-06-12 20:10:01 +0000268
Victor Stinner3d3f2642016-12-15 17:21:23 +0100269static PyObject*
270dict_hassplittable(PyObject *self, PyObject *arg)
271{
272 if (!PyDict_Check(arg)) {
273 PyErr_Format(PyExc_TypeError,
274 "dict_hassplittable() argument must be dict, not '%s'",
275 arg->ob_type->tp_name);
276 return NULL;
277 }
278
279 return PyBool_FromLong(_PyDict_HasSplitTable((PyDictObject*)arg));
280}
281
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000282/* Issue #4701: Check that PyObject_Hash implicitly calls
283 * PyType_Ready if it hasn't already been called
284 */
285static PyTypeObject _HashInheritanceTester_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 PyVarObject_HEAD_INIT(NULL, 0)
287 "hashinheritancetester", /* Name of this type */
288 sizeof(PyObject), /* Basic object size */
289 0, /* Item size for varobject */
290 (destructor)PyObject_Del, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200291 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 0, /* tp_getattr */
293 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200294 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 0, /* tp_repr */
296 0, /* tp_as_number */
297 0, /* tp_as_sequence */
298 0, /* tp_as_mapping */
299 0, /* tp_hash */
300 0, /* tp_call */
301 0, /* tp_str */
302 PyObject_GenericGetAttr, /* tp_getattro */
303 0, /* tp_setattro */
304 0, /* tp_as_buffer */
305 Py_TPFLAGS_DEFAULT, /* tp_flags */
306 0, /* tp_doc */
307 0, /* tp_traverse */
308 0, /* tp_clear */
309 0, /* tp_richcompare */
310 0, /* tp_weaklistoffset */
311 0, /* tp_iter */
312 0, /* tp_iternext */
313 0, /* tp_methods */
314 0, /* tp_members */
315 0, /* tp_getset */
316 0, /* tp_base */
317 0, /* tp_dict */
318 0, /* tp_descr_get */
319 0, /* tp_descr_set */
320 0, /* tp_dictoffset */
321 0, /* tp_init */
322 0, /* tp_alloc */
323 PyType_GenericNew, /* tp_new */
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000324};
325
326static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530327test_lazy_hash_inheritance(PyObject* self, PyObject *Py_UNUSED(ignored))
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyTypeObject *type;
330 PyObject *obj;
Antoine Pitrou29aad002010-10-23 19:42:38 +0000331 Py_hash_t hash;
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 type = &_HashInheritanceTester_Type;
Benjamin Petersonf1726372009-05-05 21:11:54 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (type->tp_dict != NULL)
336 /* The type has already been initialized. This probably means
337 -R is being used. */
338 Py_RETURN_NONE;
Benjamin Petersonf1726372009-05-05 21:11:54 +0000339
340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 obj = PyObject_New(PyObject, type);
342 if (obj == NULL) {
343 PyErr_Clear();
344 PyErr_SetString(
345 TestError,
346 "test_lazy_hash_inheritance: failed to create object");
347 return NULL;
348 }
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (type->tp_dict != NULL) {
351 PyErr_SetString(
352 TestError,
353 "test_lazy_hash_inheritance: type initialised too soon");
354 Py_DECREF(obj);
355 return NULL;
356 }
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 hash = PyObject_Hash(obj);
359 if ((hash == -1) && PyErr_Occurred()) {
360 PyErr_Clear();
361 PyErr_SetString(
362 TestError,
363 "test_lazy_hash_inheritance: could not hash object");
364 Py_DECREF(obj);
365 return NULL;
366 }
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (type->tp_dict == NULL) {
369 PyErr_SetString(
370 TestError,
371 "test_lazy_hash_inheritance: type not initialised by hash()");
372 Py_DECREF(obj);
373 return NULL;
374 }
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (type->tp_hash != PyType_Type.tp_hash) {
377 PyErr_SetString(
378 TestError,
379 "test_lazy_hash_inheritance: unexpected hash function");
380 Py_DECREF(obj);
381 return NULL;
382 }
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_DECREF(obj);
Benjamin Petersonf1726372009-05-05 21:11:54 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 Py_RETURN_NONE;
Nick Coghlanf1f2f682008-12-30 07:29:12 +0000387}
388
389
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700390/* Tests of PyLong_{As, From}{Unsigned,}Long(), and
Tim Petersff70d3c2001-06-14 01:11:03 +0000391 PyLong_{As, From}{Unsigned,}LongLong().
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000392
393 Note that the meat of the test is contained in testcapi_long.h.
394 This is revolting, but delicate code duplication is worse: "almost
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700395 exactly the same" code is needed to test long long, but the ubiquitous
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000396 dependence on type names makes it impossible to use a parameterized
397 function. A giant macro would be even worse than this. A C++ template
398 would be perfect.
399
400 The "report an error" functions are deliberately not part of the #include
401 file: if the test fails, you can set a breakpoint in the appropriate
402 error function directly, and crawl back from there in the debugger.
403*/
404
405#define UNBIND(X) Py_DECREF(X); (X) = NULL
406
407static PyObject *
408raise_test_long_error(const char* msg)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 return raiseTestError("test_long_api", msg);
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000411}
412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413#define TESTNAME test_long_api_inner
414#define TYPENAME long
415#define F_S_TO_PY PyLong_FromLong
416#define F_PY_TO_S PyLong_AsLong
417#define F_U_TO_PY PyLong_FromUnsignedLong
418#define F_PY_TO_U PyLong_AsUnsignedLong
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000419
420#include "testcapi_long.h"
421
422static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530423test_long_api(PyObject* self, PyObject *Py_UNUSED(ignored))
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return TESTNAME(raise_test_long_error);
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000426}
427
428#undef TESTNAME
429#undef TYPENAME
430#undef F_S_TO_PY
431#undef F_PY_TO_S
432#undef F_U_TO_PY
433#undef F_PY_TO_U
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000434
Tim Peters91621db2001-06-12 20:10:01 +0000435static PyObject *
Tim Petersd1a7da62001-06-13 00:35:57 +0000436raise_test_longlong_error(const char* msg)
437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return raiseTestError("test_longlong_api", msg);
Tim Petersd1a7da62001-06-13 00:35:57 +0000439}
440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441#define TESTNAME test_longlong_api_inner
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700442#define TYPENAME long long
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443#define F_S_TO_PY PyLong_FromLongLong
444#define F_PY_TO_S PyLong_AsLongLong
445#define F_U_TO_PY PyLong_FromUnsignedLongLong
446#define F_PY_TO_U PyLong_AsUnsignedLongLong
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000447
448#include "testcapi_long.h"
Tim Petersd1a7da62001-06-13 00:35:57 +0000449
450static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000451test_longlong_api(PyObject* self, PyObject *args)
Tim Peters91621db2001-06-12 20:10:01 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 return TESTNAME(raise_test_longlong_error);
Tim Peters91621db2001-06-12 20:10:01 +0000454}
455
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000456#undef TESTNAME
457#undef TYPENAME
458#undef F_S_TO_PY
459#undef F_PY_TO_S
460#undef F_U_TO_PY
461#undef F_PY_TO_U
Tim Peterse7c1f9b2001-06-14 00:55:41 +0000462
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000463/* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG
464 is tested by test_long_api_inner. This test will concentrate on proper
465 handling of overflow.
466*/
467
468static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530469test_long_and_overflow(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyObject *num, *one, *temp;
472 long value;
473 int overflow;
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* Test that overflow is set properly for a large value. */
476 /* num is a number larger than LONG_MAX even on 64-bit platforms */
477 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
478 if (num == NULL)
479 return NULL;
480 overflow = 1234;
481 value = PyLong_AsLongAndOverflow(num, &overflow);
482 Py_DECREF(num);
483 if (value == -1 && PyErr_Occurred())
484 return NULL;
485 if (value != -1)
486 return raiseTestError("test_long_and_overflow",
487 "return value was not set to -1");
488 if (overflow != 1)
489 return raiseTestError("test_long_and_overflow",
490 "overflow was not set to 1");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* Same again, with num = LONG_MAX + 1 */
493 num = PyLong_FromLong(LONG_MAX);
494 if (num == NULL)
495 return NULL;
496 one = PyLong_FromLong(1L);
497 if (one == NULL) {
498 Py_DECREF(num);
499 return NULL;
500 }
501 temp = PyNumber_Add(num, one);
502 Py_DECREF(one);
503 Py_DECREF(num);
504 num = temp;
505 if (num == NULL)
506 return NULL;
507 overflow = 0;
508 value = PyLong_AsLongAndOverflow(num, &overflow);
509 Py_DECREF(num);
510 if (value == -1 && PyErr_Occurred())
511 return NULL;
512 if (value != -1)
513 return raiseTestError("test_long_and_overflow",
514 "return value was not set to -1");
515 if (overflow != 1)
516 return raiseTestError("test_long_and_overflow",
517 "overflow was not set to 1");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* Test that overflow is set properly for a large negative value. */
520 /* num is a number smaller than LONG_MIN even on 64-bit platforms */
521 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
522 if (num == NULL)
523 return NULL;
524 overflow = 1234;
525 value = PyLong_AsLongAndOverflow(num, &overflow);
526 Py_DECREF(num);
527 if (value == -1 && PyErr_Occurred())
528 return NULL;
529 if (value != -1)
530 return raiseTestError("test_long_and_overflow",
531 "return value was not set to -1");
532 if (overflow != -1)
533 return raiseTestError("test_long_and_overflow",
534 "overflow was not set to -1");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Same again, with num = LONG_MIN - 1 */
537 num = PyLong_FromLong(LONG_MIN);
538 if (num == NULL)
539 return NULL;
540 one = PyLong_FromLong(1L);
541 if (one == NULL) {
542 Py_DECREF(num);
543 return NULL;
544 }
545 temp = PyNumber_Subtract(num, one);
546 Py_DECREF(one);
547 Py_DECREF(num);
548 num = temp;
549 if (num == NULL)
550 return NULL;
551 overflow = 0;
552 value = PyLong_AsLongAndOverflow(num, &overflow);
553 Py_DECREF(num);
554 if (value == -1 && PyErr_Occurred())
555 return NULL;
556 if (value != -1)
557 return raiseTestError("test_long_and_overflow",
558 "return value was not set to -1");
559 if (overflow != -1)
560 return raiseTestError("test_long_and_overflow",
561 "overflow was not set to -1");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* Test that overflow is cleared properly for small values. */
564 num = PyLong_FromString("FF", NULL, 16);
565 if (num == NULL)
566 return NULL;
567 overflow = 1234;
568 value = PyLong_AsLongAndOverflow(num, &overflow);
569 Py_DECREF(num);
570 if (value == -1 && PyErr_Occurred())
571 return NULL;
572 if (value != 0xFF)
573 return raiseTestError("test_long_and_overflow",
574 "expected return value 0xFF");
575 if (overflow != 0)
576 return raiseTestError("test_long_and_overflow",
577 "overflow was not cleared");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 num = PyLong_FromString("-FF", NULL, 16);
580 if (num == NULL)
581 return NULL;
582 overflow = 0;
583 value = PyLong_AsLongAndOverflow(num, &overflow);
584 Py_DECREF(num);
585 if (value == -1 && PyErr_Occurred())
586 return NULL;
587 if (value != -0xFF)
588 return raiseTestError("test_long_and_overflow",
589 "expected return value 0xFF");
590 if (overflow != 0)
591 return raiseTestError("test_long_and_overflow",
592 "overflow was set incorrectly");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 num = PyLong_FromLong(LONG_MAX);
595 if (num == NULL)
596 return NULL;
597 overflow = 1234;
598 value = PyLong_AsLongAndOverflow(num, &overflow);
599 Py_DECREF(num);
600 if (value == -1 && PyErr_Occurred())
601 return NULL;
602 if (value != LONG_MAX)
603 return raiseTestError("test_long_and_overflow",
604 "expected return value LONG_MAX");
605 if (overflow != 0)
606 return raiseTestError("test_long_and_overflow",
607 "overflow was not cleared");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 num = PyLong_FromLong(LONG_MIN);
610 if (num == NULL)
611 return NULL;
612 overflow = 0;
613 value = PyLong_AsLongAndOverflow(num, &overflow);
614 Py_DECREF(num);
615 if (value == -1 && PyErr_Occurred())
616 return NULL;
617 if (value != LONG_MIN)
618 return raiseTestError("test_long_and_overflow",
619 "expected return value LONG_MIN");
620 if (overflow != 0)
621 return raiseTestError("test_long_and_overflow",
622 "overflow was not cleared");
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000623
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200624 Py_RETURN_NONE;
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000625}
626
Mark Dickinson93f562c2010-01-30 10:30:15 +0000627/* Test the PyLong_AsLongLongAndOverflow API. General conversion to
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700628 long long is tested by test_long_api_inner. This test will
Mark Dickinson93f562c2010-01-30 10:30:15 +0000629 concentrate on proper handling of overflow.
630*/
631
632static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530633test_long_long_and_overflow(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Dickinson93f562c2010-01-30 10:30:15 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyObject *num, *one, *temp;
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700636 long long value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 int overflow;
Mark Dickinson93f562c2010-01-30 10:30:15 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* Test that overflow is set properly for a large value. */
640 /* num is a number larger than PY_LLONG_MAX on a typical machine. */
641 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
642 if (num == NULL)
643 return NULL;
644 overflow = 1234;
645 value = PyLong_AsLongLongAndOverflow(num, &overflow);
646 Py_DECREF(num);
647 if (value == -1 && PyErr_Occurred())
648 return NULL;
649 if (value != -1)
650 return raiseTestError("test_long_long_and_overflow",
651 "return value was not set to -1");
652 if (overflow != 1)
653 return raiseTestError("test_long_long_and_overflow",
654 "overflow was not set to 1");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* Same again, with num = PY_LLONG_MAX + 1 */
657 num = PyLong_FromLongLong(PY_LLONG_MAX);
658 if (num == NULL)
659 return NULL;
660 one = PyLong_FromLong(1L);
661 if (one == NULL) {
662 Py_DECREF(num);
663 return NULL;
664 }
665 temp = PyNumber_Add(num, one);
666 Py_DECREF(one);
667 Py_DECREF(num);
668 num = temp;
669 if (num == NULL)
670 return NULL;
671 overflow = 0;
672 value = PyLong_AsLongLongAndOverflow(num, &overflow);
673 Py_DECREF(num);
674 if (value == -1 && PyErr_Occurred())
675 return NULL;
676 if (value != -1)
677 return raiseTestError("test_long_long_and_overflow",
678 "return value was not set to -1");
679 if (overflow != 1)
680 return raiseTestError("test_long_long_and_overflow",
681 "overflow was not set to 1");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Test that overflow is set properly for a large negative value. */
684 /* num is a number smaller than PY_LLONG_MIN on a typical platform */
685 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
686 if (num == NULL)
687 return NULL;
688 overflow = 1234;
689 value = PyLong_AsLongLongAndOverflow(num, &overflow);
690 Py_DECREF(num);
691 if (value == -1 && PyErr_Occurred())
692 return NULL;
693 if (value != -1)
694 return raiseTestError("test_long_long_and_overflow",
695 "return value was not set to -1");
696 if (overflow != -1)
697 return raiseTestError("test_long_long_and_overflow",
698 "overflow was not set to -1");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Same again, with num = PY_LLONG_MIN - 1 */
701 num = PyLong_FromLongLong(PY_LLONG_MIN);
702 if (num == NULL)
703 return NULL;
704 one = PyLong_FromLong(1L);
705 if (one == NULL) {
706 Py_DECREF(num);
707 return NULL;
708 }
709 temp = PyNumber_Subtract(num, one);
710 Py_DECREF(one);
711 Py_DECREF(num);
712 num = temp;
713 if (num == NULL)
714 return NULL;
715 overflow = 0;
716 value = PyLong_AsLongLongAndOverflow(num, &overflow);
717 Py_DECREF(num);
718 if (value == -1 && PyErr_Occurred())
719 return NULL;
720 if (value != -1)
721 return raiseTestError("test_long_long_and_overflow",
722 "return value was not set to -1");
723 if (overflow != -1)
724 return raiseTestError("test_long_long_and_overflow",
725 "overflow was not set to -1");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* Test that overflow is cleared properly for small values. */
728 num = PyLong_FromString("FF", NULL, 16);
729 if (num == NULL)
730 return NULL;
731 overflow = 1234;
732 value = PyLong_AsLongLongAndOverflow(num, &overflow);
733 Py_DECREF(num);
734 if (value == -1 && PyErr_Occurred())
735 return NULL;
736 if (value != 0xFF)
737 return raiseTestError("test_long_long_and_overflow",
738 "expected return value 0xFF");
739 if (overflow != 0)
740 return raiseTestError("test_long_long_and_overflow",
741 "overflow was not cleared");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 num = PyLong_FromString("-FF", NULL, 16);
744 if (num == NULL)
745 return NULL;
746 overflow = 0;
747 value = PyLong_AsLongLongAndOverflow(num, &overflow);
748 Py_DECREF(num);
749 if (value == -1 && PyErr_Occurred())
750 return NULL;
751 if (value != -0xFF)
752 return raiseTestError("test_long_long_and_overflow",
753 "expected return value 0xFF");
754 if (overflow != 0)
755 return raiseTestError("test_long_long_and_overflow",
756 "overflow was set incorrectly");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 num = PyLong_FromLongLong(PY_LLONG_MAX);
759 if (num == NULL)
760 return NULL;
761 overflow = 1234;
762 value = PyLong_AsLongLongAndOverflow(num, &overflow);
763 Py_DECREF(num);
764 if (value == -1 && PyErr_Occurred())
765 return NULL;
766 if (value != PY_LLONG_MAX)
767 return raiseTestError("test_long_long_and_overflow",
768 "expected return value PY_LLONG_MAX");
769 if (overflow != 0)
770 return raiseTestError("test_long_long_and_overflow",
771 "overflow was not cleared");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 num = PyLong_FromLongLong(PY_LLONG_MIN);
774 if (num == NULL)
775 return NULL;
776 overflow = 0;
777 value = PyLong_AsLongLongAndOverflow(num, &overflow);
778 Py_DECREF(num);
779 if (value == -1 && PyErr_Occurred())
780 return NULL;
781 if (value != PY_LLONG_MIN)
782 return raiseTestError("test_long_long_and_overflow",
783 "expected return value PY_LLONG_MIN");
784 if (overflow != 0)
785 return raiseTestError("test_long_long_and_overflow",
786 "overflow was not cleared");
Mark Dickinson93f562c2010-01-30 10:30:15 +0000787
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200788 Py_RETURN_NONE;
Mark Dickinson93f562c2010-01-30 10:30:15 +0000789}
790
Nadeem Vawda3d5881e2011-09-07 21:40:26 +0200791/* Test the PyLong_As{Size,Ssize}_t API. At present this just tests that
792 non-integer arguments are handled correctly. It should be extended to
793 test overflow handling.
794 */
795
796static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530797test_long_as_size_t(PyObject *self, PyObject *Py_UNUSED(ignored))
Nadeem Vawda3d5881e2011-09-07 21:40:26 +0200798{
799 size_t out_u;
800 Py_ssize_t out_s;
801
802 Py_INCREF(Py_None);
803
804 out_u = PyLong_AsSize_t(Py_None);
805 if (out_u != (size_t)-1 || !PyErr_Occurred())
806 return raiseTestError("test_long_as_size_t",
807 "PyLong_AsSize_t(None) didn't complain");
808 if (!PyErr_ExceptionMatches(PyExc_TypeError))
809 return raiseTestError("test_long_as_size_t",
810 "PyLong_AsSize_t(None) raised "
811 "something other than TypeError");
812 PyErr_Clear();
813
814 out_s = PyLong_AsSsize_t(Py_None);
815 if (out_s != (Py_ssize_t)-1 || !PyErr_Occurred())
816 return raiseTestError("test_long_as_size_t",
817 "PyLong_AsSsize_t(None) didn't complain");
818 if (!PyErr_ExceptionMatches(PyExc_TypeError))
819 return raiseTestError("test_long_as_size_t",
820 "PyLong_AsSsize_t(None) raised "
821 "something other than TypeError");
822 PyErr_Clear();
823
824 /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
825 return Py_None;
826}
827
Zackery Spytzdc247652019-06-06 14:39:23 -0600828static PyObject *
829test_long_as_unsigned_long_long_mask(PyObject *self,
830 PyObject *Py_UNUSED(ignored))
831{
832 unsigned long long res = PyLong_AsUnsignedLongLongMask(NULL);
833
834 if (res != (unsigned long long)-1 || !PyErr_Occurred()) {
835 return raiseTestError("test_long_as_unsigned_long_long_mask",
836 "PyLong_AsUnsignedLongLongMask(NULL) didn't "
837 "complain");
838 }
839 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
840 return raiseTestError("test_long_as_unsigned_long_long_mask",
841 "PyLong_AsUnsignedLongLongMask(NULL) raised "
842 "something other than SystemError");
843 }
844 PyErr_Clear();
845 Py_RETURN_NONE;
846}
847
Nadeem Vawda3d5881e2011-09-07 21:40:26 +0200848/* Test the PyLong_AsDouble API. At present this just tests that
849 non-integer arguments are handled correctly.
850 */
851
852static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530853test_long_as_double(PyObject *self, PyObject *Py_UNUSED(ignored))
Nadeem Vawda3d5881e2011-09-07 21:40:26 +0200854{
855 double out;
856
857 Py_INCREF(Py_None);
858
859 out = PyLong_AsDouble(Py_None);
860 if (out != -1.0 || !PyErr_Occurred())
861 return raiseTestError("test_long_as_double",
862 "PyLong_AsDouble(None) didn't complain");
863 if (!PyErr_ExceptionMatches(PyExc_TypeError))
864 return raiseTestError("test_long_as_double",
865 "PyLong_AsDouble(None) raised "
866 "something other than TypeError");
867 PyErr_Clear();
868
869 /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
870 return Py_None;
871}
872
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700873/* Test the L code for PyArg_ParseTuple. This should deliver a long long
Tim Petersd38b1c72001-09-30 05:09:37 +0000874 for both long and int arguments. The test may leak a little memory if
875 it fails.
876*/
877static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530878test_L_code(PyObject *self, PyObject *Py_UNUSED(ignored))
Tim Petersd38b1c72001-09-30 05:09:37 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *tuple, *num;
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700881 long long value;
Tim Petersd38b1c72001-09-30 05:09:37 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 tuple = PyTuple_New(1);
884 if (tuple == NULL)
885 return NULL;
Tim Petersd38b1c72001-09-30 05:09:37 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 num = PyLong_FromLong(42);
888 if (num == NULL)
889 return NULL;
Tim Petersd38b1c72001-09-30 05:09:37 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyTuple_SET_ITEM(tuple, 0, num);
Tim Petersd38b1c72001-09-30 05:09:37 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 value = -1;
Oren Milmanba7d7362017-08-29 11:58:27 +0300894 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +0300896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (value != 42)
898 return raiseTestError("test_L_code",
899 "L code returned wrong value for long 42");
Tim Petersd38b1c72001-09-30 05:09:37 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 Py_DECREF(num);
902 num = PyLong_FromLong(42);
903 if (num == NULL)
904 return NULL;
Tim Petersd38b1c72001-09-30 05:09:37 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyTuple_SET_ITEM(tuple, 0, num);
Tim Petersd38b1c72001-09-30 05:09:37 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 value = -1;
Oren Milmanba7d7362017-08-29 11:58:27 +0300909 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +0300911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (value != 42)
913 return raiseTestError("test_L_code",
914 "L code returned wrong value for int 42");
Tim Petersd38b1c72001-09-30 05:09:37 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_DECREF(tuple);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200917 Py_RETURN_NONE;
Tim Petersd38b1c72001-09-30 05:09:37 +0000918}
919
Serhiy Storchakace412872016-05-08 23:36:44 +0300920static PyObject *
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300921return_none(void *unused)
922{
923 Py_RETURN_NONE;
924}
925
926static PyObject *
927raise_error(void *unused)
928{
929 PyErr_SetNone(PyExc_ValueError);
930 return NULL;
931}
932
933static int
934test_buildvalue_N_error(const char *fmt)
935{
936 PyObject *arg, *res;
937
938 arg = PyList_New(0);
939 if (arg == NULL) {
940 return -1;
941 }
942
943 Py_INCREF(arg);
944 res = Py_BuildValue(fmt, return_none, NULL, arg);
945 if (res == NULL) {
946 return -1;
947 }
948 Py_DECREF(res);
949 if (Py_REFCNT(arg) != 1) {
950 PyErr_Format(TestError, "test_buildvalue_N: "
951 "arg was not decrefed in successful "
952 "Py_BuildValue(\"%s\")", fmt);
953 return -1;
954 }
955
956 Py_INCREF(arg);
957 res = Py_BuildValue(fmt, raise_error, NULL, arg);
958 if (res != NULL || !PyErr_Occurred()) {
959 PyErr_Format(TestError, "test_buildvalue_N: "
960 "Py_BuildValue(\"%s\") didn't complain", fmt);
961 return -1;
962 }
963 PyErr_Clear();
964 if (Py_REFCNT(arg) != 1) {
965 PyErr_Format(TestError, "test_buildvalue_N: "
966 "arg was not decrefed in failed "
967 "Py_BuildValue(\"%s\")", fmt);
968 return -1;
969 }
970 Py_DECREF(arg);
971 return 0;
972}
973
974static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +0200975test_buildvalue_N(PyObject *self, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300976{
977 PyObject *arg, *res;
978
979 arg = PyList_New(0);
980 if (arg == NULL) {
981 return NULL;
982 }
983 Py_INCREF(arg);
984 res = Py_BuildValue("N", arg);
985 if (res == NULL) {
986 return NULL;
987 }
988 if (res != arg) {
989 return raiseTestError("test_buildvalue_N",
990 "Py_BuildValue(\"N\") returned wrong result");
991 }
992 if (Py_REFCNT(arg) != 2) {
993 return raiseTestError("test_buildvalue_N",
994 "arg was not decrefed in Py_BuildValue(\"N\")");
995 }
996 Py_DECREF(res);
997 Py_DECREF(arg);
998
999 if (test_buildvalue_N_error("O&N") < 0)
1000 return NULL;
1001 if (test_buildvalue_N_error("(O&N)") < 0)
1002 return NULL;
1003 if (test_buildvalue_N_error("[O&N]") < 0)
1004 return NULL;
1005 if (test_buildvalue_N_error("{O&N}") < 0)
1006 return NULL;
1007 if (test_buildvalue_N_error("{()O&(())N}") < 0)
1008 return NULL;
1009
1010 Py_RETURN_NONE;
1011}
1012
1013
1014static PyObject *
Serhiy Storchakace412872016-05-08 23:36:44 +03001015get_args(PyObject *self, PyObject *args)
1016{
1017 if (args == NULL) {
1018 args = Py_None;
1019 }
1020 Py_INCREF(args);
1021 return args;
1022}
1023
1024static PyObject *
1025get_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
1026{
1027 if (kwargs == NULL) {
1028 kwargs = Py_None;
1029 }
1030 Py_INCREF(kwargs);
1031 return kwargs;
1032}
1033
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001034/* Test tuple argument processing */
1035static PyObject *
1036getargs_tuple(PyObject *self, PyObject *args)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 int a, b, c;
1039 if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
1040 return NULL;
1041 return Py_BuildValue("iii", a, b, c);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042}
1043
Christian Heimes380f7f22008-02-28 11:19:05 +00001044/* test PyArg_ParseTupleAndKeywords */
Larry Hastings83a9f482012-03-20 20:06:16 +00001045static PyObject *
1046getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes380f7f22008-02-28 11:19:05 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001049 static const char fmt[] = "(ii)i|(i(ii))(iii)i";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
Christian Heimes380f7f22008-02-28 11:19:05 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
1053 &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
1054 &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
1055 return NULL;
1056 return Py_BuildValue("iiiiiiiiii",
1057 int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
1058 int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
Christian Heimes380f7f22008-02-28 11:19:05 +00001059}
1060
Larry Hastings83a9f482012-03-20 20:06:16 +00001061/* test PyArg_ParseTupleAndKeywords keyword-only arguments */
1062static PyObject *
1063getargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs)
1064{
1065 static char *keywords[] = {"required", "optional", "keyword_only", NULL};
1066 int required = -1;
1067 int optional = -1;
1068 int keyword_only = -1;
1069
1070 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", keywords,
1071 &required, &optional, &keyword_only))
1072 return NULL;
1073 return Py_BuildValue("iii", required, optional, keyword_only);
1074}
1075
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +03001076/* test PyArg_ParseTupleAndKeywords positional-only arguments */
1077static PyObject *
1078getargs_positional_only_and_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1079{
1080 static char *keywords[] = {"", "", "keyword", NULL};
1081 int required = -1;
1082 int optional = -1;
1083 int keyword = -1;
1084
1085 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii", keywords,
1086 &required, &optional, &keyword))
1087 return NULL;
1088 return Py_BuildValue("iii", required, optional, keyword);
1089}
1090
Thomas Heller3457e4b2003-04-24 16:14:27 +00001091/* Functions to call PyArg_ParseTuple with integer format codes,
1092 and return the result.
1093*/
Thomas Hellera4ea6032003-04-17 18:55:45 +00001094static PyObject *
Thomas Heller3457e4b2003-04-24 16:14:27 +00001095getargs_b(PyObject *self, PyObject *args)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 unsigned char value;
1098 if (!PyArg_ParseTuple(args, "b", &value))
1099 return NULL;
1100 return PyLong_FromUnsignedLong((unsigned long)value);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001101}
1102
Thomas Heller3457e4b2003-04-24 16:14:27 +00001103static PyObject *
1104getargs_B(PyObject *self, PyObject *args)
1105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 unsigned char value;
1107 if (!PyArg_ParseTuple(args, "B", &value))
1108 return NULL;
1109 return PyLong_FromUnsignedLong((unsigned long)value);
Thomas Heller3457e4b2003-04-24 16:14:27 +00001110}
1111
1112static PyObject *
Mark Dickinson1554b182009-12-20 16:03:30 +00001113getargs_h(PyObject *self, PyObject *args)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 short value;
1116 if (!PyArg_ParseTuple(args, "h", &value))
1117 return NULL;
1118 return PyLong_FromLong((long)value);
Mark Dickinson1554b182009-12-20 16:03:30 +00001119}
1120
1121static PyObject *
Thomas Heller3457e4b2003-04-24 16:14:27 +00001122getargs_H(PyObject *self, PyObject *args)
1123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 unsigned short value;
1125 if (!PyArg_ParseTuple(args, "H", &value))
1126 return NULL;
1127 return PyLong_FromUnsignedLong((unsigned long)value);
Thomas Heller3457e4b2003-04-24 16:14:27 +00001128}
1129
1130static PyObject *
1131getargs_I(PyObject *self, PyObject *args)
1132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 unsigned int value;
1134 if (!PyArg_ParseTuple(args, "I", &value))
1135 return NULL;
1136 return PyLong_FromUnsignedLong((unsigned long)value);
Thomas Heller3457e4b2003-04-24 16:14:27 +00001137}
1138
1139static PyObject *
1140getargs_k(PyObject *self, PyObject *args)
1141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 unsigned long value;
1143 if (!PyArg_ParseTuple(args, "k", &value))
1144 return NULL;
1145 return PyLong_FromUnsignedLong(value);
Thomas Heller3457e4b2003-04-24 16:14:27 +00001146}
1147
1148static PyObject *
1149getargs_i(PyObject *self, PyObject *args)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 int value;
1152 if (!PyArg_ParseTuple(args, "i", &value))
1153 return NULL;
1154 return PyLong_FromLong((long)value);
Thomas Heller3457e4b2003-04-24 16:14:27 +00001155}
1156
Thomas Hellera4ea6032003-04-17 18:55:45 +00001157static PyObject *
1158getargs_l(PyObject *self, PyObject *args)
1159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 long value;
1161 if (!PyArg_ParseTuple(args, "l", &value))
1162 return NULL;
1163 return PyLong_FromLong(value);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001164}
1165
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166static PyObject *
1167getargs_n(PyObject *self, PyObject *args)
1168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_ssize_t value;
1170 if (!PyArg_ParseTuple(args, "n", &value))
1171 return NULL;
1172 return PyLong_FromSsize_t(value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173}
1174
Larry Hastingsfaf91e72012-05-05 16:54:29 -07001175static PyObject *
1176getargs_p(PyObject *self, PyObject *args)
1177{
1178 int value;
1179 if (!PyArg_ParseTuple(args, "p", &value))
1180 return NULL;
1181 return PyLong_FromLong(value);
1182}
1183
Thomas Hellera4ea6032003-04-17 18:55:45 +00001184static PyObject *
Thomas Heller3457e4b2003-04-24 16:14:27 +00001185getargs_L(PyObject *self, PyObject *args)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001186{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001187 long long value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!PyArg_ParseTuple(args, "L", &value))
1189 return NULL;
1190 return PyLong_FromLongLong(value);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001191}
1192
Thomas Hellera4ea6032003-04-17 18:55:45 +00001193static PyObject *
Thomas Heller3457e4b2003-04-24 16:14:27 +00001194getargs_K(PyObject *self, PyObject *args)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001195{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001196 unsigned long long value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (!PyArg_ParseTuple(args, "K", &value))
1198 return NULL;
1199 return PyLong_FromUnsignedLongLong(value);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001200}
Thomas Hellera4ea6032003-04-17 18:55:45 +00001201
1202/* This function not only tests the 'k' getargs code, but also the
orenmn698845e2017-03-02 13:29:20 +02001203 PyLong_AsUnsignedLongMask() function. */
Thomas Hellera4ea6032003-04-17 18:55:45 +00001204static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301205test_k_code(PyObject *self, PyObject *Py_UNUSED(ignored))
Thomas Hellera4ea6032003-04-17 18:55:45 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyObject *tuple, *num;
1208 unsigned long value;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 tuple = PyTuple_New(1);
1211 if (tuple == NULL)
1212 return NULL;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* a number larger than ULONG_MAX even on 64-bit platforms */
1215 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
1216 if (num == NULL)
1217 return NULL;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 value = PyLong_AsUnsignedLongMask(num);
1220 if (value != ULONG_MAX)
1221 return raiseTestError("test_k_code",
Georg Brandl4b5b0622016-01-18 08:00:15 +01001222 "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
Thomas Hellera4ea6032003-04-17 18:55:45 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyTuple_SET_ITEM(tuple, 0, num);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 value = 0;
Oren Milmanba7d7362017-08-29 11:58:27 +03001227 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (value != ULONG_MAX)
1231 return raiseTestError("test_k_code",
1232 "k code returned wrong value for long 0xFFF...FFF");
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 Py_DECREF(num);
1235 num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
1236 if (num == NULL)
1237 return NULL;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 value = PyLong_AsUnsignedLongMask(num);
1240 if (value != (unsigned long)-0x42)
1241 return raiseTestError("test_k_code",
orenmn698845e2017-03-02 13:29:20 +02001242 "PyLong_AsUnsignedLongMask() returned wrong "
1243 "value for long -0xFFF..000042");
Thomas Hellera4ea6032003-04-17 18:55:45 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyTuple_SET_ITEM(tuple, 0, num);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 value = 0;
Oren Milmanba7d7362017-08-29 11:58:27 +03001248 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (value != (unsigned long)-0x42)
1252 return raiseTestError("test_k_code",
1253 "k code returned wrong value for long -0xFFF..000042");
Thomas Hellera4ea6032003-04-17 18:55:45 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 Py_DECREF(tuple);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001256 Py_RETURN_NONE;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001257}
1258
Victor Stinner06e49dd2010-06-13 18:21:50 +00001259static PyObject *
Serhiy Storchakaf95455d2016-05-16 10:11:47 +03001260getargs_f(PyObject *self, PyObject *args)
1261{
1262 float f;
1263 if (!PyArg_ParseTuple(args, "f", &f))
1264 return NULL;
1265 return PyFloat_FromDouble(f);
1266}
1267
1268static PyObject *
1269getargs_d(PyObject *self, PyObject *args)
1270{
1271 double d;
1272 if (!PyArg_ParseTuple(args, "d", &d))
1273 return NULL;
1274 return PyFloat_FromDouble(d);
1275}
1276
1277static PyObject *
1278getargs_D(PyObject *self, PyObject *args)
1279{
1280 Py_complex cval;
1281 if (!PyArg_ParseTuple(args, "D", &cval))
1282 return NULL;
1283 return PyComplex_FromCComplex(cval);
1284}
1285
1286static PyObject *
1287getargs_S(PyObject *self, PyObject *args)
1288{
1289 PyObject *obj;
1290 if (!PyArg_ParseTuple(args, "S", &obj))
1291 return NULL;
1292 Py_INCREF(obj);
1293 return obj;
1294}
1295
1296static PyObject *
1297getargs_Y(PyObject *self, PyObject *args)
1298{
1299 PyObject *obj;
1300 if (!PyArg_ParseTuple(args, "Y", &obj))
1301 return NULL;
1302 Py_INCREF(obj);
1303 return obj;
1304}
1305
1306static PyObject *
1307getargs_U(PyObject *self, PyObject *args)
1308{
1309 PyObject *obj;
1310 if (!PyArg_ParseTuple(args, "U", &obj))
1311 return NULL;
1312 Py_INCREF(obj);
1313 return obj;
1314}
1315
1316static PyObject *
Eli Bendersky906b88f2011-07-29 07:05:08 +03001317getargs_c(PyObject *self, PyObject *args)
1318{
1319 char c;
1320 if (!PyArg_ParseTuple(args, "c", &c))
1321 return NULL;
Serhiy Storchakac8241fd2016-01-28 19:49:54 +02001322 return PyLong_FromLong((unsigned char)c);
1323}
1324
1325static PyObject *
1326getargs_C(PyObject *self, PyObject *args)
1327{
1328 int c;
1329 if (!PyArg_ParseTuple(args, "C", &c))
1330 return NULL;
1331 return PyLong_FromLong(c);
Eli Bendersky906b88f2011-07-29 07:05:08 +03001332}
1333
1334static PyObject *
Victor Stinner06e49dd2010-06-13 18:21:50 +00001335getargs_s(PyObject *self, PyObject *args)
1336{
1337 char *str;
1338 if (!PyArg_ParseTuple(args, "s", &str))
1339 return NULL;
1340 return PyBytes_FromString(str);
1341}
1342
1343static PyObject *
1344getargs_s_star(PyObject *self, PyObject *args)
1345{
1346 Py_buffer buffer;
1347 PyObject *bytes;
1348 if (!PyArg_ParseTuple(args, "s*", &buffer))
1349 return NULL;
1350 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1351 PyBuffer_Release(&buffer);
1352 return bytes;
1353}
1354
1355static PyObject *
1356getargs_s_hash(PyObject *self, PyObject *args)
1357{
1358 char *str;
1359 Py_ssize_t size;
1360 if (!PyArg_ParseTuple(args, "s#", &str, &size))
1361 return NULL;
1362 return PyBytes_FromStringAndSize(str, size);
1363}
1364
1365static PyObject *
1366getargs_z(PyObject *self, PyObject *args)
1367{
1368 char *str;
1369 if (!PyArg_ParseTuple(args, "z", &str))
1370 return NULL;
1371 if (str != NULL)
1372 return PyBytes_FromString(str);
1373 else
1374 Py_RETURN_NONE;
1375}
1376
1377static PyObject *
1378getargs_z_star(PyObject *self, PyObject *args)
1379{
1380 Py_buffer buffer;
1381 PyObject *bytes;
1382 if (!PyArg_ParseTuple(args, "z*", &buffer))
1383 return NULL;
1384 if (buffer.buf != NULL)
1385 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1386 else {
1387 Py_INCREF(Py_None);
1388 bytes = Py_None;
1389 }
1390 PyBuffer_Release(&buffer);
1391 return bytes;
1392}
1393
1394static PyObject *
1395getargs_z_hash(PyObject *self, PyObject *args)
1396{
1397 char *str;
1398 Py_ssize_t size;
1399 if (!PyArg_ParseTuple(args, "z#", &str, &size))
1400 return NULL;
1401 if (str != NULL)
1402 return PyBytes_FromStringAndSize(str, size);
1403 else
1404 Py_RETURN_NONE;
1405}
1406
1407static PyObject *
1408getargs_y(PyObject *self, PyObject *args)
1409{
1410 char *str;
1411 if (!PyArg_ParseTuple(args, "y", &str))
1412 return NULL;
1413 return PyBytes_FromString(str);
1414}
1415
1416static PyObject *
1417getargs_y_star(PyObject *self, PyObject *args)
1418{
1419 Py_buffer buffer;
1420 PyObject *bytes;
1421 if (!PyArg_ParseTuple(args, "y*", &buffer))
1422 return NULL;
1423 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1424 PyBuffer_Release(&buffer);
1425 return bytes;
1426}
1427
1428static PyObject *
1429getargs_y_hash(PyObject *self, PyObject *args)
1430{
1431 char *str;
1432 Py_ssize_t size;
1433 if (!PyArg_ParseTuple(args, "y#", &str, &size))
1434 return NULL;
1435 return PyBytes_FromStringAndSize(str, size);
1436}
1437
1438static PyObject *
1439getargs_u(PyObject *self, PyObject *args)
1440{
1441 Py_UNICODE *str;
Victor Stinner06e49dd2010-06-13 18:21:50 +00001442 if (!PyArg_ParseTuple(args, "u", &str))
1443 return NULL;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001444 return PyUnicode_FromWideChar(str, -1);
Victor Stinner06e49dd2010-06-13 18:21:50 +00001445}
1446
1447static PyObject *
1448getargs_u_hash(PyObject *self, PyObject *args)
1449{
1450 Py_UNICODE *str;
1451 Py_ssize_t size;
1452 if (!PyArg_ParseTuple(args, "u#", &str, &size))
1453 return NULL;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001454 return PyUnicode_FromWideChar(str, size);
Victor Stinner06e49dd2010-06-13 18:21:50 +00001455}
1456
1457static PyObject *
1458getargs_Z(PyObject *self, PyObject *args)
1459{
1460 Py_UNICODE *str;
Victor Stinner06e49dd2010-06-13 18:21:50 +00001461 if (!PyArg_ParseTuple(args, "Z", &str))
1462 return NULL;
1463 if (str != NULL) {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001464 return PyUnicode_FromWideChar(str, -1);
Victor Stinner06e49dd2010-06-13 18:21:50 +00001465 } else
1466 Py_RETURN_NONE;
1467}
1468
1469static PyObject *
1470getargs_Z_hash(PyObject *self, PyObject *args)
1471{
1472 Py_UNICODE *str;
1473 Py_ssize_t size;
1474 if (!PyArg_ParseTuple(args, "Z#", &str, &size))
1475 return NULL;
1476 if (str != NULL)
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001477 return PyUnicode_FromWideChar(str, size);
Victor Stinner06e49dd2010-06-13 18:21:50 +00001478 else
1479 Py_RETURN_NONE;
1480}
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001481
Serhiy Storchakac8241fd2016-01-28 19:49:54 +02001482static PyObject *
1483getargs_es(PyObject *self, PyObject *args)
1484{
1485 PyObject *arg, *result;
1486 const char *encoding = NULL;
1487 char *str;
1488
1489 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1490 return NULL;
1491 if (!PyArg_Parse(arg, "es", encoding, &str))
1492 return NULL;
1493 result = PyBytes_FromString(str);
1494 PyMem_Free(str);
1495 return result;
1496}
1497
1498static PyObject *
1499getargs_et(PyObject *self, PyObject *args)
1500{
1501 PyObject *arg, *result;
1502 const char *encoding = NULL;
1503 char *str;
1504
1505 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1506 return NULL;
1507 if (!PyArg_Parse(arg, "et", encoding, &str))
1508 return NULL;
1509 result = PyBytes_FromString(str);
1510 PyMem_Free(str);
1511 return result;
1512}
1513
1514static PyObject *
1515getargs_es_hash(PyObject *self, PyObject *args)
1516{
1517 PyObject *arg, *result;
1518 const char *encoding = NULL;
1519 PyByteArrayObject *buffer = NULL;
1520 char *str = NULL;
1521 Py_ssize_t size;
1522
1523 if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1524 return NULL;
1525 if (buffer != NULL) {
1526 str = PyByteArray_AS_STRING(buffer);
1527 size = PyByteArray_GET_SIZE(buffer);
1528 }
1529 if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
1530 return NULL;
1531 result = PyBytes_FromStringAndSize(str, size);
1532 if (buffer == NULL)
1533 PyMem_Free(str);
1534 return result;
1535}
1536
1537static PyObject *
1538getargs_et_hash(PyObject *self, PyObject *args)
1539{
1540 PyObject *arg, *result;
1541 const char *encoding = NULL;
1542 PyByteArrayObject *buffer = NULL;
1543 char *str = NULL;
1544 Py_ssize_t size;
1545
1546 if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1547 return NULL;
1548 if (buffer != NULL) {
1549 str = PyByteArray_AS_STRING(buffer);
1550 size = PyByteArray_GET_SIZE(buffer);
1551 }
1552 if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
1553 return NULL;
1554 result = PyBytes_FromStringAndSize(str, size);
1555 if (buffer == NULL)
1556 PyMem_Free(str);
1557 return result;
1558}
1559
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001560/* Test the s and z codes for PyArg_ParseTuple.
1561*/
1562static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301563test_s_code(PyObject *self, PyObject *Py_UNUSED(ignored))
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001564{
1565 /* Unicode strings should be accepted */
1566 PyObject *tuple, *obj;
1567 char *value;
1568
1569 tuple = PyTuple_New(1);
1570 if (tuple == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 return NULL;
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001572
1573 obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 "latin-1", NULL);
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001575 if (obj == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 return NULL;
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001577
1578 PyTuple_SET_ITEM(tuple, 0, obj);
1579
1580 /* These two blocks used to raise a TypeError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 * "argument must be string without null bytes, not str"
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001582 */
Oren Milmanba7d7362017-08-29 11:58:27 +03001583 if (!PyArg_ParseTuple(tuple, "s:test_s_code1", &value)) {
1584 return NULL;
1585 }
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001586
Oren Milmanba7d7362017-08-29 11:58:27 +03001587 if (!PyArg_ParseTuple(tuple, "z:test_s_code2", &value)) {
1588 return NULL;
1589 }
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001590
Alexandre Vassalottib645bc72008-05-15 22:06:59 +00001591 Py_DECREF(tuple);
Amaury Forgeot d'Arc07404592008-05-12 13:19:07 +00001592 Py_RETURN_NONE;
1593}
1594
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001595static PyObject *
Larry Hastings8f904da2012-06-22 03:56:29 -07001596parse_tuple_and_keywords(PyObject *self, PyObject *args)
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001597{
Larry Hastings8f904da2012-06-22 03:56:29 -07001598 PyObject *sub_args;
1599 PyObject *sub_kwargs;
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +03001600 const char *sub_format;
Larry Hastings8f904da2012-06-22 03:56:29 -07001601 PyObject *sub_keywords;
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001602
Larry Hastings8f904da2012-06-22 03:56:29 -07001603 Py_ssize_t i, size;
1604 char *keywords[8 + 1]; /* space for NULL at end */
1605 PyObject *o;
1606 PyObject *converted[8];
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001607
Larry Hastings8f904da2012-06-22 03:56:29 -07001608 int result;
1609 PyObject *return_value = NULL;
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001610
Larry Hastings22701e82012-08-08 14:52:22 -07001611 double buffers[8][4]; /* double ensures alignment where necessary */
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001612
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +03001613 if (!PyArg_ParseTuple(args, "OOsO:parse_tuple_and_keywords",
Larry Hastings8f904da2012-06-22 03:56:29 -07001614 &sub_args, &sub_kwargs,
1615 &sub_format, &sub_keywords))
1616 return NULL;
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001617
Larry Hastings8f904da2012-06-22 03:56:29 -07001618 if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) {
1619 PyErr_SetString(PyExc_ValueError,
1620 "parse_tuple_and_keywords: sub_keywords must be either list or tuple");
1621 return NULL;
1622 }
1623
1624 memset(buffers, 0, sizeof(buffers));
1625 memset(converted, 0, sizeof(converted));
1626 memset(keywords, 0, sizeof(keywords));
1627
1628 size = PySequence_Fast_GET_SIZE(sub_keywords);
1629 if (size > 8) {
1630 PyErr_SetString(PyExc_ValueError,
1631 "parse_tuple_and_keywords: too many keywords in sub_keywords");
1632 goto exit;
1633 }
1634
1635 for (i = 0; i < size; i++) {
1636 o = PySequence_Fast_GET_ITEM(sub_keywords, i);
1637 if (!PyUnicode_FSConverter(o, (void *)(converted + i))) {
1638 PyErr_Format(PyExc_ValueError,
Jesus Cea6e1d2b62012-10-04 16:06:30 +02001639 "parse_tuple_and_keywords: could not convert keywords[%zd] to narrow string", i);
Larry Hastings8f904da2012-06-22 03:56:29 -07001640 goto exit;
1641 }
1642 keywords[i] = PyBytes_AS_STRING(converted[i]);
1643 }
1644
1645 result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs,
1646 sub_format, keywords,
1647 buffers + 0, buffers + 1, buffers + 2, buffers + 3,
1648 buffers + 4, buffers + 5, buffers + 6, buffers + 7);
1649
1650 if (result) {
1651 return_value = Py_None;
1652 Py_INCREF(Py_None);
1653 }
1654
1655exit:
1656 size = sizeof(converted) / sizeof(converted[0]);
1657 for (i = 0; i < size; i++) {
1658 Py_XDECREF(converted[i]);
1659 }
1660 return return_value;
Mark Dickinsonf08173b2009-12-03 10:59:46 +00001661}
1662
Benjamin Peterson92035012008-12-27 16:00:54 +00001663static volatile int x;
1664
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001665/* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
1666 of an error.
1667*/
1668static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301669test_u_code(PyObject *self, PyObject *Py_UNUSED(ignored))
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PyObject *tuple, *obj;
1672 Py_UNICODE *value;
1673 Py_ssize_t len;
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
1676 /* Just use the macro and check that it compiles */
1677 x = Py_UNICODE_ISSPACE(25);
Benjamin Peterson206e3072008-10-19 14:07:49 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 tuple = PyTuple_New(1);
1680 if (tuple == NULL)
1681 return NULL;
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 obj = PyUnicode_Decode("test", strlen("test"),
1684 "ascii", NULL);
1685 if (obj == NULL)
1686 return NULL;
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyTuple_SET_ITEM(tuple, 0, obj);
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 value = 0;
Oren Milmanba7d7362017-08-29 11:58:27 +03001691 if (!PyArg_ParseTuple(tuple, "u:test_u_code", &value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (value != PyUnicode_AS_UNICODE(obj))
1695 return raiseTestError("test_u_code",
1696 "u code returned wrong value for u'test'");
1697 value = 0;
Oren Milmanba7d7362017-08-29 11:58:27 +03001698 if (!PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001700 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (value != PyUnicode_AS_UNICODE(obj) ||
1702 len != PyUnicode_GET_SIZE(obj))
1703 return raiseTestError("test_u_code",
1704 "u# code returned wrong values for u'test'");
Tim Petersbaefd9e2003-01-28 20:37:45 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 Py_DECREF(tuple);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001707 Py_RETURN_NONE;
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00001708}
1709
Guido van Rossumfb67be22007-08-29 18:38:11 +00001710/* Test Z and Z# codes for PyArg_ParseTuple */
1711static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301712test_Z_code(PyObject *self, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb67be22007-08-29 18:38:11 +00001713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyObject *tuple, *obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 const Py_UNICODE *value1, *value2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 Py_ssize_t len1, len2;
Guido van Rossumfb67be22007-08-29 18:38:11 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 tuple = PyTuple_New(2);
1719 if (tuple == NULL)
1720 return NULL;
Guido van Rossumfb67be22007-08-29 18:38:11 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 obj = PyUnicode_FromString("test");
1723 PyTuple_SET_ITEM(tuple, 0, obj);
1724 Py_INCREF(Py_None);
1725 PyTuple_SET_ITEM(tuple, 1, Py_None);
Guido van Rossumfb67be22007-08-29 18:38:11 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* swap values on purpose */
1728 value1 = NULL;
1729 value2 = PyUnicode_AS_UNICODE(obj);
Guido van Rossumfb67be22007-08-29 18:38:11 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 /* Test Z for both values */
Oren Milmanba7d7362017-08-29 11:58:27 +03001732 if (!PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (value1 != PyUnicode_AS_UNICODE(obj))
1736 return raiseTestError("test_Z_code",
1737 "Z code returned wrong value for 'test'");
1738 if (value2 != NULL)
1739 return raiseTestError("test_Z_code",
1740 "Z code returned wrong value for None");
Guido van Rossumfb67be22007-08-29 18:38:11 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 value1 = NULL;
1743 value2 = PyUnicode_AS_UNICODE(obj);
1744 len1 = -1;
1745 len2 = -1;
Guido van Rossumfb67be22007-08-29 18:38:11 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 /* Test Z# for both values */
Oren Milmanba7d7362017-08-29 11:58:27 +03001748 if (!PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
1749 &value2, &len2))
1750 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03001752 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (value1 != PyUnicode_AS_UNICODE(obj) ||
1754 len1 != PyUnicode_GET_SIZE(obj))
1755 return raiseTestError("test_Z_code",
1756 "Z# code returned wrong values for 'test'");
1757 if (value2 != NULL ||
1758 len2 != 0)
1759 return raiseTestError("test_Z_code",
1760 "Z# code returned wrong values for None'");
Guido van Rossumfb67be22007-08-29 18:38:11 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 Py_DECREF(tuple);
1763 Py_RETURN_NONE;
Guido van Rossumfb67be22007-08-29 18:38:11 +00001764}
1765
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301767test_widechar(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Dickinson081dfee2009-03-18 14:47:41 +00001768{
1769#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
1771 size_t wtextlen = 1;
Victor Stinnere3b47152011-12-09 20:49:49 +01001772 const wchar_t invalid[1] = {(wchar_t)0x110000u};
Mark Dickinson081dfee2009-03-18 14:47:41 +00001773#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
1775 size_t wtextlen = 2;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001776#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 PyObject *wide, *utf8;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 wide = PyUnicode_FromWideChar(wtext, wtextlen);
1780 if (wide == NULL)
1781 return NULL;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
1784 if (utf8 == NULL) {
1785 Py_DECREF(wide);
1786 return NULL;
1787 }
Mark Dickinson081dfee2009-03-18 14:47:41 +00001788
Victor Stinner8ef18872011-11-21 02:06:57 +01001789 if (PyUnicode_GET_LENGTH(wide) != PyUnicode_GET_LENGTH(utf8)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 Py_DECREF(wide);
1791 Py_DECREF(utf8);
1792 return raiseTestError("test_widechar",
1793 "wide string and utf8 string "
1794 "have different length");
1795 }
1796 if (PyUnicode_Compare(wide, utf8)) {
1797 Py_DECREF(wide);
1798 Py_DECREF(utf8);
1799 if (PyErr_Occurred())
1800 return NULL;
1801 return raiseTestError("test_widechar",
1802 "wide string and utf8 string "
1803 "are different");
1804 }
Mark Dickinson081dfee2009-03-18 14:47:41 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 Py_DECREF(wide);
1807 Py_DECREF(utf8);
Victor Stinnere3b47152011-12-09 20:49:49 +01001808
1809#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
1810 wide = PyUnicode_FromWideChar(invalid, 1);
1811 if (wide == NULL)
1812 PyErr_Clear();
1813 else
1814 return raiseTestError("test_widechar",
1815 "PyUnicode_FromWideChar(L\"\\U00110000\", 1) didn't fail");
1816
1817 wide = PyUnicode_FromUnicode(invalid, 1);
1818 if (wide == NULL)
1819 PyErr_Clear();
1820 else
1821 return raiseTestError("test_widechar",
1822 "PyUnicode_FromUnicode(L\"\\U00110000\", 1) didn't fail");
Victor Stinnere5c05332013-03-06 00:39:03 +01001823
1824 wide = PyUnicode_FromUnicode(NULL, 1);
1825 if (wide == NULL)
1826 return NULL;
1827 PyUnicode_AS_UNICODE(wide)[0] = invalid[0];
Ezio Melotti03e667d2013-03-07 21:18:45 +02001828 if (_PyUnicode_Ready(wide) < 0) {
1829 Py_DECREF(wide);
Victor Stinnere5c05332013-03-06 00:39:03 +01001830 PyErr_Clear();
Ezio Melotti03e667d2013-03-07 21:18:45 +02001831 }
1832 else {
1833 Py_DECREF(wide);
Victor Stinnere5c05332013-03-06 00:39:03 +01001834 return raiseTestError("test_widechar",
1835 "PyUnicode_Ready() didn't fail");
Ezio Melotti03e667d2013-03-07 21:18:45 +02001836 }
Victor Stinnere3b47152011-12-09 20:49:49 +01001837#endif
1838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 Py_RETURN_NONE;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001840}
1841
1842static PyObject *
Victor Stinner46c7b3b2010-10-02 11:49:31 +00001843unicode_aswidechar(PyObject *self, PyObject *args)
Victor Stinner1c24bd02010-10-02 11:03:13 +00001844{
1845 PyObject *unicode, *result;
1846 Py_ssize_t buflen, size;
1847 wchar_t *buffer;
1848
1849 if (!PyArg_ParseTuple(args, "Un", &unicode, &buflen))
1850 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02001851 buffer = PyMem_New(wchar_t, buflen);
Victor Stinner1c24bd02010-10-02 11:03:13 +00001852 if (buffer == NULL)
1853 return PyErr_NoMemory();
1854
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001855 size = PyUnicode_AsWideChar(unicode, buffer, buflen);
Victor Stinner1c24bd02010-10-02 11:03:13 +00001856 if (size == -1) {
1857 PyMem_Free(buffer);
1858 return NULL;
1859 }
1860
1861 if (size < buflen)
1862 buflen = size + 1;
1863 else
1864 buflen = size;
1865 result = PyUnicode_FromWideChar(buffer, buflen);
1866 PyMem_Free(buffer);
1867 if (result == NULL)
1868 return NULL;
1869
1870 return Py_BuildValue("(Nn)", result, size);
1871}
1872
1873static PyObject *
Victor Stinner46c7b3b2010-10-02 11:49:31 +00001874unicode_aswidecharstring(PyObject *self, PyObject *args)
Victor Stinner1c24bd02010-10-02 11:03:13 +00001875{
1876 PyObject *unicode, *result;
1877 Py_ssize_t size;
1878 wchar_t *buffer;
1879
1880 if (!PyArg_ParseTuple(args, "U", &unicode))
1881 return NULL;
1882
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001883 buffer = PyUnicode_AsWideCharString(unicode, &size);
Victor Stinner1c24bd02010-10-02 11:03:13 +00001884 if (buffer == NULL)
1885 return NULL;
1886
1887 result = PyUnicode_FromWideChar(buffer, size + 1);
1888 PyMem_Free(buffer);
1889 if (result == NULL)
1890 return NULL;
1891 return Py_BuildValue("(Nn)", result, size);
1892}
1893
1894static PyObject *
Serhiy Storchakacc164232016-10-02 21:29:26 +03001895unicode_asucs4(PyObject *self, PyObject *args)
1896{
1897 PyObject *unicode, *result;
1898 Py_UCS4 *buffer;
1899 int copy_null;
1900 Py_ssize_t str_len, buf_len;
1901
1902 if (!PyArg_ParseTuple(args, "Unp:unicode_asucs4", &unicode, &str_len, &copy_null)) {
1903 return NULL;
1904 }
1905
1906 buf_len = str_len + 1;
1907 buffer = PyMem_NEW(Py_UCS4, buf_len);
1908 if (buffer == NULL) {
1909 return PyErr_NoMemory();
1910 }
1911 memset(buffer, 0, sizeof(Py_UCS4)*buf_len);
1912 buffer[str_len] = 0xffffU;
1913
1914 if (!PyUnicode_AsUCS4(unicode, buffer, buf_len, copy_null)) {
1915 PyMem_FREE(buffer);
1916 return NULL;
1917 }
1918
1919 result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buffer, buf_len);
1920 PyMem_FREE(buffer);
1921 return result;
1922}
1923
1924static PyObject *
Hai Shi5623ac82019-07-20 02:56:23 -05001925unicode_asutf8(PyObject *self, PyObject *args)
1926{
1927 PyObject *unicode;
1928 const char *buffer;
1929
1930 if (!PyArg_ParseTuple(args, "U", &unicode)) {
1931 return NULL;
1932 }
1933
1934 buffer = PyUnicode_AsUTF8(unicode);
1935 if (buffer == NULL) {
1936 return NULL;
1937 }
1938
1939 return PyBytes_FromString(buffer);
1940}
1941
1942static PyObject *
1943unicode_asutf8andsize(PyObject *self, PyObject *args)
1944{
1945 PyObject *unicode, *result;
1946 const char *buffer;
1947 Py_ssize_t utf8_len;
1948
1949 if(!PyArg_ParseTuple(args, "U", &unicode)) {
1950 return NULL;
1951 }
1952
1953 buffer = PyUnicode_AsUTF8AndSize(unicode, &utf8_len);
1954 if (buffer == NULL) {
1955 return NULL;
1956 }
1957
1958 result = PyBytes_FromString(buffer);
1959 if (result == NULL) {
1960 return NULL;
1961 }
1962
1963 return Py_BuildValue("(Nn)", result, utf8_len);
1964}
1965
1966static PyObject *
Xiang Zhangb2110682016-12-20 22:52:33 +08001967unicode_findchar(PyObject *self, PyObject *args)
1968{
1969 PyObject *str;
1970 int direction;
1971 unsigned int ch;
1972 Py_ssize_t result;
1973 Py_ssize_t start, end;
1974
1975 if (!PyArg_ParseTuple(args, "UInni:unicode_findchar", &str, &ch,
1976 &start, &end, &direction)) {
1977 return NULL;
1978 }
1979
1980 result = PyUnicode_FindChar(str, (Py_UCS4)ch, start, end, direction);
1981 if (result == -2)
1982 return NULL;
1983 else
1984 return PyLong_FromSsize_t(result);
1985}
1986
1987static PyObject *
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001988unicode_copycharacters(PyObject *self, PyObject *args)
1989{
1990 PyObject *from, *to, *to_copy;
1991 Py_ssize_t from_start, to_start, how_many, copied;
1992
1993 if (!PyArg_ParseTuple(args, "UnOnn:unicode_copycharacters", &to, &to_start,
1994 &from, &from_start, &how_many)) {
1995 return NULL;
1996 }
1997
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001998 if (!(to_copy = PyUnicode_New(PyUnicode_GET_LENGTH(to),
1999 PyUnicode_MAX_CHAR_VALUE(to)))) {
2000 return NULL;
2001 }
2002 if (PyUnicode_Fill(to_copy, 0, PyUnicode_GET_LENGTH(to_copy), 0U) < 0) {
2003 Py_DECREF(to_copy);
2004 return NULL;
2005 }
2006
2007 if ((copied = PyUnicode_CopyCharacters(to_copy, to_start, from,
2008 from_start, how_many)) < 0) {
2009 Py_DECREF(to_copy);
2010 return NULL;
2011 }
2012
2013 return Py_BuildValue("(Nn)", to_copy, copied);
2014}
2015
2016static PyObject *
Victor Stinner42bf7752011-11-21 22:52:58 +01002017unicode_encodedecimal(PyObject *self, PyObject *args)
2018{
2019 Py_UNICODE *unicode;
2020 Py_ssize_t length;
2021 char *errors = NULL;
2022 PyObject *decimal;
2023 Py_ssize_t decimal_length, new_length;
2024 int res;
2025
2026 if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors))
2027 return NULL;
2028
2029 decimal_length = length * 7; /* len('&#8364;') */
2030 decimal = PyBytes_FromStringAndSize(NULL, decimal_length);
2031 if (decimal == NULL)
2032 return NULL;
2033
2034 res = PyUnicode_EncodeDecimal(unicode, length,
2035 PyBytes_AS_STRING(decimal),
2036 errors);
2037 if (res < 0) {
2038 Py_DECREF(decimal);
2039 return NULL;
2040 }
2041
2042 new_length = strlen(PyBytes_AS_STRING(decimal));
2043 assert(new_length <= decimal_length);
2044 res = _PyBytes_Resize(&decimal, new_length);
2045 if (res < 0)
2046 return NULL;
2047
2048 return decimal;
2049}
2050
2051static PyObject *
2052unicode_transformdecimaltoascii(PyObject *self, PyObject *args)
2053{
2054 Py_UNICODE *unicode;
2055 Py_ssize_t length;
2056 if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length))
2057 return NULL;
2058 return PyUnicode_TransformDecimalToASCII(unicode, length);
2059}
2060
2061static PyObject *
Stefan Krahe6996ed2012-11-02 14:44:20 +01002062unicode_legacy_string(PyObject *self, PyObject *args)
2063{
2064 Py_UNICODE *data;
2065 Py_ssize_t len;
2066 PyObject *u;
2067
2068 if (!PyArg_ParseTuple(args, "u#", &data, &len))
2069 return NULL;
2070
2071 u = PyUnicode_FromUnicode(NULL, len);
2072 if (u == NULL)
2073 return NULL;
2074
2075 memcpy(PyUnicode_AS_UNICODE(u), data, len * sizeof(Py_UNICODE));
2076
2077 if (len > 0) { /* The empty string is always ready. */
2078 assert(!PyUnicode_IS_READY(u));
2079 }
2080
2081 return u;
2082}
2083
2084static PyObject *
Victor Stinner25e8ec42010-06-25 00:02:38 +00002085getargs_w_star(PyObject *self, PyObject *args)
2086{
2087 Py_buffer buffer;
2088 PyObject *result;
2089 char *str;
2090
2091 if (!PyArg_ParseTuple(args, "w*:getargs_w_star", &buffer))
2092 return NULL;
2093
2094 if (2 <= buffer.len) {
2095 str = buffer.buf;
2096 str[0] = '[';
2097 str[buffer.len-1] = ']';
2098 }
2099
2100 result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
2101 PyBuffer_Release(&buffer);
2102 return result;
2103}
2104
2105
2106static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302107test_empty_argparse(PyObject *self, PyObject *Py_UNUSED(ignored))
Benjamin Peterson92035012008-12-27 16:00:54 +00002108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Test that formats can begin with '|'. See issue #4720. */
2110 PyObject *tuple, *dict = NULL;
2111 static char *kwlist[] = {NULL};
2112 int result;
2113 tuple = PyTuple_New(0);
2114 if (!tuple)
2115 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03002116 if (!(result = PyArg_ParseTuple(tuple, "|:test_empty_argparse"))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 goto done;
Oren Milmanba7d7362017-08-29 11:58:27 +03002118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 dict = PyDict_New();
2120 if (!dict)
2121 goto done;
2122 result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
Benjamin Peterson92035012008-12-27 16:00:54 +00002123 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_DECREF(tuple);
2125 Py_XDECREF(dict);
Oren Milmanba7d7362017-08-29 11:58:27 +03002126 if (!result) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 return NULL;
Oren Milmanba7d7362017-08-29 11:58:27 +03002128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 else {
2130 Py_RETURN_NONE;
2131 }
Benjamin Peterson92035012008-12-27 16:00:54 +00002132}
2133
2134static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00002135codec_incrementalencoder(PyObject *self, PyObject *args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 const char *encoding, *errors = NULL;
2138 if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
2139 &encoding, &errors))
2140 return NULL;
2141 return PyCodec_IncrementalEncoder(encoding, errors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002142}
2143
Thomas Wouters477c8d52006-05-27 19:21:47 +00002144static PyObject *
2145codec_incrementaldecoder(PyObject *self, PyObject *args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 const char *encoding, *errors = NULL;
2148 if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
2149 &encoding, &errors))
2150 return NULL;
2151 return PyCodec_IncrementalDecoder(encoding, errors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002152}
2153
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +00002154
Tim Peters5b8132f2003-01-31 15:52:05 +00002155/* Simple test of _PyLong_NumBits and _PyLong_Sign. */
Tim Petersbaefd9e2003-01-28 20:37:45 +00002156static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302157test_long_numbits(PyObject *self, PyObject *Py_UNUSED(ignored))
Tim Petersbaefd9e2003-01-28 20:37:45 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 struct triple {
2160 long input;
2161 size_t nbits;
2162 int sign;
2163 } testcases[] = {{0, 0, 0},
2164 {1L, 1, 1},
2165 {-1L, 1, -1},
2166 {2L, 2, 1},
2167 {-2L, 2, -1},
2168 {3L, 2, 1},
2169 {-3L, 2, -1},
2170 {4L, 3, 1},
2171 {-4L, 3, -1},
Serhiy Storchaka95949422013-08-27 19:40:23 +03002172 {0x7fffL, 15, 1}, /* one Python int digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 {-0x7fffL, 15, -1},
2174 {0xffffL, 16, 1},
2175 {-0xffffL, 16, -1},
2176 {0xfffffffL, 28, 1},
2177 {-0xfffffffL, 28, -1}};
Victor Stinner706768c2014-08-16 01:03:39 +02002178 size_t i;
Tim Petersbaefd9e2003-01-28 20:37:45 +00002179
Victor Stinner63941882011-09-29 00:42:28 +02002180 for (i = 0; i < Py_ARRAY_LENGTH(testcases); ++i) {
Christian Heimes3205e742013-07-26 15:06:48 +02002181 size_t nbits;
2182 int sign;
2183 PyObject *plong;
2184
2185 plong = PyLong_FromLong(testcases[i].input);
Christian Heimesff369a52013-07-26 14:52:18 +02002186 if (plong == NULL)
2187 return NULL;
Christian Heimes3205e742013-07-26 15:06:48 +02002188 nbits = _PyLong_NumBits(plong);
2189 sign = _PyLong_Sign(plong);
Tim Petersbaefd9e2003-01-28 20:37:45 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_DECREF(plong);
2192 if (nbits != testcases[i].nbits)
2193 return raiseTestError("test_long_numbits",
2194 "wrong result for _PyLong_NumBits");
2195 if (sign != testcases[i].sign)
2196 return raiseTestError("test_long_numbits",
2197 "wrong result for _PyLong_Sign");
2198 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002199 Py_RETURN_NONE;
Tim Petersbaefd9e2003-01-28 20:37:45 +00002200}
2201
Thomas Heller519a0422007-11-15 20:48:54 +00002202/* Example passing NULLs to PyObject_Str(NULL). */
Thomas Woutersa9773292006-04-21 09:43:23 +00002203
2204static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302205test_null_strings(PyObject *self, PyObject *Py_UNUSED(ignored))
Thomas Woutersa9773292006-04-21 09:43:23 +00002206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL);
2208 PyObject *tuple = PyTuple_Pack(2, o1, o2);
2209 Py_XDECREF(o1);
2210 Py_XDECREF(o2);
2211 return tuple;
Thomas Woutersa9773292006-04-21 09:43:23 +00002212}
2213
Jeremy Hyltonede049b2001-09-26 20:01:13 +00002214static PyObject *
2215raise_exception(PyObject *self, PyObject *args)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject *exc;
2218 PyObject *exc_args, *v;
2219 int num_args, i;
Jeremy Hyltonede049b2001-09-26 20:01:13 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (!PyArg_ParseTuple(args, "Oi:raise_exception",
2222 &exc, &num_args))
2223 return NULL;
Jeremy Hyltonede049b2001-09-26 20:01:13 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 exc_args = PyTuple_New(num_args);
2226 if (exc_args == NULL)
2227 return NULL;
2228 for (i = 0; i < num_args; ++i) {
2229 v = PyLong_FromLong(i);
2230 if (v == NULL) {
2231 Py_DECREF(exc_args);
2232 return NULL;
2233 }
2234 PyTuple_SET_ITEM(exc_args, i, v);
2235 }
2236 PyErr_SetObject(exc, exc_args);
2237 Py_DECREF(exc_args);
2238 return NULL;
Jeremy Hyltonede049b2001-09-26 20:01:13 +00002239}
Tim Peters91621db2001-06-12 20:10:01 +00002240
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +02002241static PyObject *
Antoine Pitrou6bc217d2015-06-23 14:31:11 +02002242set_errno(PyObject *self, PyObject *args)
2243{
2244 int new_errno;
2245
2246 if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
2247 return NULL;
2248
2249 errno = new_errno;
2250 Py_RETURN_NONE;
2251}
2252
2253static PyObject *
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +02002254test_set_exc_info(PyObject *self, PyObject *args)
2255{
2256 PyObject *orig_exc;
2257 PyObject *new_type, *new_value, *new_tb;
2258 PyObject *type, *value, *tb;
2259 if (!PyArg_ParseTuple(args, "OOO:test_set_exc_info",
2260 &new_type, &new_value, &new_tb))
2261 return NULL;
2262
2263 PyErr_GetExcInfo(&type, &value, &tb);
2264
2265 Py_INCREF(new_type);
2266 Py_INCREF(new_value);
2267 Py_INCREF(new_tb);
2268 PyErr_SetExcInfo(new_type, new_value, new_tb);
2269
2270 orig_exc = PyTuple_Pack(3, type ? type : Py_None, value ? value : Py_None, tb ? tb : Py_None);
2271 Py_XDECREF(type);
2272 Py_XDECREF(value);
2273 Py_XDECREF(tb);
2274 return orig_exc;
2275}
Benjamin Peterson16323982010-02-03 01:13:41 +00002276
2277static int test_run_counter = 0;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002278
Benjamin Peterson91d58bd2009-12-13 21:30:54 +00002279static PyObject *
2280test_datetime_capi(PyObject *self, PyObject *args) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (PyDateTimeAPI) {
2282 if (test_run_counter) {
2283 /* Probably regrtest.py -R */
2284 Py_RETURN_NONE;
2285 }
2286 else {
2287 PyErr_SetString(PyExc_AssertionError,
2288 "PyDateTime_CAPI somehow initialized");
2289 return NULL;
2290 }
2291 }
2292 test_run_counter++;
2293 PyDateTime_IMPORT;
Paul Ganssle04af5b12018-01-24 17:29:30 -05002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (PyDateTimeAPI)
2296 Py_RETURN_NONE;
2297 else
2298 return NULL;
Benjamin Peterson91d58bd2009-12-13 21:30:54 +00002299}
2300
Paul Ganssle04af5b12018-01-24 17:29:30 -05002301/* Functions exposing the C API type checking for testing */
2302#define MAKE_DATETIME_CHECK_FUNC(check_method, exact_method) \
2303 PyObject *obj; \
2304 int exact = 0; \
2305 if (!PyArg_ParseTuple(args, "O|p", &obj, &exact)) { \
2306 return NULL; \
2307 } \
2308 int rv = exact?exact_method(obj):check_method(obj); \
2309 if (rv) { \
2310 Py_RETURN_TRUE; \
2311 } else { \
2312 Py_RETURN_FALSE; \
2313 }
2314
2315static PyObject *
2316datetime_check_date(PyObject *self, PyObject *args) {
2317 MAKE_DATETIME_CHECK_FUNC(PyDate_Check, PyDate_CheckExact)
2318}
2319
2320static PyObject *
2321datetime_check_time(PyObject *self, PyObject *args) {
2322 MAKE_DATETIME_CHECK_FUNC(PyTime_Check, PyTime_CheckExact)
2323}
2324
2325static PyObject *
2326datetime_check_datetime(PyObject *self, PyObject *args) {
2327 MAKE_DATETIME_CHECK_FUNC(PyDateTime_Check, PyDateTime_CheckExact)
2328}
2329
2330static PyObject *
2331datetime_check_delta(PyObject *self, PyObject *args) {
2332 MAKE_DATETIME_CHECK_FUNC(PyDelta_Check, PyDelta_CheckExact)
2333}
2334
2335static PyObject *
2336datetime_check_tzinfo(PyObject *self, PyObject *args) {
2337 MAKE_DATETIME_CHECK_FUNC(PyTZInfo_Check, PyTZInfo_CheckExact)
2338}
2339
2340
2341/* Makes three variations on timezone representing UTC-5:
2342 1. timezone with offset and name from PyDateTimeAPI
2343 2. timezone with offset and name from PyTimeZone_FromOffsetAndName
2344 3. timezone with offset (no name) from PyTimeZone_FromOffset
2345*/
2346static PyObject *
2347make_timezones_capi(PyObject *self, PyObject *args) {
2348 PyObject *offset = PyDelta_FromDSU(0, -18000, 0);
2349 PyObject *name = PyUnicode_FromString("EST");
2350
2351 PyObject *est_zone_capi = PyDateTimeAPI->TimeZone_FromTimeZone(offset, name);
2352 PyObject *est_zone_macro = PyTimeZone_FromOffsetAndName(offset, name);
2353 PyObject *est_zone_macro_noname = PyTimeZone_FromOffset(offset);
2354
2355 Py_DecRef(offset);
2356 Py_DecRef(name);
2357
2358 PyObject *rv = PyTuple_New(3);
2359
2360 PyTuple_SET_ITEM(rv, 0, est_zone_capi);
2361 PyTuple_SET_ITEM(rv, 1, est_zone_macro);
2362 PyTuple_SET_ITEM(rv, 2, est_zone_macro_noname);
2363
2364 return rv;
2365}
2366
2367static PyObject *
Paul Gansslea049f572018-02-22 15:15:32 -05002368get_timezones_offset_zero(PyObject *self, PyObject *args) {
2369 PyObject *offset = PyDelta_FromDSU(0, 0, 0);
2370 PyObject *name = PyUnicode_FromString("");
2371
2372 // These two should return the UTC singleton
2373 PyObject *utc_singleton_0 = PyTimeZone_FromOffset(offset);
2374 PyObject *utc_singleton_1 = PyTimeZone_FromOffsetAndName(offset, NULL);
2375
2376 // This one will return +00:00 zone, but not the UTC singleton
2377 PyObject *non_utc_zone = PyTimeZone_FromOffsetAndName(offset, name);
2378
2379 Py_DecRef(offset);
2380 Py_DecRef(name);
2381
2382 PyObject *rv = PyTuple_New(3);
2383 PyTuple_SET_ITEM(rv, 0, utc_singleton_0);
2384 PyTuple_SET_ITEM(rv, 1, utc_singleton_1);
2385 PyTuple_SET_ITEM(rv, 2, non_utc_zone);
2386
2387 return rv;
2388}
2389
2390static PyObject *
Paul Ganssle04af5b12018-01-24 17:29:30 -05002391get_timezone_utc_capi(PyObject* self, PyObject *args) {
2392 int macro = 0;
2393 if (!PyArg_ParseTuple(args, "|p", &macro)) {
2394 return NULL;
2395 }
2396 if (macro) {
Paul Ganssle58dc03c2018-01-25 08:58:07 -05002397 Py_INCREF(PyDateTime_TimeZone_UTC);
Paul Ganssle04af5b12018-01-24 17:29:30 -05002398 return PyDateTime_TimeZone_UTC;
2399 } else {
Paul Ganssle58dc03c2018-01-25 08:58:07 -05002400 Py_INCREF(PyDateTimeAPI->TimeZone_UTC);
Paul Ganssle04af5b12018-01-24 17:29:30 -05002401 return PyDateTimeAPI->TimeZone_UTC;
2402 }
2403}
2404
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04002405static PyObject *
Edison A98ff4d52019-05-17 13:28:42 -07002406get_date_fromdate(PyObject *self, PyObject *args)
2407{
2408 PyObject *rv = NULL;
2409 int macro;
2410 int year, month, day;
2411
2412 if (!PyArg_ParseTuple(args, "piii", &macro, &year, &month, &day)) {
2413 return NULL;
2414 }
2415
2416 if (macro) {
2417 rv = PyDate_FromDate(year, month, day);
2418 }
2419 else {
2420 rv = PyDateTimeAPI->Date_FromDate(
2421 year, month, day,
2422 PyDateTimeAPI->DateType);
2423 }
2424 return rv;
2425}
2426
2427static PyObject *
2428get_datetime_fromdateandtime(PyObject *self, PyObject *args)
2429{
2430 PyObject *rv = NULL;
2431 int macro;
2432 int year, month, day;
2433 int hour, minute, second, microsecond;
2434
2435 if (!PyArg_ParseTuple(args, "piiiiiii",
2436 &macro,
2437 &year, &month, &day,
2438 &hour, &minute, &second, &microsecond)) {
2439 return NULL;
2440 }
2441
2442 if (macro) {
2443 rv = PyDateTime_FromDateAndTime(
2444 year, month, day,
2445 hour, minute, second, microsecond);
2446 }
2447 else {
2448 rv = PyDateTimeAPI->DateTime_FromDateAndTime(
2449 year, month, day,
2450 hour, minute, second, microsecond,
2451 Py_None,
2452 PyDateTimeAPI->DateTimeType);
2453 }
2454 return rv;
2455}
2456
2457static PyObject *
2458get_datetime_fromdateandtimeandfold(PyObject *self, PyObject *args)
2459{
2460 PyObject *rv = NULL;
2461 int macro;
2462 int year, month, day;
2463 int hour, minute, second, microsecond, fold;
2464
2465 if (!PyArg_ParseTuple(args, "piiiiiiii",
2466 &macro,
2467 &year, &month, &day,
2468 &hour, &minute, &second, &microsecond,
2469 &fold)) {
2470 return NULL;
2471 }
2472
2473 if (macro) {
2474 rv = PyDateTime_FromDateAndTimeAndFold(
2475 year, month, day,
2476 hour, minute, second, microsecond,
2477 fold);
2478 }
2479 else {
2480 rv = PyDateTimeAPI->DateTime_FromDateAndTimeAndFold(
2481 year, month, day,
2482 hour, minute, second, microsecond,
2483 Py_None,
2484 fold,
2485 PyDateTimeAPI->DateTimeType);
2486 }
2487 return rv;
2488}
2489
2490static PyObject *
2491get_time_fromtime(PyObject *self, PyObject *args)
2492{
2493 PyObject *rv = NULL;
2494 int macro;
2495 int hour, minute, second, microsecond;
2496
2497 if (!PyArg_ParseTuple(args, "piiii",
2498 &macro,
2499 &hour, &minute, &second, &microsecond)) {
2500 return NULL;
2501 }
2502
2503 if (macro) {
2504 rv = PyTime_FromTime(hour, minute, second, microsecond);
2505 }
2506 else {
2507 rv = PyDateTimeAPI->Time_FromTime(
2508 hour, minute, second, microsecond,
2509 Py_None,
2510 PyDateTimeAPI->TimeType);
2511 }
2512 return rv;
2513}
2514
2515static PyObject *
2516get_time_fromtimeandfold(PyObject *self, PyObject *args)
2517{
2518 PyObject *rv = NULL;
2519 int macro;
2520 int hour, minute, second, microsecond, fold;
2521
2522 if (!PyArg_ParseTuple(args, "piiiii",
2523 &macro,
2524 &hour, &minute, &second, &microsecond,
2525 &fold)) {
2526 return NULL;
2527 }
2528
2529 if (macro) {
2530 rv = PyTime_FromTimeAndFold(hour, minute, second, microsecond, fold);
2531 }
2532 else {
2533 rv = PyDateTimeAPI->Time_FromTimeAndFold(
2534 hour, minute, second, microsecond,
2535 Py_None,
2536 fold,
2537 PyDateTimeAPI->TimeType);
2538 }
2539 return rv;
2540}
2541
2542static PyObject *
2543get_delta_fromdsu(PyObject *self, PyObject *args)
2544{
2545 PyObject *rv = NULL;
2546 int macro;
2547 int days, seconds, microseconds;
2548
2549 if (!PyArg_ParseTuple(args, "piii",
2550 &macro,
2551 &days, &seconds, &microseconds)) {
2552 return NULL;
2553 }
2554
2555 if (macro) {
2556 rv = PyDelta_FromDSU(days, seconds, microseconds);
2557 }
2558 else {
2559 rv = PyDateTimeAPI->Delta_FromDelta(
2560 days, seconds, microseconds, 1,
2561 PyDateTimeAPI->DeltaType);
2562 }
2563
2564 return rv;
2565}
2566
2567static PyObject *
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04002568get_date_fromtimestamp(PyObject* self, PyObject *args)
2569{
2570 PyObject *tsargs = NULL, *ts = NULL, *rv = NULL;
2571 int macro = 0;
2572
2573 if (!PyArg_ParseTuple(args, "O|p", &ts, &macro)) {
2574 return NULL;
2575 }
2576
2577 // Construct the argument tuple
2578 if ((tsargs = PyTuple_Pack(1, ts)) == NULL) {
2579 return NULL;
2580 }
2581
2582 // Pass along to the API function
2583 if (macro) {
2584 rv = PyDate_FromTimestamp(tsargs);
2585 }
2586 else {
2587 rv = PyDateTimeAPI->Date_FromTimestamp(
2588 (PyObject *)PyDateTimeAPI->DateType, tsargs
2589 );
2590 }
2591
2592 Py_DECREF(tsargs);
2593 return rv;
2594}
2595
2596static PyObject *
2597get_datetime_fromtimestamp(PyObject* self, PyObject *args)
2598{
2599 int macro = 0;
2600 int usetz = 0;
2601 PyObject *tsargs = NULL, *ts = NULL, *tzinfo = Py_None, *rv = NULL;
2602 if (!PyArg_ParseTuple(args, "OO|pp", &ts, &tzinfo, &usetz, &macro)) {
2603 return NULL;
2604 }
2605
2606 // Construct the argument tuple
2607 if (usetz) {
2608 tsargs = PyTuple_Pack(2, ts, tzinfo);
2609 }
2610 else {
2611 tsargs = PyTuple_Pack(1, ts);
2612 }
2613
2614 if (tsargs == NULL) {
2615 return NULL;
2616 }
2617
2618 // Pass along to the API function
2619 if (macro) {
2620 rv = PyDateTime_FromTimestamp(tsargs);
2621 }
2622 else {
2623 rv = PyDateTimeAPI->DateTime_FromTimestamp(
2624 (PyObject *)PyDateTimeAPI->DateTimeType, tsargs, NULL
2625 );
2626 }
2627
2628 Py_DECREF(tsargs);
2629 return rv;
2630}
2631
Joannah Nanjekye2c5fb172019-08-29 09:54:46 -03002632static PyObject *
2633test_PyDateTime_GET(PyObject *self, PyObject *obj)
2634{
2635 int year, month, day;
2636
2637 year = PyDateTime_GET_YEAR(obj);
2638 month = PyDateTime_GET_MONTH(obj);
2639 day = PyDateTime_GET_DAY(obj);
2640
2641 return Py_BuildValue("(lll)", year, month, day);
2642}
2643
2644static PyObject *
2645test_PyDateTime_DATE_GET(PyObject *self, PyObject *obj)
2646{
2647 int hour, minute, second, microsecond;
2648
2649 hour = PyDateTime_DATE_GET_HOUR(obj);
2650 minute = PyDateTime_DATE_GET_MINUTE(obj);
2651 second = PyDateTime_DATE_GET_SECOND(obj);
2652 microsecond = PyDateTime_DATE_GET_MICROSECOND(obj);
2653
2654 return Py_BuildValue("(llll)", hour, minute, second, microsecond);
2655}
2656
2657static PyObject *
2658test_PyDateTime_TIME_GET(PyObject *self, PyObject *obj)
2659{
2660 int hour, minute, second, microsecond;
2661
2662 hour = PyDateTime_TIME_GET_HOUR(obj);
2663 minute = PyDateTime_TIME_GET_MINUTE(obj);
2664 second = PyDateTime_TIME_GET_SECOND(obj);
2665 microsecond = PyDateTime_TIME_GET_MICROSECOND(obj);
2666
2667 return Py_BuildValue("(llll)", hour, minute, second, microsecond);
2668}
2669
2670static PyObject *
2671test_PyDateTime_DELTA_GET(PyObject *self, PyObject *obj)
2672{
2673 int days, seconds, microseconds;
2674
2675 days = PyDateTime_DELTA_GET_DAYS(obj);
2676 seconds = PyDateTime_DELTA_GET_SECONDS(obj);
2677 microseconds = PyDateTime_DELTA_GET_MICROSECONDS(obj);
2678
2679 return Py_BuildValue("(lll)", days, seconds, microseconds);
2680}
Benjamin Peterson16323982010-02-03 01:13:41 +00002681
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682/* test_thread_state spawns a thread of its own, and that thread releases
2683 * `thread_done` when it's finished. The driver code has to know when the
2684 * thread finishes, because the thread uses a PyObject (the callable) that
2685 * may go away when the driver finishes. The former lack of this explicit
2686 * synchronization caused rare segfaults, so rare that they were seen only
2687 * on a Mac buildbot (although they were possible on any box).
2688 */
2689static PyThread_type_lock thread_done = NULL;
2690
Benjamin Petersona786b022008-08-25 21:05:21 +00002691static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002692_make_call(void *callable)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 PyObject *rc;
2695 int success;
2696 PyGILState_STATE s = PyGILState_Ensure();
Victor Stinner3466bde2016-09-05 18:16:01 -07002697 rc = _PyObject_CallNoArg((PyObject *)callable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 success = (rc != NULL);
2699 Py_XDECREF(rc);
2700 PyGILState_Release(s);
2701 return success;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002702}
2703
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002704/* Same thing, but releases `thread_done` when it returns. This variant
2705 * should be called only from threads spawned by test_thread_state().
2706 */
2707static void
2708_make_call_from_thread(void *callable)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 _make_call(callable);
2711 PyThread_release_lock(thread_done);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002712}
2713
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002714static PyObject *
2715test_thread_state(PyObject *self, PyObject *args)
2716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 PyObject *fn;
2718 int success = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
2721 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 if (!PyCallable_Check(fn)) {
2724 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
2725 fn->ob_type->tp_name);
2726 return NULL;
2727 }
Benjamin Petersona786b022008-08-25 21:05:21 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 /* Ensure Python is set up for threading */
2730 PyEval_InitThreads();
2731 thread_done = PyThread_allocate_lock();
2732 if (thread_done == NULL)
2733 return PyErr_NoMemory();
2734 PyThread_acquire_lock(thread_done, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 /* Start a new thread with our callback. */
2737 PyThread_start_new_thread(_make_call_from_thread, fn);
2738 /* Make the callback with the thread lock held by this thread */
2739 success &= _make_call(fn);
2740 /* Do it all again, but this time with the thread-lock released */
2741 Py_BEGIN_ALLOW_THREADS
2742 success &= _make_call(fn);
2743 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2744 Py_END_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 /* And once more with and without a thread
2747 XXX - should use a lock and work out exactly what we are trying
2748 to test <wink>
2749 */
2750 Py_BEGIN_ALLOW_THREADS
2751 PyThread_start_new_thread(_make_call_from_thread, fn);
2752 success &= _make_call(fn);
2753 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2754 Py_END_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 /* Release lock we acquired above. This is required on HP-UX. */
2757 PyThread_release_lock(thread_done);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 PyThread_free_lock(thread_done);
2760 if (!success)
2761 return NULL;
2762 Py_RETURN_NONE;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002763}
Benjamin Petersona54c9092009-01-13 02:11:23 +00002764
2765/* test Py_AddPendingCalls using threads */
2766static int _pending_callback(void *arg)
2767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 /* we assume the argument is callable object to which we own a reference */
2769 PyObject *callable = (PyObject *)arg;
Victor Stinnera5ed5f02016-12-06 18:45:50 +01002770 PyObject *r = _PyObject_CallNoArg(callable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 Py_DECREF(callable);
2772 Py_XDECREF(r);
2773 return r != NULL ? 0 : -1;
Benjamin Petersona54c9092009-01-13 02:11:23 +00002774}
2775
2776/* The following requests n callbacks to _pending_callback. It can be
2777 * run from any python thread.
2778 */
Benjamin Petersonb4588c22018-07-03 22:30:56 -07002779static PyObject *
2780pending_threadfunc(PyObject *self, PyObject *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +00002781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 PyObject *callable;
2783 int r;
2784 if (PyArg_ParseTuple(arg, "O", &callable) == 0)
2785 return NULL;
Benjamin Petersona54c9092009-01-13 02:11:23 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 /* create the reference for the callbackwhile we hold the lock */
2788 Py_INCREF(callable);
Benjamin Petersona54c9092009-01-13 02:11:23 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 Py_BEGIN_ALLOW_THREADS
2791 r = Py_AddPendingCall(&_pending_callback, callable);
2792 Py_END_ALLOW_THREADS
Benjamin Petersona54c9092009-01-13 02:11:23 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 if (r<0) {
2795 Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002796 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002798 Py_RETURN_TRUE;
Benjamin Petersona54c9092009-01-13 02:11:23 +00002799}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00002800
Neal Norwitzb0d26332007-08-25 00:49:05 +00002801/* Some tests of PyUnicode_FromFormat(). This needs more tests. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002802static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02002803test_string_from_format(PyObject *self, PyObject *Py_UNUSED(ignored))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 PyObject *result;
2806 char *msg;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002807
Alexander Belopolskye239d232010-12-08 23:31:48 +00002808#define CHECK_1_FORMAT(FORMAT, TYPE) \
2809 result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
2810 if (result == NULL) \
2811 return NULL; \
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002812 if (!_PyUnicode_EqualToASCIIString(result, "1")) { \
Alexander Belopolskye239d232010-12-08 23:31:48 +00002813 msg = FORMAT " failed at 1"; \
2814 goto Fail; \
2815 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 Py_DECREF(result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 CHECK_1_FORMAT("%d", int);
2819 CHECK_1_FORMAT("%ld", long);
2820 /* The z width modifier was added in Python 2.5. */
2821 CHECK_1_FORMAT("%zd", Py_ssize_t);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* The u type code was added in Python 2.5. */
2824 CHECK_1_FORMAT("%u", unsigned int);
2825 CHECK_1_FORMAT("%lu", unsigned long);
2826 CHECK_1_FORMAT("%zu", size_t);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* "%lld" and "%llu" support added in Python 2.7. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002829 CHECK_1_FORMAT("%llu", unsigned long long);
2830 CHECK_1_FORMAT("%lld", long long);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002833
2834 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 Py_XDECREF(result);
2836 return raiseTestError("test_string_from_format", msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002837
2838#undef CHECK_1_FORMAT
2839}
2840
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00002841
2842static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302843test_unicode_compare_with_ascii(PyObject *self, PyObject *Py_UNUSED(ignored)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
2845 int result;
2846 if (py_s == NULL)
2847 return NULL;
2848 result = PyUnicode_CompareWithASCIIString(py_s, "str");
2849 Py_DECREF(py_s);
2850 if (!result) {
2851 PyErr_SetString(TestError, "Python string ending in NULL "
2852 "should not compare equal to c string.");
2853 return NULL;
2854 }
2855 Py_RETURN_NONE;
Victor Stinner3e2b7172010-11-09 09:32:19 +00002856}
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00002857
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002858/* This is here to provide a docstring for test_descr. */
2859static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302860test_with_docstring(PyObject *self, PyObject *Py_UNUSED(ignored))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002863}
2864
Mark Dickinson725bfd82009-05-03 20:33:40 +00002865/* Test PyOS_string_to_double. */
2866static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302867test_string_to_double(PyObject *self, PyObject *Py_UNUSED(ignored)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 double result;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002869 const char *msg;
Mark Dickinson725bfd82009-05-03 20:33:40 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871#define CHECK_STRING(STR, expected) \
2872 result = PyOS_string_to_double(STR, NULL, NULL); \
2873 if (result == -1.0 && PyErr_Occurred()) \
2874 return NULL; \
Benjamin Peterson8f4b2472016-09-07 18:09:22 -07002875 if (result != (double)expected) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 msg = "conversion of " STR " to float failed"; \
2877 goto fail; \
2878 }
Mark Dickinson725bfd82009-05-03 20:33:40 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880#define CHECK_INVALID(STR) \
2881 result = PyOS_string_to_double(STR, NULL, NULL); \
2882 if (result == -1.0 && PyErr_Occurred()) { \
2883 if (PyErr_ExceptionMatches(PyExc_ValueError)) \
2884 PyErr_Clear(); \
2885 else \
2886 return NULL; \
2887 } \
2888 else { \
2889 msg = "conversion of " STR " didn't raise ValueError"; \
2890 goto fail; \
2891 }
Mark Dickinson725bfd82009-05-03 20:33:40 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 CHECK_STRING("0.1", 0.1);
2894 CHECK_STRING("1.234", 1.234);
2895 CHECK_STRING("-1.35", -1.35);
2896 CHECK_STRING(".1e01", 1.0);
2897 CHECK_STRING("2.e-2", 0.02);
Mark Dickinson725bfd82009-05-03 20:33:40 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 CHECK_INVALID(" 0.1");
2900 CHECK_INVALID("\t\n-3");
2901 CHECK_INVALID(".123 ");
2902 CHECK_INVALID("3\n");
2903 CHECK_INVALID("123abc");
Mark Dickinson725bfd82009-05-03 20:33:40 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 Py_RETURN_NONE;
Mark Dickinson725bfd82009-05-03 20:33:40 +00002906 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 return raiseTestError("test_string_to_double", msg);
Mark Dickinson725bfd82009-05-03 20:33:40 +00002908#undef CHECK_STRING
2909#undef CHECK_INVALID
2910}
2911
2912
Benjamin Petersonb173f782009-05-05 22:31:58 +00002913/* Coverage testing of capsule objects. */
2914
2915static const char *capsule_name = "capsule name";
2916static char *capsule_pointer = "capsule pointer";
2917static char *capsule_context = "capsule context";
2918static const char *capsule_error = NULL;
2919static int
2920capsule_destructor_call_count = 0;
2921
2922static void
2923capsule_destructor(PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 capsule_destructor_call_count++;
2925 if (PyCapsule_GetContext(o) != capsule_context) {
2926 capsule_error = "context did not match in destructor!";
2927 } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
2928 capsule_error = "destructor did not match in destructor! (woah!)";
2929 } else if (PyCapsule_GetName(o) != capsule_name) {
2930 capsule_error = "name did not match in destructor!";
2931 } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
2932 capsule_error = "pointer did not match in destructor!";
2933 }
Benjamin Petersonb173f782009-05-05 22:31:58 +00002934}
2935
2936typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 char *name;
2938 char *module;
2939 char *attribute;
Benjamin Petersonb173f782009-05-05 22:31:58 +00002940} known_capsule;
2941
2942static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02002943test_capsule(PyObject *self, PyObject *Py_UNUSED(ignored))
Benjamin Petersonb173f782009-05-05 22:31:58 +00002944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 PyObject *object;
2946 const char *error = NULL;
2947 void *pointer;
2948 void *pointer2;
2949 known_capsule known_capsules[] = {
2950 #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
2951 KNOWN_CAPSULE("_socket", "CAPI"),
2952 KNOWN_CAPSULE("_curses", "_C_API"),
2953 KNOWN_CAPSULE("datetime", "datetime_CAPI"),
2954 { NULL, NULL },
2955 };
2956 known_capsule *known = &known_capsules[0];
Benjamin Petersonb173f782009-05-05 22:31:58 +00002957
2958#define FAIL(x) { error = (x); goto exit; }
2959
2960#define CHECK_DESTRUCTOR \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (capsule_error) { \
2962 FAIL(capsule_error); \
2963 } \
2964 else if (!capsule_destructor_call_count) { \
2965 FAIL("destructor not called!"); \
2966 } \
2967 capsule_destructor_call_count = 0; \
Benjamin Petersonb173f782009-05-05 22:31:58 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
2970 PyCapsule_SetContext(object, capsule_context);
2971 capsule_destructor(object);
2972 CHECK_DESTRUCTOR;
2973 Py_DECREF(object);
2974 CHECK_DESTRUCTOR;
Benjamin Petersonb173f782009-05-05 22:31:58 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 object = PyCapsule_New(known, "ignored", NULL);
2977 PyCapsule_SetPointer(object, capsule_pointer);
2978 PyCapsule_SetName(object, capsule_name);
2979 PyCapsule_SetDestructor(object, capsule_destructor);
2980 PyCapsule_SetContext(object, capsule_context);
2981 capsule_destructor(object);
2982 CHECK_DESTRUCTOR;
2983 /* intentionally access using the wrong name */
2984 pointer2 = PyCapsule_GetPointer(object, "the wrong name");
2985 if (!PyErr_Occurred()) {
2986 FAIL("PyCapsule_GetPointer should have failed but did not!");
2987 }
2988 PyErr_Clear();
2989 if (pointer2) {
2990 if (pointer2 == capsule_pointer) {
2991 FAIL("PyCapsule_GetPointer should not have"
2992 " returned the internal pointer!");
2993 } else {
2994 FAIL("PyCapsule_GetPointer should have "
2995 "returned NULL pointer but did not!");
2996 }
2997 }
2998 PyCapsule_SetDestructor(object, NULL);
2999 Py_DECREF(object);
3000 if (capsule_destructor_call_count) {
3001 FAIL("destructor called when it should not have been!");
3002 }
Benjamin Petersonb173f782009-05-05 22:31:58 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 for (known = &known_capsules[0]; known->module != NULL; known++) {
3005 /* yeah, ordinarily I wouldn't do this either,
3006 but it's fine for this test harness.
3007 */
3008 static char buffer[256];
Benjamin Petersonb173f782009-05-05 22:31:58 +00003009#undef FAIL
3010#define FAIL(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 { \
3012 sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
3013 x, known->module, known->attribute); \
3014 error = buffer; \
3015 goto exit; \
3016 } \
Benjamin Petersonb173f782009-05-05 22:31:58 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 PyObject *module = PyImport_ImportModule(known->module);
3019 if (module) {
3020 pointer = PyCapsule_Import(known->name, 0);
3021 if (!pointer) {
3022 Py_DECREF(module);
3023 FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
3024 }
3025 object = PyObject_GetAttrString(module, known->attribute);
3026 if (!object) {
3027 Py_DECREF(module);
3028 return NULL;
3029 }
3030 pointer2 = PyCapsule_GetPointer(object,
3031 "weebles wobble but they don't fall down");
3032 if (!PyErr_Occurred()) {
3033 Py_DECREF(object);
3034 Py_DECREF(module);
3035 FAIL("PyCapsule_GetPointer should have failed but did not!");
3036 }
3037 PyErr_Clear();
3038 if (pointer2) {
3039 Py_DECREF(module);
3040 Py_DECREF(object);
3041 if (pointer2 == pointer) {
3042 FAIL("PyCapsule_GetPointer should not have"
3043 " returned its internal pointer!");
3044 } else {
3045 FAIL("PyCapsule_GetPointer should have"
3046 " returned NULL pointer but did not!");
3047 }
3048 }
3049 Py_DECREF(object);
3050 Py_DECREF(module);
3051 }
3052 else
3053 PyErr_Clear();
3054 }
Benjamin Petersonb173f782009-05-05 22:31:58 +00003055
3056 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 if (error) {
3058 return raiseTestError("test_capsule", error);
3059 }
3060 Py_RETURN_NONE;
Benjamin Petersonb173f782009-05-05 22:31:58 +00003061#undef FAIL
3062}
3063
Guido van Rossumddefaf32007-01-14 03:31:43 +00003064#ifdef HAVE_GETTIMEOFDAY
3065/* Profiling of integer performance */
Martin v. Löwis1c951552008-06-13 07:48:19 +00003066static void print_delta(int test, struct timeval *s, struct timeval *e)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 e->tv_sec -= s->tv_sec;
3069 e->tv_usec -= s->tv_usec;
3070 if (e->tv_usec < 0) {
3071 e->tv_sec -=1;
3072 e->tv_usec += 1000000;
3073 }
3074 printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003075}
3076
3077static PyObject *
3078profile_int(PyObject *self, PyObject* args)
3079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 int i, k;
3081 struct timeval start, stop;
3082 PyObject *single, **multiple, *op1, *result;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 /* Test 1: Allocate and immediately deallocate
3085 many small integers */
3086 gettimeofday(&start, NULL);
3087 for(k=0; k < 20000; k++)
3088 for(i=0; i < 1000; i++) {
3089 single = PyLong_FromLong(i);
3090 Py_DECREF(single);
3091 }
3092 gettimeofday(&stop, NULL);
3093 print_delta(1, &start, &stop);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 /* Test 2: Allocate and immediately deallocate
3096 many large integers */
3097 gettimeofday(&start, NULL);
3098 for(k=0; k < 20000; k++)
3099 for(i=0; i < 1000; i++) {
3100 single = PyLong_FromLong(i+1000000);
3101 Py_DECREF(single);
3102 }
3103 gettimeofday(&stop, NULL);
3104 print_delta(2, &start, &stop);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 /* Test 3: Allocate a few integers, then release
3107 them all simultaneously. */
3108 multiple = malloc(sizeof(PyObject*) * 1000);
Christian Heimes7e138022013-07-26 15:03:50 +02003109 if (multiple == NULL)
3110 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 gettimeofday(&start, NULL);
3112 for(k=0; k < 20000; k++) {
3113 for(i=0; i < 1000; i++) {
3114 multiple[i] = PyLong_FromLong(i+1000000);
3115 }
3116 for(i=0; i < 1000; i++) {
3117 Py_DECREF(multiple[i]);
3118 }
3119 }
3120 gettimeofday(&stop, NULL);
3121 print_delta(3, &start, &stop);
Christian Heimes7e138022013-07-26 15:03:50 +02003122 free(multiple);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* Test 4: Allocate many integers, then release
3125 them all simultaneously. */
3126 multiple = malloc(sizeof(PyObject*) * 1000000);
Christian Heimes7e138022013-07-26 15:03:50 +02003127 if (multiple == NULL)
3128 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 gettimeofday(&start, NULL);
3130 for(k=0; k < 20; k++) {
3131 for(i=0; i < 1000000; i++) {
3132 multiple[i] = PyLong_FromLong(i+1000000);
3133 }
3134 for(i=0; i < 1000000; i++) {
3135 Py_DECREF(multiple[i]);
3136 }
3137 }
3138 gettimeofday(&stop, NULL);
3139 print_delta(4, &start, &stop);
Christian Heimes7e138022013-07-26 15:03:50 +02003140 free(multiple);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* Test 5: Allocate many integers < 32000 */
3143 multiple = malloc(sizeof(PyObject*) * 1000000);
Christian Heimes7e138022013-07-26 15:03:50 +02003144 if (multiple == NULL)
3145 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 gettimeofday(&start, NULL);
3147 for(k=0; k < 10; k++) {
3148 for(i=0; i < 1000000; i++) {
3149 multiple[i] = PyLong_FromLong(i+1000);
3150 }
3151 for(i=0; i < 1000000; i++) {
3152 Py_DECREF(multiple[i]);
3153 }
3154 }
3155 gettimeofday(&stop, NULL);
3156 print_delta(5, &start, &stop);
Christian Heimes7e138022013-07-26 15:03:50 +02003157 free(multiple);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* Test 6: Perform small int addition */
3160 op1 = PyLong_FromLong(1);
3161 gettimeofday(&start, NULL);
3162 for(i=0; i < 10000000; i++) {
3163 result = PyNumber_Add(op1, op1);
3164 Py_DECREF(result);
3165 }
3166 gettimeofday(&stop, NULL);
3167 Py_DECREF(op1);
3168 print_delta(6, &start, &stop);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 /* Test 7: Perform medium int addition */
3171 op1 = PyLong_FromLong(1000);
Christian Heimes66eda262013-07-26 15:54:07 +02003172 if (op1 == NULL)
3173 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 gettimeofday(&start, NULL);
3175 for(i=0; i < 10000000; i++) {
3176 result = PyNumber_Add(op1, op1);
Christian Heimesff369a52013-07-26 14:52:18 +02003177 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 }
3179 gettimeofday(&stop, NULL);
3180 Py_DECREF(op1);
3181 print_delta(7, &start, &stop);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003182
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02003183 Py_RETURN_NONE;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003184}
3185#endif
3186
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003187/* To test the format of tracebacks as printed out. */
3188static PyObject *
3189traceback_print(PyObject *self, PyObject *args)
3190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 PyObject *file;
3192 PyObject *traceback;
3193 int result;
3194
3195 if (!PyArg_ParseTuple(args, "OO:traceback_print",
3196 &traceback, &file))
3197 return NULL;
3198
3199 result = PyTraceBack_Print(traceback, file);
3200 if (result < 0)
3201 return NULL;
3202 Py_RETURN_NONE;
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003203}
3204
Benjamin Petersone6528212008-07-15 15:32:09 +00003205/* To test the format of exceptions as printed out. */
3206static PyObject *
3207exception_print(PyObject *self, PyObject *args)
3208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 PyObject *value;
3210 PyObject *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (!PyArg_ParseTuple(args, "O:exception_print",
3213 &value))
3214 return NULL;
3215 if (!PyExceptionInstance_Check(value)) {
3216 PyErr_Format(PyExc_TypeError, "an exception instance is required");
3217 return NULL;
3218 }
Benjamin Petersone6528212008-07-15 15:32:09 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 tb = PyException_GetTraceback(value);
3221 PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
3222 Py_XDECREF(tb);
Benjamin Petersone6528212008-07-15 15:32:09 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 Py_RETURN_NONE;
Benjamin Petersone6528212008-07-15 15:32:09 +00003225}
3226
3227
3228
Benjamin Peterson0067bd62008-08-16 16:11:03 +00003229
3230/* reliably raise a MemoryError */
3231static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303232raise_memoryerror(PyObject *self, PyObject *Py_UNUSED(ignored))
Benjamin Peterson0067bd62008-08-16 16:11:03 +00003233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 PyErr_NoMemory();
3235 return NULL;
Benjamin Peterson0067bd62008-08-16 16:11:03 +00003236}
3237
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003238/* Issue 6012 */
3239static PyObject *str1, *str2;
3240static int
3241failing_converter(PyObject *obj, void *arg)
3242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* Clone str1, then let the conversion fail. */
3244 assert(str1);
3245 str2 = str1;
3246 Py_INCREF(str2);
3247 return 0;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003248}
3249static PyObject*
3250argparsing(PyObject *o, PyObject *args)
3251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 PyObject *res;
3253 str1 = str2 = NULL;
3254 if (!PyArg_ParseTuple(args, "O&O&",
3255 PyUnicode_FSConverter, &str1,
3256 failing_converter, &str2)) {
3257 if (!str2)
3258 /* argument converter not called? */
3259 return NULL;
3260 /* Should be 1 */
Victor Stinner0fcab4a2011-01-04 12:59:15 +00003261 res = PyLong_FromSsize_t(Py_REFCNT(str2));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 Py_DECREF(str2);
3263 PyErr_Clear();
3264 return res;
3265 }
3266 Py_RETURN_NONE;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003267}
Benjamin Peterson0067bd62008-08-16 16:11:03 +00003268
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003269/* To test that the result of PyCode_NewEmpty has the right members. */
3270static PyObject *
3271code_newempty(PyObject *self, PyObject *args)
3272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 const char *filename;
3274 const char *funcname;
3275 int firstlineno;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (!PyArg_ParseTuple(args, "ssi:code_newempty",
3278 &filename, &funcname, &firstlineno))
3279 return NULL;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003282}
3283
Georg Brandl1e28a272009-12-28 08:41:01 +00003284/* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
3285 Run via Lib/test/test_exceptions.py */
3286static PyObject *
3287make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
3288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 const char *name;
3290 const char *doc = NULL;
3291 PyObject *base = NULL;
3292 PyObject *dict = NULL;
Georg Brandl1e28a272009-12-28 08:41:01 +00003293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
Georg Brandl1e28a272009-12-28 08:41:01 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3297 "s|sOO:make_exception_with_doc", kwlist,
3298 &name, &doc, &base, &dict))
3299 return NULL;
Georg Brandl1e28a272009-12-28 08:41:01 +00003300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 return PyErr_NewExceptionWithDoc(name, doc, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +00003302}
3303
Antoine Pitrou5bffa792011-02-24 20:50:49 +00003304static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303305make_memoryview_from_NULL_pointer(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrou5bffa792011-02-24 20:50:49 +00003306{
3307 Py_buffer info;
3308 if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
3309 return NULL;
3310 return PyMemoryView_FromBuffer(&info);
3311}
Serhiy Storchaka009b8112015-03-18 21:53:15 +02003312
Stefan Krah7213fcc2015-02-01 16:19:23 +01003313static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02003314test_from_contiguous(PyObject* self, PyObject *Py_UNUSED(ignored))
Stefan Krah7213fcc2015-02-01 16:19:23 +01003315{
3316 int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
3317 int init[5] = {0, 1, 2, 3, 4};
3318 Py_ssize_t itemsize = sizeof(int);
3319 Py_ssize_t shape = 5;
3320 Py_ssize_t strides = 2 * itemsize;
3321 Py_buffer view = {
3322 data,
3323 NULL,
3324 5 * itemsize,
3325 itemsize,
3326 1,
3327 1,
3328 NULL,
3329 &shape,
3330 &strides,
3331 NULL,
3332 NULL
3333 };
3334 int *ptr;
3335 int i;
3336
3337 PyBuffer_FromContiguous(&view, init, view.len, 'C');
3338 ptr = view.buf;
3339 for (i = 0; i < 5; i++) {
3340 if (ptr[2*i] != i) {
3341 PyErr_SetString(TestError,
3342 "test_from_contiguous: incorrect result");
3343 return NULL;
3344 }
3345 }
3346
3347 view.buf = &data[8];
3348 view.strides[0] = -2 * itemsize;
3349
3350 PyBuffer_FromContiguous(&view, init, view.len, 'C');
3351 ptr = view.buf;
3352 for (i = 0; i < 5; i++) {
3353 if (*(ptr-2*i) != i) {
3354 PyErr_SetString(TestError,
3355 "test_from_contiguous: incorrect result");
3356 return NULL;
3357 }
3358 }
3359
3360 Py_RETURN_NONE;
3361}
Stefan Krah650c1e82015-02-03 21:43:23 +01003362
Stefan Kraha7559c02015-02-03 22:27:21 +01003363#if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
Stefan Krah650c1e82015-02-03 21:43:23 +01003364extern PyTypeObject _PyBytesIOBuffer_Type;
3365
Stefan Krah5178d912015-02-03 16:57:21 +01003366static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02003367test_pep3118_obsolete_write_locks(PyObject* self, PyObject *Py_UNUSED(ignored))
Stefan Krah5178d912015-02-03 16:57:21 +01003368{
Stefan Krah650c1e82015-02-03 21:43:23 +01003369 PyTypeObject *type = &_PyBytesIOBuffer_Type;
Stefan Krah5178d912015-02-03 16:57:21 +01003370 PyObject *b;
3371 char *dummy[1];
3372 int ret, match;
3373
Stefan Krah650c1e82015-02-03 21:43:23 +01003374 /* PyBuffer_FillInfo() */
Stefan Krah5178d912015-02-03 16:57:21 +01003375 ret = PyBuffer_FillInfo(NULL, NULL, dummy, 1, 0, PyBUF_SIMPLE);
3376 match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
3377 PyErr_Clear();
3378 if (ret != -1 || match == 0)
3379 goto error;
3380
Stefan Krah650c1e82015-02-03 21:43:23 +01003381 /* bytesiobuf_getbuffer() */
3382 b = type->tp_alloc(type, 0);
Stefan Krah5178d912015-02-03 16:57:21 +01003383 if (b == NULL) {
3384 return NULL;
3385 }
3386
3387 ret = PyObject_GetBuffer(b, NULL, PyBUF_SIMPLE);
3388 Py_DECREF(b);
3389 match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
3390 PyErr_Clear();
3391 if (ret != -1 || match == 0)
3392 goto error;
3393
3394 Py_RETURN_NONE;
3395
3396error:
3397 PyErr_SetString(TestError,
3398 "test_pep3118_obsolete_write_locks: failure");
3399 return NULL;
3400}
Stefan Kraha7559c02015-02-03 22:27:21 +01003401#endif
Antoine Pitrou5bffa792011-02-24 20:50:49 +00003402
Stefan Krah650c1e82015-02-03 21:43:23 +01003403/* This tests functions that historically supported write locks. It is
3404 wrong to call getbuffer() with view==NULL and a compliant getbufferproc
3405 is entitled to segfault in that case. */
3406static PyObject *
3407getbuffer_with_null_view(PyObject* self, PyObject *obj)
3408{
3409 if (PyObject_GetBuffer(obj, NULL, PyBUF_SIMPLE) < 0)
3410 return NULL;
3411
3412 Py_RETURN_NONE;
3413}
3414
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -03003415/* PyBuffer_SizeFromFormat() */
3416static PyObject *
3417test_PyBuffer_SizeFromFormat(PyObject *self, PyObject *args)
3418{
3419 const char *format;
3420 Py_ssize_t result;
3421
3422 if (!PyArg_ParseTuple(args, "s:test_PyBuffer_SizeFromFormat",
3423 &format)) {
3424 return NULL;
3425 }
3426
3427 result = PyBuffer_SizeFromFormat(format);
3428 if (result == -1) {
3429 return NULL;
3430 }
3431
3432 return PyLong_FromSsize_t(result);
3433}
3434
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00003435/* Test that the fatal error from not having a current thread doesn't
3436 cause an infinite loop. Run via Lib/test/test_capi.py */
3437static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303438crash_no_current_thread(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00003439{
3440 Py_BEGIN_ALLOW_THREADS
Jeffrey Yasskinea7b7482010-05-17 16:59:23 +00003441 /* Using PyThreadState_Get() directly allows the test to pass in
3442 !pydebug mode. However, the test only actually tests anything
3443 in pydebug mode, since that's where the infinite loop was in
3444 the first place. */
3445 PyThreadState_Get();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00003446 Py_END_ALLOW_THREADS
3447 return NULL;
3448}
3449
Antoine Pitrou2f828f22012-01-18 00:21:11 +01003450/* To run some code in a sub-interpreter. */
3451static PyObject *
3452run_in_subinterp(PyObject *self, PyObject *args)
3453{
3454 const char *code;
3455 int r;
3456 PyThreadState *substate, *mainstate;
3457
3458 if (!PyArg_ParseTuple(args, "s:run_in_subinterp",
3459 &code))
3460 return NULL;
3461
3462 mainstate = PyThreadState_Get();
3463
3464 PyThreadState_Swap(NULL);
3465
3466 substate = Py_NewInterpreter();
Brett Cannonb6855682012-02-03 12:08:03 -05003467 if (substate == NULL) {
3468 /* Since no new thread state was created, there is no exception to
3469 propagate; raise a fresh one after swapping in the old thread
3470 state. */
3471 PyThreadState_Swap(mainstate);
3472 PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
3473 return NULL;
3474 }
Antoine Pitrou2f828f22012-01-18 00:21:11 +01003475 r = PyRun_SimpleString(code);
3476 Py_EndInterpreter(substate);
3477
3478 PyThreadState_Swap(mainstate);
3479
3480 return PyLong_FromLong(r);
3481}
3482
Victor Stinner3c1b3792014-02-17 00:02:43 +01003483static int
3484check_time_rounding(int round)
3485{
Victor Stinner74474232015-09-02 01:43:56 +02003486 if (round != _PyTime_ROUND_FLOOR
3487 && round != _PyTime_ROUND_CEILING
Pablo Galindo2c15b292017-10-17 15:14:41 +01003488 && round != _PyTime_ROUND_HALF_EVEN
3489 && round != _PyTime_ROUND_UP) {
Victor Stinner3c1b3792014-02-17 00:02:43 +01003490 PyErr_SetString(PyExc_ValueError, "invalid rounding");
3491 return -1;
3492 }
3493 return 0;
3494}
3495
Victor Stinner5d272cc2012-03-13 13:35:55 +01003496static PyObject *
3497test_pytime_object_to_time_t(PyObject *self, PyObject *args)
3498{
3499 PyObject *obj;
3500 time_t sec;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003501 int round;
3502 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_time_t", &obj, &round))
Victor Stinner5d272cc2012-03-13 13:35:55 +01003503 return NULL;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003504 if (check_time_rounding(round) < 0)
3505 return NULL;
3506 if (_PyTime_ObjectToTime_t(obj, &sec, round) == -1)
Victor Stinner5d272cc2012-03-13 13:35:55 +01003507 return NULL;
3508 return _PyLong_FromTime_t(sec);
3509}
3510
3511static PyObject *
3512test_pytime_object_to_timeval(PyObject *self, PyObject *args)
3513{
3514 PyObject *obj;
3515 time_t sec;
3516 long usec;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003517 int round;
3518 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timeval", &obj, &round))
Victor Stinner5d272cc2012-03-13 13:35:55 +01003519 return NULL;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003520 if (check_time_rounding(round) < 0)
3521 return NULL;
3522 if (_PyTime_ObjectToTimeval(obj, &sec, &usec, round) == -1)
Victor Stinner5d272cc2012-03-13 13:35:55 +01003523 return NULL;
3524 return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), usec);
3525}
3526
Victor Stinner643cd682012-03-02 22:54:03 +01003527static PyObject *
3528test_pytime_object_to_timespec(PyObject *self, PyObject *args)
3529{
3530 PyObject *obj;
3531 time_t sec;
3532 long nsec;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003533 int round;
3534 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timespec", &obj, &round))
Victor Stinner643cd682012-03-02 22:54:03 +01003535 return NULL;
Victor Stinner3c1b3792014-02-17 00:02:43 +01003536 if (check_time_rounding(round) < 0)
3537 return NULL;
3538 if (_PyTime_ObjectToTimespec(obj, &sec, &nsec, round) == -1)
Victor Stinner643cd682012-03-02 22:54:03 +01003539 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01003540 return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), nsec);
Victor Stinner643cd682012-03-02 22:54:03 +01003541}
3542
Antoine Pitrou796564c2013-07-30 19:59:21 +02003543static void
3544slot_tp_del(PyObject *self)
3545{
3546 _Py_IDENTIFIER(__tp_del__);
3547 PyObject *del, *res;
3548 PyObject *error_type, *error_value, *error_traceback;
3549
3550 /* Temporarily resurrect the object. */
3551 assert(self->ob_refcnt == 0);
3552 self->ob_refcnt = 1;
3553
3554 /* Save the current exception, if any. */
3555 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3556
3557 /* Execute __del__ method, if any. */
3558 del = _PyObject_LookupSpecial(self, &PyId___tp_del__);
3559 if (del != NULL) {
INADA Naoki72dccde2017-02-16 09:26:01 +09003560 res = _PyObject_CallNoArg(del);
Antoine Pitrou796564c2013-07-30 19:59:21 +02003561 if (res == NULL)
3562 PyErr_WriteUnraisable(del);
3563 else
3564 Py_DECREF(res);
3565 Py_DECREF(del);
3566 }
3567
3568 /* Restore the saved exception. */
3569 PyErr_Restore(error_type, error_value, error_traceback);
3570
3571 /* Undo the temporary resurrection; can't use DECREF here, it would
3572 * cause a recursive call.
3573 */
3574 assert(self->ob_refcnt > 0);
3575 if (--self->ob_refcnt == 0)
3576 return; /* this is the normal path out */
3577
3578 /* __del__ resurrected it! Make it look like the original Py_DECREF
3579 * never happened.
3580 */
3581 {
3582 Py_ssize_t refcnt = self->ob_refcnt;
3583 _Py_NewReference(self);
3584 self->ob_refcnt = refcnt;
3585 }
INADA Naokid8521422018-05-17 11:07:21 +09003586 assert(!PyType_IS_GC(Py_TYPE(self)) || _PyObject_GC_IS_TRACKED(self));
Antoine Pitrou796564c2013-07-30 19:59:21 +02003587 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
3588 * we need to undo that. */
3589 _Py_DEC_REFTOTAL;
3590 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3591 * chain, so no more to do there.
3592 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3593 * _Py_NewReference bumped tp_allocs: both of those need to be
3594 * undone.
3595 */
3596#ifdef COUNT_ALLOCS
3597 --Py_TYPE(self)->tp_frees;
3598 --Py_TYPE(self)->tp_allocs;
3599#endif
3600}
3601
3602static PyObject *
3603with_tp_del(PyObject *self, PyObject *args)
3604{
3605 PyObject *obj;
3606 PyTypeObject *tp;
3607
3608 if (!PyArg_ParseTuple(args, "O:with_tp_del", &obj))
3609 return NULL;
3610 tp = (PyTypeObject *) obj;
3611 if (!PyType_Check(obj) || !PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) {
3612 PyErr_Format(PyExc_TypeError,
3613 "heap type expected, got %R", obj);
3614 return NULL;
3615 }
3616 tp->tp_del = slot_tp_del;
3617 Py_INCREF(obj);
3618 return obj;
3619}
3620
Antoine Pitroub349e4c2014-08-06 19:31:40 -04003621static PyMethodDef ml;
3622
3623static PyObject *
3624create_cfunction(PyObject *self, PyObject *args)
3625{
3626 return PyCFunction_NewEx(&ml, self, NULL);
3627}
3628
3629static PyMethodDef ml = {
3630 "create_cfunction",
3631 create_cfunction,
3632 METH_NOARGS,
3633 NULL
3634};
3635
Benjamin Petersonda5eb5a2013-05-27 14:46:14 -07003636static PyObject *
3637_test_incref(PyObject *ob)
3638{
3639 Py_INCREF(ob);
3640 return ob;
3641}
3642
3643static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303644test_xincref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
Benjamin Petersonda5eb5a2013-05-27 14:46:14 -07003645{
3646 PyObject *obj = PyLong_FromLong(0);
3647 Py_XINCREF(_test_incref(obj));
3648 Py_DECREF(obj);
3649 Py_DECREF(obj);
3650 Py_DECREF(obj);
3651 Py_RETURN_NONE;
3652}
3653
3654static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303655test_incref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
Benjamin Petersonda5eb5a2013-05-27 14:46:14 -07003656{
3657 PyObject *obj = PyLong_FromLong(0);
3658 Py_INCREF(_test_incref(obj));
3659 Py_DECREF(obj);
3660 Py_DECREF(obj);
3661 Py_DECREF(obj);
3662 Py_RETURN_NONE;
3663}
3664
3665static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303666test_xdecref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
Benjamin Petersonda5eb5a2013-05-27 14:46:14 -07003667{
3668 Py_XDECREF(PyLong_FromLong(0));
3669 Py_RETURN_NONE;
3670}
3671
3672static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303673test_decref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
Benjamin Petersonda5eb5a2013-05-27 14:46:14 -07003674{
3675 Py_DECREF(PyLong_FromLong(0));
3676 Py_RETURN_NONE;
3677}
Antoine Pitrou2f828f22012-01-18 00:21:11 +01003678
Victor Stinner0507bf52013-07-07 02:05:46 +02003679static PyObject *
Eddie Elizondo474eedf2018-11-13 04:09:31 -08003680test_structseq_newtype_doesnt_leak(PyObject *Py_UNUSED(self),
3681 PyObject *Py_UNUSED(args))
3682{
3683 PyStructSequence_Desc descr;
3684 PyStructSequence_Field descr_fields[3];
3685
3686 descr_fields[0] = (PyStructSequence_Field){"foo", "foo value"};
3687 descr_fields[1] = (PyStructSequence_Field){NULL, "some hidden value"};
3688 descr_fields[2] = (PyStructSequence_Field){0, NULL};
3689
3690 descr.name = "_testcapi.test_descr";
3691 descr.doc = "This is used to test for memory leaks in NewType";
3692 descr.fields = descr_fields;
3693 descr.n_in_sequence = 1;
3694
3695 PyTypeObject* structseq_type = PyStructSequence_NewType(&descr);
3696 assert(structseq_type != NULL);
3697 assert(PyType_Check(structseq_type));
3698 assert(PyType_FastSubclass(structseq_type, Py_TPFLAGS_TUPLE_SUBCLASS));
3699 Py_DECREF(structseq_type);
3700
3701 Py_RETURN_NONE;
3702}
3703
3704static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303705test_incref_decref_API(PyObject *ob, PyObject *Py_UNUSED(ignored))
Christian Heimes4efdb412013-07-31 02:36:43 +02003706{
3707 PyObject *obj = PyLong_FromLong(0);
Victor Stinnerfc6a90a2014-10-09 22:15:41 +02003708 Py_IncRef(obj);
Christian Heimes4efdb412013-07-31 02:36:43 +02003709 Py_DecRef(obj);
3710 Py_DecRef(obj);
3711 Py_RETURN_NONE;
3712}
3713
3714static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303715test_pymem_alloc0(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner0507bf52013-07-07 02:05:46 +02003716{
3717 void *ptr;
3718
Victor Stinnerdb067af2014-05-02 22:31:14 +02003719 ptr = PyMem_RawMalloc(0);
3720 if (ptr == NULL) {
3721 PyErr_SetString(PyExc_RuntimeError, "PyMem_RawMalloc(0) returns NULL");
3722 return NULL;
3723 }
3724 PyMem_RawFree(ptr);
3725
3726 ptr = PyMem_RawCalloc(0, 0);
3727 if (ptr == NULL) {
3728 PyErr_SetString(PyExc_RuntimeError, "PyMem_RawCalloc(0, 0) returns NULL");
3729 return NULL;
3730 }
3731 PyMem_RawFree(ptr);
3732
Victor Stinner0507bf52013-07-07 02:05:46 +02003733 ptr = PyMem_Malloc(0);
3734 if (ptr == NULL) {
3735 PyErr_SetString(PyExc_RuntimeError, "PyMem_Malloc(0) returns NULL");
3736 return NULL;
3737 }
3738 PyMem_Free(ptr);
3739
Victor Stinnerdb067af2014-05-02 22:31:14 +02003740 ptr = PyMem_Calloc(0, 0);
3741 if (ptr == NULL) {
3742 PyErr_SetString(PyExc_RuntimeError, "PyMem_Calloc(0, 0) returns NULL");
3743 return NULL;
3744 }
3745 PyMem_Free(ptr);
3746
Victor Stinner0507bf52013-07-07 02:05:46 +02003747 ptr = PyObject_Malloc(0);
3748 if (ptr == NULL) {
3749 PyErr_SetString(PyExc_RuntimeError, "PyObject_Malloc(0) returns NULL");
3750 return NULL;
3751 }
3752 PyObject_Free(ptr);
3753
Victor Stinnerdb067af2014-05-02 22:31:14 +02003754 ptr = PyObject_Calloc(0, 0);
3755 if (ptr == NULL) {
3756 PyErr_SetString(PyExc_RuntimeError, "PyObject_Calloc(0, 0) returns NULL");
3757 return NULL;
3758 }
3759 PyObject_Free(ptr);
3760
Victor Stinner0507bf52013-07-07 02:05:46 +02003761 Py_RETURN_NONE;
3762}
3763
3764typedef struct {
Victor Stinnerd8f0d922014-06-02 21:57:10 +02003765 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +02003766
3767 size_t malloc_size;
Victor Stinnerdb067af2014-05-02 22:31:14 +02003768 size_t calloc_nelem;
3769 size_t calloc_elsize;
Victor Stinner0507bf52013-07-07 02:05:46 +02003770 void *realloc_ptr;
3771 size_t realloc_new_size;
3772 void *free_ptr;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003773 void *ctx;
Victor Stinner0507bf52013-07-07 02:05:46 +02003774} alloc_hook_t;
3775
Victor Stinner9ed83c42017-10-31 12:18:10 -07003776static void* hook_malloc(void* ctx, size_t size)
Victor Stinner0507bf52013-07-07 02:05:46 +02003777{
3778 alloc_hook_t *hook = (alloc_hook_t *)ctx;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003779 hook->ctx = ctx;
Victor Stinner0507bf52013-07-07 02:05:46 +02003780 hook->malloc_size = size;
3781 return hook->alloc.malloc(hook->alloc.ctx, size);
3782}
3783
Victor Stinner9ed83c42017-10-31 12:18:10 -07003784static void* hook_calloc(void* ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02003785{
3786 alloc_hook_t *hook = (alloc_hook_t *)ctx;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003787 hook->ctx = ctx;
Victor Stinnerdb067af2014-05-02 22:31:14 +02003788 hook->calloc_nelem = nelem;
3789 hook->calloc_elsize = elsize;
3790 return hook->alloc.calloc(hook->alloc.ctx, nelem, elsize);
3791}
3792
Victor Stinner9ed83c42017-10-31 12:18:10 -07003793static void* hook_realloc(void* ctx, void* ptr, size_t new_size)
Victor Stinner0507bf52013-07-07 02:05:46 +02003794{
3795 alloc_hook_t *hook = (alloc_hook_t *)ctx;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003796 hook->ctx = ctx;
Victor Stinner0507bf52013-07-07 02:05:46 +02003797 hook->realloc_ptr = ptr;
3798 hook->realloc_new_size = new_size;
3799 return hook->alloc.realloc(hook->alloc.ctx, ptr, new_size);
3800}
3801
Victor Stinner9ed83c42017-10-31 12:18:10 -07003802static void hook_free(void *ctx, void *ptr)
Victor Stinner0507bf52013-07-07 02:05:46 +02003803{
3804 alloc_hook_t *hook = (alloc_hook_t *)ctx;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003805 hook->ctx = ctx;
Victor Stinner0507bf52013-07-07 02:05:46 +02003806 hook->free_ptr = ptr;
3807 hook->alloc.free(hook->alloc.ctx, ptr);
3808}
3809
3810static PyObject *
3811test_setallocators(PyMemAllocatorDomain domain)
3812{
3813 PyObject *res = NULL;
3814 const char *error_msg;
3815 alloc_hook_t hook;
Victor Stinnerd8f0d922014-06-02 21:57:10 +02003816 PyMemAllocatorEx alloc;
Victor Stinnerdb067af2014-05-02 22:31:14 +02003817 size_t size, size2, nelem, elsize;
Victor Stinner0507bf52013-07-07 02:05:46 +02003818 void *ptr, *ptr2;
3819
Victor Stinnerdb067af2014-05-02 22:31:14 +02003820 memset(&hook, 0, sizeof(hook));
Victor Stinner0507bf52013-07-07 02:05:46 +02003821
3822 alloc.ctx = &hook;
3823 alloc.malloc = &hook_malloc;
Victor Stinnerdb067af2014-05-02 22:31:14 +02003824 alloc.calloc = &hook_calloc;
Victor Stinner0507bf52013-07-07 02:05:46 +02003825 alloc.realloc = &hook_realloc;
3826 alloc.free = &hook_free;
3827 PyMem_GetAllocator(domain, &hook.alloc);
3828 PyMem_SetAllocator(domain, &alloc);
3829
Victor Stinner9ed83c42017-10-31 12:18:10 -07003830 /* malloc, realloc, free */
Victor Stinner0507bf52013-07-07 02:05:46 +02003831 size = 42;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003832 hook.ctx = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +02003833 switch(domain)
3834 {
3835 case PYMEM_DOMAIN_RAW: ptr = PyMem_RawMalloc(size); break;
3836 case PYMEM_DOMAIN_MEM: ptr = PyMem_Malloc(size); break;
3837 case PYMEM_DOMAIN_OBJ: ptr = PyObject_Malloc(size); break;
3838 default: ptr = NULL; break;
3839 }
3840
Victor Stinner9ed83c42017-10-31 12:18:10 -07003841#define CHECK_CTX(FUNC) \
3842 if (hook.ctx != &hook) { \
3843 error_msg = FUNC " wrong context"; \
3844 goto fail; \
3845 } \
3846 hook.ctx = NULL; /* reset for next check */
3847
Victor Stinner0507bf52013-07-07 02:05:46 +02003848 if (ptr == NULL) {
3849 error_msg = "malloc failed";
3850 goto fail;
3851 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07003852 CHECK_CTX("malloc");
Victor Stinner0507bf52013-07-07 02:05:46 +02003853 if (hook.malloc_size != size) {
3854 error_msg = "malloc invalid size";
3855 goto fail;
3856 }
3857
3858 size2 = 200;
3859 switch(domain)
3860 {
3861 case PYMEM_DOMAIN_RAW: ptr2 = PyMem_RawRealloc(ptr, size2); break;
3862 case PYMEM_DOMAIN_MEM: ptr2 = PyMem_Realloc(ptr, size2); break;
3863 case PYMEM_DOMAIN_OBJ: ptr2 = PyObject_Realloc(ptr, size2); break;
Christian Heimes865d12a2013-08-02 11:10:51 +02003864 default: ptr2 = NULL; break;
Victor Stinner0507bf52013-07-07 02:05:46 +02003865 }
3866
3867 if (ptr2 == NULL) {
3868 error_msg = "realloc failed";
3869 goto fail;
3870 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07003871 CHECK_CTX("realloc");
Victor Stinner0507bf52013-07-07 02:05:46 +02003872 if (hook.realloc_ptr != ptr
3873 || hook.realloc_new_size != size2) {
3874 error_msg = "realloc invalid parameters";
3875 goto fail;
3876 }
3877
3878 switch(domain)
3879 {
3880 case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr2); break;
3881 case PYMEM_DOMAIN_MEM: PyMem_Free(ptr2); break;
3882 case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr2); break;
3883 }
3884
Victor Stinner9ed83c42017-10-31 12:18:10 -07003885 CHECK_CTX("free");
Victor Stinner0507bf52013-07-07 02:05:46 +02003886 if (hook.free_ptr != ptr2) {
3887 error_msg = "free invalid pointer";
3888 goto fail;
3889 }
3890
Victor Stinner9ed83c42017-10-31 12:18:10 -07003891 /* calloc, free */
Victor Stinnerdb067af2014-05-02 22:31:14 +02003892 nelem = 2;
3893 elsize = 5;
3894 switch(domain)
3895 {
3896 case PYMEM_DOMAIN_RAW: ptr = PyMem_RawCalloc(nelem, elsize); break;
3897 case PYMEM_DOMAIN_MEM: ptr = PyMem_Calloc(nelem, elsize); break;
3898 case PYMEM_DOMAIN_OBJ: ptr = PyObject_Calloc(nelem, elsize); break;
3899 default: ptr = NULL; break;
3900 }
3901
3902 if (ptr == NULL) {
3903 error_msg = "calloc failed";
3904 goto fail;
3905 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07003906 CHECK_CTX("calloc");
Victor Stinnerdb067af2014-05-02 22:31:14 +02003907 if (hook.calloc_nelem != nelem || hook.calloc_elsize != elsize) {
3908 error_msg = "calloc invalid nelem or elsize";
3909 goto fail;
3910 }
3911
Victor Stinner9ed83c42017-10-31 12:18:10 -07003912 hook.free_ptr = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +02003913 switch(domain)
3914 {
3915 case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr); break;
3916 case PYMEM_DOMAIN_MEM: PyMem_Free(ptr); break;
3917 case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr); break;
3918 }
3919
Victor Stinner9ed83c42017-10-31 12:18:10 -07003920 CHECK_CTX("calloc free");
3921 if (hook.free_ptr != ptr) {
3922 error_msg = "calloc free invalid pointer";
3923 goto fail;
3924 }
3925
Victor Stinner0507bf52013-07-07 02:05:46 +02003926 Py_INCREF(Py_None);
3927 res = Py_None;
3928 goto finally;
3929
3930fail:
3931 PyErr_SetString(PyExc_RuntimeError, error_msg);
3932
3933finally:
3934 PyMem_SetAllocator(domain, &hook.alloc);
3935 return res;
Victor Stinner9ed83c42017-10-31 12:18:10 -07003936
3937#undef CHECK_CTX
Victor Stinner0507bf52013-07-07 02:05:46 +02003938}
3939
3940static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303941test_pymem_setrawallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner0507bf52013-07-07 02:05:46 +02003942{
3943 return test_setallocators(PYMEM_DOMAIN_RAW);
3944}
3945
3946static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303947test_pymem_setallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner0507bf52013-07-07 02:05:46 +02003948{
3949 return test_setallocators(PYMEM_DOMAIN_MEM);
3950}
3951
3952static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303953test_pyobject_setallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner0507bf52013-07-07 02:05:46 +02003954{
3955 return test_setallocators(PYMEM_DOMAIN_OBJ);
3956}
3957
xdegaye85f64302017-07-01 14:14:45 +02003958/* Most part of the following code is inherited from the pyfailmalloc project
3959 * written by Victor Stinner. */
3960static struct {
3961 int installed;
3962 PyMemAllocatorEx raw;
3963 PyMemAllocatorEx mem;
3964 PyMemAllocatorEx obj;
3965} FmHook;
3966
3967static struct {
3968 int start;
3969 int stop;
3970 Py_ssize_t count;
3971} FmData;
3972
3973static int
3974fm_nomemory(void)
3975{
3976 FmData.count++;
3977 if (FmData.count > FmData.start &&
3978 (FmData.stop <= 0 || FmData.count <= FmData.stop)) {
3979 return 1;
3980 }
3981 return 0;
3982}
3983
3984static void *
3985hook_fmalloc(void *ctx, size_t size)
3986{
3987 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
3988 if (fm_nomemory()) {
3989 return NULL;
3990 }
3991 return alloc->malloc(alloc->ctx, size);
3992}
3993
3994static void *
3995hook_fcalloc(void *ctx, size_t nelem, size_t elsize)
3996{
3997 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
3998 if (fm_nomemory()) {
3999 return NULL;
4000 }
4001 return alloc->calloc(alloc->ctx, nelem, elsize);
4002}
4003
4004static void *
4005hook_frealloc(void *ctx, void *ptr, size_t new_size)
4006{
4007 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4008 if (fm_nomemory()) {
4009 return NULL;
4010 }
4011 return alloc->realloc(alloc->ctx, ptr, new_size);
4012}
4013
4014static void
4015hook_ffree(void *ctx, void *ptr)
4016{
4017 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4018 alloc->free(alloc->ctx, ptr);
4019}
4020
4021static void
4022fm_setup_hooks(void)
4023{
4024 PyMemAllocatorEx alloc;
4025
4026 if (FmHook.installed) {
4027 return;
4028 }
4029 FmHook.installed = 1;
4030
4031 alloc.malloc = hook_fmalloc;
4032 alloc.calloc = hook_fcalloc;
4033 alloc.realloc = hook_frealloc;
4034 alloc.free = hook_ffree;
4035 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &FmHook.raw);
4036 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &FmHook.mem);
4037 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &FmHook.obj);
4038
4039 alloc.ctx = &FmHook.raw;
4040 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
4041
4042 alloc.ctx = &FmHook.mem;
4043 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
4044
4045 alloc.ctx = &FmHook.obj;
4046 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
4047}
4048
4049static void
4050fm_remove_hooks(void)
4051{
4052 if (FmHook.installed) {
4053 FmHook.installed = 0;
4054 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &FmHook.raw);
4055 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &FmHook.mem);
4056 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &FmHook.obj);
4057 }
4058}
4059
4060static PyObject*
4061set_nomemory(PyObject *self, PyObject *args)
4062{
4063 /* Memory allocation fails after 'start' allocation requests, and until
4064 * 'stop' allocation requests except when 'stop' is negative or equal
4065 * to 0 (default) in which case allocation failures never stop. */
4066 FmData.count = 0;
4067 FmData.stop = 0;
4068 if (!PyArg_ParseTuple(args, "i|i", &FmData.start, &FmData.stop)) {
4069 return NULL;
4070 }
4071 fm_setup_hooks();
4072 Py_RETURN_NONE;
4073}
4074
4075static PyObject*
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304076remove_mem_hooks(PyObject *self, PyObject *Py_UNUSED(ignored))
xdegaye85f64302017-07-01 14:14:45 +02004077{
4078 fm_remove_hooks();
4079 Py_RETURN_NONE;
4080}
4081
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004082PyDoc_STRVAR(docstring_empty,
4083""
4084);
4085
4086PyDoc_STRVAR(docstring_no_signature,
4087"This docstring has no signature."
4088);
4089
4090PyDoc_STRVAR(docstring_with_invalid_signature,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004091"docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004092"\n"
4093"This docstring has an invalid signature."
4094);
4095
Larry Hastings2623c8c2014-02-08 22:15:29 -08004096PyDoc_STRVAR(docstring_with_invalid_signature2,
4097"docstring_with_invalid_signature2($module, /, boo)\n"
4098"\n"
4099"--\n"
4100"\n"
4101"This docstring also has an invalid signature."
4102);
4103
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004104PyDoc_STRVAR(docstring_with_signature,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004105"docstring_with_signature($module, /, sig)\n"
4106"--\n"
4107"\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004108"This docstring has a valid signature."
4109);
4110
Zachary Ware8ef887c2015-04-13 18:22:35 -05004111PyDoc_STRVAR(docstring_with_signature_but_no_doc,
4112"docstring_with_signature_but_no_doc($module, /, sig)\n"
4113"--\n"
4114"\n"
4115);
4116
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004117PyDoc_STRVAR(docstring_with_signature_and_extra_newlines,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004118"docstring_with_signature_and_extra_newlines($module, /, parameter)\n"
4119"--\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -08004120"\n"
4121"\n"
4122"This docstring has a valid signature and some extra newlines."
4123);
4124
Larry Hastings16c51912014-01-07 11:53:01 -08004125PyDoc_STRVAR(docstring_with_signature_with_defaults,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004126"docstring_with_signature_with_defaults(module, s='avocado',\n"
4127" b=b'bytes', d=3.14, i=35, n=None, t=True, f=False,\n"
4128" local=the_number_three, sys=sys.maxsize,\n"
4129" exp=sys.maxsize - 1)\n"
4130"--\n"
Larry Hastings16c51912014-01-07 11:53:01 -08004131"\n"
4132"\n"
4133"\n"
4134"This docstring has a valid signature with parameters,\n"
4135"and the parameters take defaults of varying types."
4136);
4137
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004138typedef struct {
4139 PyThread_type_lock start_event;
4140 PyThread_type_lock exit_event;
4141 PyObject *callback;
4142} test_c_thread_t;
4143
4144static void
4145temporary_c_thread(void *data)
4146{
4147 test_c_thread_t *test_c_thread = data;
4148 PyGILState_STATE state;
4149 PyObject *res;
4150
4151 PyThread_release_lock(test_c_thread->start_event);
4152
4153 /* Allocate a Python thread state for this thread */
4154 state = PyGILState_Ensure();
4155
Victor Stinner3466bde2016-09-05 18:16:01 -07004156 res = _PyObject_CallNoArg(test_c_thread->callback);
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004157 Py_CLEAR(test_c_thread->callback);
4158
4159 if (res == NULL) {
4160 PyErr_Print();
4161 }
4162 else {
4163 Py_DECREF(res);
4164 }
4165
4166 /* Destroy the Python thread state for this thread */
4167 PyGILState_Release(state);
4168
4169 PyThread_release_lock(test_c_thread->exit_event);
4170
4171 PyThread_exit_thread();
4172}
4173
4174static PyObject *
4175call_in_temporary_c_thread(PyObject *self, PyObject *callback)
4176{
4177 PyObject *res = NULL;
4178 test_c_thread_t test_c_thread;
4179 long thread;
4180
4181 PyEval_InitThreads();
4182
4183 test_c_thread.start_event = PyThread_allocate_lock();
4184 test_c_thread.exit_event = PyThread_allocate_lock();
4185 test_c_thread.callback = NULL;
4186 if (!test_c_thread.start_event || !test_c_thread.exit_event) {
4187 PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
4188 goto exit;
4189 }
4190
4191 Py_INCREF(callback);
4192 test_c_thread.callback = callback;
4193
4194 PyThread_acquire_lock(test_c_thread.start_event, 1);
4195 PyThread_acquire_lock(test_c_thread.exit_event, 1);
4196
4197 thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
4198 if (thread == -1) {
4199 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
4200 PyThread_release_lock(test_c_thread.start_event);
4201 PyThread_release_lock(test_c_thread.exit_event);
4202 goto exit;
4203 }
4204
4205 PyThread_acquire_lock(test_c_thread.start_event, 1);
4206 PyThread_release_lock(test_c_thread.start_event);
4207
4208 Py_BEGIN_ALLOW_THREADS
4209 PyThread_acquire_lock(test_c_thread.exit_event, 1);
4210 PyThread_release_lock(test_c_thread.exit_event);
4211 Py_END_ALLOW_THREADS
4212
4213 Py_INCREF(Py_None);
4214 res = Py_None;
4215
4216exit:
4217 Py_CLEAR(test_c_thread.callback);
4218 if (test_c_thread.start_event)
4219 PyThread_free_lock(test_c_thread.start_event);
4220 if (test_c_thread.exit_event)
4221 PyThread_free_lock(test_c_thread.exit_event);
4222 return res;
4223}
Victor Stinner13105102013-12-13 02:17:29 +01004224
Serhiy Storchakab5181342015-02-06 08:58:56 +02004225/* marshal */
4226
4227static PyObject*
4228pymarshal_write_long_to_file(PyObject* self, PyObject *args)
4229{
4230 long value;
4231 char *filename;
4232 int version;
4233 FILE *fp;
4234
4235 if (!PyArg_ParseTuple(args, "lsi:pymarshal_write_long_to_file",
4236 &value, &filename, &version))
4237 return NULL;
4238
4239 fp = fopen(filename, "wb");
4240 if (fp == NULL) {
4241 PyErr_SetFromErrno(PyExc_OSError);
4242 return NULL;
4243 }
4244
4245 PyMarshal_WriteLongToFile(value, fp, version);
4246
4247 fclose(fp);
4248 if (PyErr_Occurred())
4249 return NULL;
4250 Py_RETURN_NONE;
4251}
4252
4253static PyObject*
4254pymarshal_write_object_to_file(PyObject* self, PyObject *args)
4255{
4256 PyObject *obj;
4257 char *filename;
4258 int version;
4259 FILE *fp;
4260
4261 if (!PyArg_ParseTuple(args, "Osi:pymarshal_write_object_to_file",
4262 &obj, &filename, &version))
4263 return NULL;
4264
4265 fp = fopen(filename, "wb");
4266 if (fp == NULL) {
4267 PyErr_SetFromErrno(PyExc_OSError);
4268 return NULL;
4269 }
4270
4271 PyMarshal_WriteObjectToFile(obj, fp, version);
4272
4273 fclose(fp);
4274 if (PyErr_Occurred())
4275 return NULL;
4276 Py_RETURN_NONE;
4277}
4278
4279static PyObject*
4280pymarshal_read_short_from_file(PyObject* self, PyObject *args)
4281{
4282 int value;
4283 long pos;
4284 char *filename;
4285 FILE *fp;
4286
4287 if (!PyArg_ParseTuple(args, "s:pymarshal_read_short_from_file", &filename))
4288 return NULL;
4289
4290 fp = fopen(filename, "rb");
4291 if (fp == NULL) {
4292 PyErr_SetFromErrno(PyExc_OSError);
4293 return NULL;
4294 }
4295
4296 value = PyMarshal_ReadShortFromFile(fp);
4297 pos = ftell(fp);
4298
4299 fclose(fp);
4300 if (PyErr_Occurred())
4301 return NULL;
4302 return Py_BuildValue("il", value, pos);
4303}
4304
4305static PyObject*
4306pymarshal_read_long_from_file(PyObject* self, PyObject *args)
4307{
4308 long value, pos;
4309 char *filename;
4310 FILE *fp;
4311
4312 if (!PyArg_ParseTuple(args, "s:pymarshal_read_long_from_file", &filename))
4313 return NULL;
4314
4315 fp = fopen(filename, "rb");
4316 if (fp == NULL) {
4317 PyErr_SetFromErrno(PyExc_OSError);
4318 return NULL;
4319 }
4320
4321 value = PyMarshal_ReadLongFromFile(fp);
4322 pos = ftell(fp);
4323
4324 fclose(fp);
4325 if (PyErr_Occurred())
4326 return NULL;
4327 return Py_BuildValue("ll", value, pos);
4328}
4329
4330static PyObject*
4331pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
4332{
4333 PyObject *obj;
4334 long pos;
4335 char *filename;
4336 FILE *fp;
4337
4338 if (!PyArg_ParseTuple(args, "s:pymarshal_read_last_object_from_file", &filename))
4339 return NULL;
4340
4341 fp = fopen(filename, "rb");
4342 if (fp == NULL) {
4343 PyErr_SetFromErrno(PyExc_OSError);
4344 return NULL;
4345 }
4346
4347 obj = PyMarshal_ReadLastObjectFromFile(fp);
4348 pos = ftell(fp);
4349
4350 fclose(fp);
4351 return Py_BuildValue("Nl", obj, pos);
4352}
4353
4354static PyObject*
4355pymarshal_read_object_from_file(PyObject* self, PyObject *args)
4356{
4357 PyObject *obj;
4358 long pos;
4359 char *filename;
4360 FILE *fp;
4361
4362 if (!PyArg_ParseTuple(args, "s:pymarshal_read_object_from_file", &filename))
4363 return NULL;
4364
4365 fp = fopen(filename, "rb");
4366 if (fp == NULL) {
4367 PyErr_SetFromErrno(PyExc_OSError);
4368 return NULL;
4369 }
4370
4371 obj = PyMarshal_ReadObjectFromFile(fp);
4372 pos = ftell(fp);
4373
4374 fclose(fp);
4375 return Py_BuildValue("Nl", obj, pos);
4376}
4377
Victor Stinnerefde1462015-03-21 15:04:43 +01004378static PyObject*
4379return_null_without_error(PyObject *self, PyObject *args)
4380{
4381 /* invalid call: return NULL without setting an error,
4382 * _Py_CheckFunctionResult() must detect such bug at runtime. */
4383 PyErr_Clear();
4384 return NULL;
4385}
4386
4387static PyObject*
4388return_result_with_error(PyObject *self, PyObject *args)
4389{
4390 /* invalid call: return a result with an error set,
4391 * _Py_CheckFunctionResult() must detect such bug at runtime. */
4392 PyErr_SetNone(PyExc_ValueError);
4393 Py_RETURN_NONE;
4394}
4395
Victor Stinner992c43f2015-03-27 17:12:45 +01004396static PyObject *
Victor Stinner13019fd2015-04-03 13:10:54 +02004397test_pytime_fromseconds(PyObject *self, PyObject *args)
4398{
4399 int seconds;
4400 _PyTime_t ts;
4401
4402 if (!PyArg_ParseTuple(args, "i", &seconds))
4403 return NULL;
4404 ts = _PyTime_FromSeconds(seconds);
4405 return _PyTime_AsNanosecondsObject(ts);
4406}
4407
4408static PyObject *
Victor Stinner992c43f2015-03-27 17:12:45 +01004409test_pytime_fromsecondsobject(PyObject *self, PyObject *args)
4410{
4411 PyObject *obj;
4412 int round;
4413 _PyTime_t ts;
4414
4415 if (!PyArg_ParseTuple(args, "Oi", &obj, &round))
4416 return NULL;
4417 if (check_time_rounding(round) < 0)
4418 return NULL;
4419 if (_PyTime_FromSecondsObject(&ts, obj, round) == -1)
4420 return NULL;
4421 return _PyTime_AsNanosecondsObject(ts);
4422}
4423
Victor Stinner4bfb4602015-03-27 22:27:24 +01004424static PyObject *
4425test_pytime_assecondsdouble(PyObject *self, PyObject *args)
4426{
Victor Stinnerc29b5852017-11-02 07:28:27 -07004427 PyObject *obj;
Victor Stinner4bfb4602015-03-27 22:27:24 +01004428 _PyTime_t ts;
4429 double d;
4430
Victor Stinnerc29b5852017-11-02 07:28:27 -07004431 if (!PyArg_ParseTuple(args, "O", &obj)) {
Victor Stinner4bfb4602015-03-27 22:27:24 +01004432 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004433 }
4434 if (_PyTime_FromNanosecondsObject(&ts, obj) < 0) {
4435 return NULL;
4436 }
Victor Stinner4bfb4602015-03-27 22:27:24 +01004437 d = _PyTime_AsSecondsDouble(ts);
4438 return PyFloat_FromDouble(d);
4439}
4440
Victor Stinner95e9cef2015-03-28 01:26:47 +01004441static PyObject *
4442test_PyTime_AsTimeval(PyObject *self, PyObject *args)
4443{
Victor Stinnerc29b5852017-11-02 07:28:27 -07004444 PyObject *obj;
Victor Stinner95e9cef2015-03-28 01:26:47 +01004445 int round;
4446 _PyTime_t t;
4447 struct timeval tv;
4448 PyObject *seconds;
4449
Victor Stinnerc29b5852017-11-02 07:28:27 -07004450 if (!PyArg_ParseTuple(args, "Oi", &obj, &round))
Victor Stinner95e9cef2015-03-28 01:26:47 +01004451 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004452 if (check_time_rounding(round) < 0) {
Victor Stinner95e9cef2015-03-28 01:26:47 +01004453 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004454 }
4455 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
Victor Stinner95e9cef2015-03-28 01:26:47 +01004456 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004457 }
4458 if (_PyTime_AsTimeval(t, &tv, round) < 0) {
4459 return NULL;
4460 }
Victor Stinner95e9cef2015-03-28 01:26:47 +01004461
Benjamin Peterson2c134c32017-04-13 01:44:54 -07004462 seconds = PyLong_FromLongLong(tv.tv_sec);
Victor Stinnerc29b5852017-11-02 07:28:27 -07004463 if (seconds == NULL) {
Victor Stinner95e9cef2015-03-28 01:26:47 +01004464 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004465 }
Victor Stinner95e9cef2015-03-28 01:26:47 +01004466 return Py_BuildValue("Nl", seconds, tv.tv_usec);
4467}
4468
Victor Stinner34dc0f42015-03-27 18:19:03 +01004469#ifdef HAVE_CLOCK_GETTIME
4470static PyObject *
4471test_PyTime_AsTimespec(PyObject *self, PyObject *args)
4472{
Victor Stinnerc29b5852017-11-02 07:28:27 -07004473 PyObject *obj;
Victor Stinner34dc0f42015-03-27 18:19:03 +01004474 _PyTime_t t;
4475 struct timespec ts;
4476
Victor Stinnerc29b5852017-11-02 07:28:27 -07004477 if (!PyArg_ParseTuple(args, "O", &obj)) {
Victor Stinner34dc0f42015-03-27 18:19:03 +01004478 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004479 }
4480 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
Victor Stinner34dc0f42015-03-27 18:19:03 +01004481 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004482 }
4483 if (_PyTime_AsTimespec(t, &ts) == -1) {
4484 return NULL;
4485 }
Victor Stinner34dc0f42015-03-27 18:19:03 +01004486 return Py_BuildValue("Nl", _PyLong_FromTime_t(ts.tv_sec), ts.tv_nsec);
4487}
4488#endif
4489
Victor Stinner62d1c702015-04-01 17:47:07 +02004490static PyObject *
4491test_PyTime_AsMilliseconds(PyObject *self, PyObject *args)
4492{
Victor Stinnerc29b5852017-11-02 07:28:27 -07004493 PyObject *obj;
Victor Stinner62d1c702015-04-01 17:47:07 +02004494 int round;
4495 _PyTime_t t, ms;
4496
Victor Stinnerc29b5852017-11-02 07:28:27 -07004497 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
Victor Stinner62d1c702015-04-01 17:47:07 +02004498 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004499 }
4500 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
Victor Stinner62d1c702015-04-01 17:47:07 +02004501 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004502 }
4503 if (check_time_rounding(round) < 0) {
4504 return NULL;
4505 }
Victor Stinner62d1c702015-04-01 17:47:07 +02004506 ms = _PyTime_AsMilliseconds(t, round);
4507 /* This conversion rely on the fact that _PyTime_t is a number of
4508 nanoseconds */
4509 return _PyTime_AsNanosecondsObject(ms);
4510}
4511
4512static PyObject *
4513test_PyTime_AsMicroseconds(PyObject *self, PyObject *args)
4514{
Victor Stinnerc29b5852017-11-02 07:28:27 -07004515 PyObject *obj;
Victor Stinner62d1c702015-04-01 17:47:07 +02004516 int round;
4517 _PyTime_t t, ms;
4518
Victor Stinnerc29b5852017-11-02 07:28:27 -07004519 if (!PyArg_ParseTuple(args, "Oi", &obj, &round))
Victor Stinner62d1c702015-04-01 17:47:07 +02004520 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004521 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
Victor Stinner62d1c702015-04-01 17:47:07 +02004522 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07004523 }
4524 if (check_time_rounding(round) < 0) {
4525 return NULL;
4526 }
Victor Stinner62d1c702015-04-01 17:47:07 +02004527 ms = _PyTime_AsMicroseconds(t, round);
4528 /* This conversion rely on the fact that _PyTime_t is a number of
4529 nanoseconds */
4530 return _PyTime_AsNanosecondsObject(ms);
4531}
4532
Victor Stinner50856d52015-10-13 00:11:21 +02004533static PyObject*
4534get_recursion_depth(PyObject *self, PyObject *args)
4535{
Victor Stinner50b48572018-11-01 01:51:40 +01004536 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner50856d52015-10-13 00:11:21 +02004537
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07004538 /* subtract one to ignore the frame of the get_recursion_depth() call */
Victor Stinner50856d52015-10-13 00:11:21 +02004539 return PyLong_FromLong(tstate->recursion_depth - 1);
4540}
4541
Victor Stinner34be807c2016-03-14 12:04:26 +01004542static PyObject*
4543pymem_buffer_overflow(PyObject *self, PyObject *args)
4544{
4545 char *buffer;
4546
4547 /* Deliberate buffer overflow to check that PyMem_Free() detects
4548 the overflow when debug hooks are installed. */
4549 buffer = PyMem_Malloc(16);
Victor Stinner414b1cd2019-03-26 14:35:30 +01004550 if (buffer == NULL) {
4551 PyErr_NoMemory();
4552 return NULL;
4553 }
Victor Stinner34be807c2016-03-14 12:04:26 +01004554 buffer[16] = 'x';
4555 PyMem_Free(buffer);
4556
4557 Py_RETURN_NONE;
4558}
4559
4560static PyObject*
4561pymem_api_misuse(PyObject *self, PyObject *args)
4562{
4563 char *buffer;
4564
4565 /* Deliberate misusage of Python allocators:
4566 allococate with PyMem but release with PyMem_Raw. */
4567 buffer = PyMem_Malloc(16);
4568 PyMem_RawFree(buffer);
4569
4570 Py_RETURN_NONE;
4571}
4572
Victor Stinnerc4aec362016-03-14 22:26:53 +01004573static PyObject*
Victor Stinnerad524372016-03-16 12:12:53 +01004574pymem_malloc_without_gil(PyObject *self, PyObject *args)
4575{
4576 char *buffer;
4577
4578 /* Deliberate bug to test debug hooks on Python memory allocators:
4579 call PyMem_Malloc() without holding the GIL */
4580 Py_BEGIN_ALLOW_THREADS
4581 buffer = PyMem_Malloc(10);
4582 Py_END_ALLOW_THREADS
4583
4584 PyMem_Free(buffer);
4585
4586 Py_RETURN_NONE;
4587}
4588
Victor Stinner5d39e042017-11-29 17:20:38 +01004589
4590static PyObject*
4591test_pymem_getallocatorsname(PyObject *self, PyObject *args)
4592{
Victor Stinnerb16b4e42019-05-17 15:20:52 +02004593 const char *name = _PyMem_GetCurrentAllocatorName();
Victor Stinner5d39e042017-11-29 17:20:38 +01004594 if (name == NULL) {
4595 PyErr_SetString(PyExc_RuntimeError, "cannot get allocators name");
4596 return NULL;
4597 }
4598 return PyUnicode_FromString(name);
4599}
4600
4601
Victor Stinnerad524372016-03-16 12:12:53 +01004602static PyObject*
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004603test_pyobject_is_freed(const char *test_name, PyObject *op)
Victor Stinner2b00db62019-04-11 11:33:27 +02004604{
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004605 if (!_PyObject_IsFreed(op)) {
4606 return raiseTestError(test_name, "object is not seen as freed");
4607 }
4608 Py_RETURN_NONE;
Victor Stinner2b00db62019-04-11 11:33:27 +02004609}
4610
4611
4612static PyObject*
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004613check_pyobject_uninitialized_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
Victor Stinner2b00db62019-04-11 11:33:27 +02004614{
4615 PyObject *op = (PyObject *)PyObject_Malloc(sizeof(PyObject));
4616 if (op == NULL) {
4617 return NULL;
4618 }
4619 /* Initialize reference count to avoid early crash in ceval or GC */
4620 Py_REFCNT(op) = 1;
4621 /* object fields like ob_type are uninitialized! */
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004622 return test_pyobject_is_freed("check_pyobject_uninitialized_is_freed", op);
Victor Stinner2b00db62019-04-11 11:33:27 +02004623}
4624
4625
4626static PyObject*
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004627check_pyobject_forbidden_bytes_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
Victor Stinner2b00db62019-04-11 11:33:27 +02004628{
4629 /* Allocate an incomplete PyObject structure: truncate 'ob_type' field */
4630 PyObject *op = (PyObject *)PyObject_Malloc(offsetof(PyObject, ob_type));
4631 if (op == NULL) {
4632 return NULL;
4633 }
4634 /* Initialize reference count to avoid early crash in ceval or GC */
4635 Py_REFCNT(op) = 1;
4636 /* ob_type field is after the memory block: part of "forbidden bytes"
Min ho Kim39d87b52019-08-31 06:21:19 +10004637 when using debug hooks on memory allocators! */
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004638 return test_pyobject_is_freed("check_pyobject_forbidden_bytes_is_freed", op);
Victor Stinner2b00db62019-04-11 11:33:27 +02004639}
4640
4641
4642static PyObject*
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004643check_pyobject_freed_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
Victor Stinner2b00db62019-04-11 11:33:27 +02004644{
4645 PyObject *op = _PyObject_CallNoArg((PyObject *)&PyBaseObject_Type);
4646 if (op == NULL) {
4647 return NULL;
4648 }
4649 Py_TYPE(op)->tp_dealloc(op);
4650 /* Reset reference count to avoid early crash in ceval or GC */
4651 Py_REFCNT(op) = 1;
4652 /* object memory is freed! */
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02004653 return test_pyobject_is_freed("check_pyobject_freed_is_freed", op);
Victor Stinner2b00db62019-04-11 11:33:27 +02004654}
4655
4656
4657static PyObject*
Victor Stinnerc4aec362016-03-14 22:26:53 +01004658pyobject_malloc_without_gil(PyObject *self, PyObject *args)
4659{
4660 char *buffer;
4661
Victor Stinnerad524372016-03-16 12:12:53 +01004662 /* Deliberate bug to test debug hooks on Python memory allocators:
4663 call PyObject_Malloc() without holding the GIL */
Victor Stinnerc4aec362016-03-14 22:26:53 +01004664 Py_BEGIN_ALLOW_THREADS
4665 buffer = PyObject_Malloc(10);
4666 Py_END_ALLOW_THREADS
4667
4668 PyObject_Free(buffer);
4669
4670 Py_RETURN_NONE;
4671}
4672
Victor Stinner10b73e12016-03-22 13:39:05 +01004673static PyObject *
4674tracemalloc_track(PyObject *self, PyObject *args)
4675{
4676 unsigned int domain;
4677 PyObject *ptr_obj;
4678 void *ptr;
4679 Py_ssize_t size;
4680 int release_gil = 0;
4681 int res;
4682
4683 if (!PyArg_ParseTuple(args, "IOn|i", &domain, &ptr_obj, &size, &release_gil))
4684 return NULL;
4685 ptr = PyLong_AsVoidPtr(ptr_obj);
4686 if (PyErr_Occurred())
4687 return NULL;
4688
4689 if (release_gil) {
4690 Py_BEGIN_ALLOW_THREADS
Victor Stinner5ea4c062017-06-20 17:46:36 +02004691 res = PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
Victor Stinner10b73e12016-03-22 13:39:05 +01004692 Py_END_ALLOW_THREADS
4693 }
4694 else {
Victor Stinner5ea4c062017-06-20 17:46:36 +02004695 res = PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
Victor Stinner10b73e12016-03-22 13:39:05 +01004696 }
4697
4698 if (res < 0) {
Victor Stinner5ea4c062017-06-20 17:46:36 +02004699 PyErr_SetString(PyExc_RuntimeError, "PyTraceMalloc_Track error");
Victor Stinner10b73e12016-03-22 13:39:05 +01004700 return NULL;
4701 }
4702
4703 Py_RETURN_NONE;
4704}
4705
4706static PyObject *
4707tracemalloc_untrack(PyObject *self, PyObject *args)
4708{
4709 unsigned int domain;
4710 PyObject *ptr_obj;
4711 void *ptr;
4712 int res;
4713
4714 if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
4715 return NULL;
4716 ptr = PyLong_AsVoidPtr(ptr_obj);
4717 if (PyErr_Occurred())
4718 return NULL;
4719
Victor Stinner5ea4c062017-06-20 17:46:36 +02004720 res = PyTraceMalloc_Untrack(domain, (uintptr_t)ptr);
Victor Stinner10b73e12016-03-22 13:39:05 +01004721 if (res < 0) {
Victor Stinner5ea4c062017-06-20 17:46:36 +02004722 PyErr_SetString(PyExc_RuntimeError, "PyTraceMalloc_Untrack error");
Victor Stinner10b73e12016-03-22 13:39:05 +01004723 return NULL;
4724 }
4725
4726 Py_RETURN_NONE;
4727}
4728
4729static PyObject *
4730tracemalloc_get_traceback(PyObject *self, PyObject *args)
4731{
4732 unsigned int domain;
4733 PyObject *ptr_obj;
4734 void *ptr;
4735
4736 if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
4737 return NULL;
4738 ptr = PyLong_AsVoidPtr(ptr_obj);
4739 if (PyErr_Occurred())
4740 return NULL;
4741
Benjamin Petersonca470632016-09-06 13:47:26 -07004742 return _PyTraceMalloc_GetTraceback(domain, (uintptr_t)ptr);
Victor Stinner10b73e12016-03-22 13:39:05 +01004743}
4744
Victor Stinner3b6a6b42016-09-08 12:51:24 -07004745static PyObject *
4746dict_get_version(PyObject *self, PyObject *args)
4747{
4748 PyDictObject *dict;
4749 uint64_t version;
4750
4751 if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
4752 return NULL;
4753
4754 version = dict->ma_version_tag;
4755
4756 Py_BUILD_ASSERT(sizeof(unsigned PY_LONG_LONG) >= sizeof(version));
4757 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)version);
4758}
4759
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004760
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07004761static PyObject *
4762raise_SIGINT_then_send_None(PyObject *self, PyObject *args)
4763{
4764 PyGenObject *gen;
4765
4766 if (!PyArg_ParseTuple(args, "O!", &PyGen_Type, &gen))
4767 return NULL;
4768
4769 /* This is used in a test to check what happens if a signal arrives just
4770 as we're in the process of entering a yield from chain (see
4771 bpo-30039).
4772
4773 Needs to be done in C, because:
4774 - we don't have a Python wrapper for raise()
4775 - we need to make sure that the Python-level signal handler doesn't run
4776 *before* we enter the generator frame, which is impossible in Python
4777 because we check for signals before every bytecode operation.
4778 */
4779 raise(SIGINT);
4780 return _PyGen_Send(gen, Py_None);
4781}
4782
4783
Victor Stinner3b5cf852017-06-09 16:48:45 +02004784static int
4785fastcall_args(PyObject *args, PyObject ***stack, Py_ssize_t *nargs)
4786{
4787 if (args == Py_None) {
4788 *stack = NULL;
4789 *nargs = 0;
4790 }
4791 else if (PyTuple_Check(args)) {
Victor Stinnerd17a6932018-11-09 16:56:48 +01004792 *stack = ((PyTupleObject *)args)->ob_item;
Victor Stinner3b5cf852017-06-09 16:48:45 +02004793 *nargs = PyTuple_GET_SIZE(args);
4794 }
4795 else {
4796 PyErr_SetString(PyExc_TypeError, "args must be None or a tuple");
4797 return -1;
4798 }
4799 return 0;
4800}
4801
4802
4803static PyObject *
4804test_pyobject_fastcall(PyObject *self, PyObject *args)
4805{
4806 PyObject *func, *func_args;
4807 PyObject **stack;
4808 Py_ssize_t nargs;
4809
4810 if (!PyArg_ParseTuple(args, "OO", &func, &func_args)) {
4811 return NULL;
4812 }
4813
4814 if (fastcall_args(func_args, &stack, &nargs) < 0) {
4815 return NULL;
4816 }
4817 return _PyObject_FastCall(func, stack, nargs);
4818}
4819
4820
4821static PyObject *
4822test_pyobject_fastcalldict(PyObject *self, PyObject *args)
4823{
4824 PyObject *func, *func_args, *kwargs;
4825 PyObject **stack;
4826 Py_ssize_t nargs;
4827
4828 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwargs)) {
4829 return NULL;
4830 }
4831
4832 if (fastcall_args(func_args, &stack, &nargs) < 0) {
4833 return NULL;
4834 }
4835
4836 if (kwargs == Py_None) {
4837 kwargs = NULL;
4838 }
4839 else if (!PyDict_Check(kwargs)) {
4840 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a dict");
4841 return NULL;
4842 }
4843
4844 return _PyObject_FastCallDict(func, stack, nargs, kwargs);
4845}
4846
4847
4848static PyObject *
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02004849test_pyobject_vectorcall(PyObject *self, PyObject *args)
Victor Stinner3b5cf852017-06-09 16:48:45 +02004850{
4851 PyObject *func, *func_args, *kwnames = NULL;
4852 PyObject **stack;
4853 Py_ssize_t nargs, nkw;
4854
4855 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwnames)) {
4856 return NULL;
4857 }
4858
4859 if (fastcall_args(func_args, &stack, &nargs) < 0) {
4860 return NULL;
4861 }
4862
4863 if (kwnames == Py_None) {
4864 kwnames = NULL;
4865 }
4866 else if (PyTuple_Check(kwnames)) {
4867 nkw = PyTuple_GET_SIZE(kwnames);
4868 if (nargs < nkw) {
4869 PyErr_SetString(PyExc_ValueError, "kwnames longer than args");
4870 return NULL;
4871 }
4872 nargs -= nkw;
4873 }
4874 else {
4875 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a tuple");
4876 return NULL;
4877 }
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02004878 return _PyObject_Vectorcall(func, stack, nargs, kwnames);
4879}
4880
4881
4882static PyObject *
4883test_pyvectorcall_call(PyObject *self, PyObject *args)
4884{
4885 PyObject *func;
4886 PyObject *argstuple;
4887 PyObject *kwargs = NULL;
4888
4889 if (!PyArg_ParseTuple(args, "OO|O", &func, &argstuple, &kwargs)) {
4890 return NULL;
4891 }
4892
4893 if (!PyTuple_Check(argstuple)) {
4894 PyErr_SetString(PyExc_TypeError, "args must be a tuple");
4895 return NULL;
4896 }
4897 if (kwargs != NULL && !PyDict_Check(kwargs)) {
4898 PyErr_SetString(PyExc_TypeError, "kwargs must be a dict");
4899 return NULL;
4900 }
4901
4902 return PyVectorcall_Call(func, argstuple, kwargs);
Victor Stinner3b5cf852017-06-09 16:48:45 +02004903}
4904
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02004905
Victor Stinner64fa4492017-07-10 14:37:49 +02004906static PyObject*
4907stack_pointer(PyObject *self, PyObject *args)
4908{
4909 int v = 5;
4910 return PyLong_FromVoidPtr(&v);
4911}
4912
Victor Stinner3b5cf852017-06-09 16:48:45 +02004913
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02004914#ifdef W_STOPCODE
4915static PyObject*
4916py_w_stopcode(PyObject *self, PyObject *args)
4917{
4918 int sig, status;
4919 if (!PyArg_ParseTuple(args, "i", &sig)) {
4920 return NULL;
4921 }
4922 status = W_STOPCODE(sig);
4923 return PyLong_FromLong(status);
4924}
4925#endif
4926
4927
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09004928static PyObject *
Oren Milman0ccc0f62017-10-08 11:17:46 +03004929get_mapping_keys(PyObject* self, PyObject *obj)
4930{
4931 return PyMapping_Keys(obj);
4932}
4933
4934static PyObject *
4935get_mapping_values(PyObject* self, PyObject *obj)
4936{
4937 return PyMapping_Values(obj);
4938}
4939
4940static PyObject *
4941get_mapping_items(PyObject* self, PyObject *obj)
4942{
4943 return PyMapping_Items(obj);
4944}
4945
4946
4947static PyObject *
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09004948test_pythread_tss_key_state(PyObject *self, PyObject *args)
4949{
4950 Py_tss_t tss_key = Py_tss_NEEDS_INIT;
4951 if (PyThread_tss_is_created(&tss_key)) {
4952 return raiseTestError("test_pythread_tss_key_state",
4953 "TSS key not in an uninitialized state at "
4954 "creation time");
4955 }
4956 if (PyThread_tss_create(&tss_key) != 0) {
4957 PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_create failed");
4958 return NULL;
4959 }
4960 if (!PyThread_tss_is_created(&tss_key)) {
4961 return raiseTestError("test_pythread_tss_key_state",
4962 "PyThread_tss_create succeeded, "
4963 "but with TSS key in an uninitialized state");
4964 }
4965 if (PyThread_tss_create(&tss_key) != 0) {
4966 return raiseTestError("test_pythread_tss_key_state",
4967 "PyThread_tss_create unsuccessful with "
4968 "an already initialized key");
4969 }
4970#define CHECK_TSS_API(expr) \
4971 (void)(expr); \
4972 if (!PyThread_tss_is_created(&tss_key)) { \
4973 return raiseTestError("test_pythread_tss_key_state", \
4974 "TSS key initialization state was not " \
4975 "preserved after calling " #expr); }
4976 CHECK_TSS_API(PyThread_tss_set(&tss_key, NULL));
4977 CHECK_TSS_API(PyThread_tss_get(&tss_key));
4978#undef CHECK_TSS_API
4979 PyThread_tss_delete(&tss_key);
4980 if (PyThread_tss_is_created(&tss_key)) {
4981 return raiseTestError("test_pythread_tss_key_state",
4982 "PyThread_tss_delete called, but did not "
4983 "set the key state to uninitialized");
4984 }
4985
4986 Py_tss_t *ptr_key = PyThread_tss_alloc();
4987 if (ptr_key == NULL) {
4988 PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_alloc failed");
4989 return NULL;
4990 }
4991 if (PyThread_tss_is_created(ptr_key)) {
4992 return raiseTestError("test_pythread_tss_key_state",
4993 "TSS key not in an uninitialized state at "
4994 "allocation time");
4995 }
4996 PyThread_tss_free(ptr_key);
4997 ptr_key = NULL;
4998 Py_RETURN_NONE;
4999}
5000
5001
Yury Selivanovf23746a2018-01-22 19:11:18 -05005002static PyObject*
5003new_hamt(PyObject *self, PyObject *args)
5004{
5005 return _PyContext_NewHamtForTests();
5006}
5007
5008
jdemeyer5a306202018-10-19 23:50:06 +02005009/* def bad_get(self, obj, cls):
5010 cls()
5011 return repr(self)
5012*/
5013static PyObject*
5014bad_get(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
5015{
Serhiy Storchakab1dede32018-11-20 20:45:40 +02005016 PyObject *self, *obj, *cls;
5017 if (!_PyArg_UnpackStack(args, nargs, "bad_get", 3, 3, &self, &obj, &cls)) {
jdemeyer5a306202018-10-19 23:50:06 +02005018 return NULL;
5019 }
5020
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02005021 PyObject *res = _PyObject_CallNoArg(cls);
jdemeyer5a306202018-10-19 23:50:06 +02005022 if (res == NULL) {
5023 return NULL;
5024 }
5025 Py_DECREF(res);
5026
Serhiy Storchakab1dede32018-11-20 20:45:40 +02005027 return PyObject_Repr(self);
jdemeyer5a306202018-10-19 23:50:06 +02005028}
5029
5030
Victor Stinner3d4226a2018-08-29 22:21:32 +02005031static PyObject *
5032encode_locale_ex(PyObject *self, PyObject *args)
5033{
5034 PyObject *unicode;
5035 int current_locale = 0;
5036 wchar_t *wstr;
5037 PyObject *res = NULL;
5038 const char *errors = NULL;
5039
5040 if (!PyArg_ParseTuple(args, "U|is", &unicode, &current_locale, &errors)) {
5041 return NULL;
5042 }
5043 wstr = PyUnicode_AsWideCharString(unicode, NULL);
5044 if (wstr == NULL) {
5045 return NULL;
5046 }
5047 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
5048
5049 char *str = NULL;
5050 size_t error_pos;
5051 const char *reason = NULL;
5052 int ret = _Py_EncodeLocaleEx(wstr,
5053 &str, &error_pos, &reason,
5054 current_locale, error_handler);
5055 PyMem_Free(wstr);
5056
5057 switch(ret) {
5058 case 0:
5059 res = PyBytes_FromString(str);
5060 PyMem_RawFree(str);
5061 break;
5062 case -1:
5063 PyErr_NoMemory();
5064 break;
5065 case -2:
5066 PyErr_Format(PyExc_RuntimeError, "encode error: pos=%zu, reason=%s",
5067 error_pos, reason);
5068 break;
5069 case -3:
5070 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
5071 break;
5072 default:
5073 PyErr_SetString(PyExc_ValueError, "unknow error code");
5074 break;
5075 }
5076 return res;
5077}
5078
5079
5080static PyObject *
5081decode_locale_ex(PyObject *self, PyObject *args)
5082{
5083 char *str;
5084 int current_locale = 0;
5085 PyObject *res = NULL;
5086 const char *errors = NULL;
5087
5088 if (!PyArg_ParseTuple(args, "y|is", &str, &current_locale, &errors)) {
5089 return NULL;
5090 }
5091 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
5092
5093 wchar_t *wstr = NULL;
5094 size_t wlen = 0;
5095 const char *reason = NULL;
5096 int ret = _Py_DecodeLocaleEx(str,
5097 &wstr, &wlen, &reason,
5098 current_locale, error_handler);
5099
5100 switch(ret) {
5101 case 0:
5102 res = PyUnicode_FromWideChar(wstr, wlen);
5103 PyMem_RawFree(wstr);
5104 break;
5105 case -1:
5106 PyErr_NoMemory();
5107 break;
5108 case -2:
5109 PyErr_Format(PyExc_RuntimeError, "decode error: pos=%zu, reason=%s",
5110 wlen, reason);
5111 break;
5112 case -3:
5113 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
5114 break;
5115 default:
5116 PyErr_SetString(PyExc_ValueError, "unknow error code");
5117 break;
5118 }
5119 return res;
5120}
5121
5122
Victor Stinner18618e652018-10-25 17:28:11 +02005123#ifdef Py_REF_DEBUG
5124static PyObject *
5125negative_refcount(PyObject *self, PyObject *Py_UNUSED(args))
5126{
5127 PyObject *obj = PyUnicode_FromString("negative_refcount");
5128 if (obj == NULL) {
5129 return NULL;
5130 }
5131 assert(Py_REFCNT(obj) == 1);
5132
5133 Py_REFCNT(obj) = 0;
5134 /* Py_DECREF() must call _Py_NegativeRefcount() and abort Python */
5135 Py_DECREF(obj);
5136
5137 Py_RETURN_NONE;
5138}
5139#endif
5140
5141
Victor Stinneref9d9b62019-05-22 11:28:22 +02005142static PyObject*
5143test_write_unraisable_exc(PyObject *self, PyObject *args)
5144{
Victor Stinner71c52e32019-05-27 08:57:14 +02005145 PyObject *exc, *err_msg, *obj;
5146 if (!PyArg_ParseTuple(args, "OOO", &exc, &err_msg, &obj)) {
Victor Stinneref9d9b62019-05-22 11:28:22 +02005147 return NULL;
5148 }
5149
Victor Stinner71c52e32019-05-27 08:57:14 +02005150 const char *err_msg_utf8;
5151 if (err_msg != Py_None) {
5152 err_msg_utf8 = PyUnicode_AsUTF8(err_msg);
5153 if (err_msg_utf8 == NULL) {
5154 return NULL;
5155 }
5156 }
5157 else {
5158 err_msg_utf8 = NULL;
5159 }
5160
Victor Stinneref9d9b62019-05-22 11:28:22 +02005161 PyErr_SetObject((PyObject *)Py_TYPE(exc), exc);
Victor Stinner71c52e32019-05-27 08:57:14 +02005162 _PyErr_WriteUnraisableMsg(err_msg_utf8, obj);
Victor Stinneref9d9b62019-05-22 11:28:22 +02005163 Py_RETURN_NONE;
5164}
5165
5166
Sergey Fedoseev92709a22019-09-09 21:28:34 +05005167static PyObject *
5168sequence_getitem(PyObject *self, PyObject *args)
5169{
5170 PyObject *seq;
5171 Py_ssize_t i;
5172 if (!PyArg_ParseTuple(args, "On", &seq, &i)) {
5173 return NULL;
5174 }
5175 return PySequence_GetItem(seq, i);
5176}
5177
5178
Petr Viktorinf9583772019-09-10 12:21:09 +01005179/* Functions for testing C calling conventions (METH_*) are named meth_*,
5180 * e.g. "meth_varargs" for METH_VARARGS.
5181 *
5182 * They all return a tuple of their C-level arguments, with None instead
5183 * of NULL and Python tuples instead of C arrays.
5184 */
5185
5186
5187static PyObject*
5188_null_to_none(PyObject* obj)
5189{
5190 if (obj == NULL) {
5191 Py_RETURN_NONE;
5192 }
5193 Py_INCREF(obj);
5194 return obj;
5195}
5196
5197static PyObject*
5198meth_varargs(PyObject* self, PyObject* args)
5199{
5200 return Py_BuildValue("NO", _null_to_none(self), args);
5201}
5202
5203static PyObject*
5204meth_varargs_keywords(PyObject* self, PyObject* args, PyObject* kwargs)
5205{
5206 return Py_BuildValue("NON", _null_to_none(self), args, _null_to_none(kwargs));
5207}
5208
5209static PyObject*
5210meth_o(PyObject* self, PyObject* obj)
5211{
5212 return Py_BuildValue("NO", _null_to_none(self), obj);
5213}
5214
5215static PyObject*
5216meth_noargs(PyObject* self, PyObject* ignored)
5217{
5218 return _null_to_none(self);
5219}
5220
5221static PyObject*
5222_fastcall_to_tuple(PyObject* const* args, Py_ssize_t nargs)
5223{
5224 PyObject *tuple = PyTuple_New(nargs);
5225 if (tuple == NULL) {
5226 return NULL;
5227 }
5228 for (Py_ssize_t i=0; i < nargs; i++) {
5229 Py_INCREF(args[i]);
5230 PyTuple_SET_ITEM(tuple, i, args[i]);
5231 }
5232 return tuple;
5233}
5234
5235static PyObject*
5236meth_fastcall(PyObject* self, PyObject* const* args, Py_ssize_t nargs)
5237{
5238 return Py_BuildValue(
5239 "NN", _null_to_none(self), _fastcall_to_tuple(args, nargs)
5240 );
5241}
5242
5243static PyObject*
5244meth_fastcall_keywords(PyObject* self, PyObject* const* args,
5245 Py_ssize_t nargs, PyObject* kwargs)
5246{
5247 PyObject *pyargs = _fastcall_to_tuple(args, nargs);
5248 if (pyargs == NULL) {
5249 return NULL;
5250 }
5251 PyObject *pykwargs = _PyObject_Vectorcall((PyObject*)&PyDict_Type,
5252 args + nargs, 0, kwargs);
5253 return Py_BuildValue("NNN", _null_to_none(self), pyargs, pykwargs);
5254}
5255
Tim Peters9ea17ac2001-02-02 05:57:15 +00005256static PyMethodDef TestMethods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 {"raise_exception", raise_exception, METH_VARARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305258 {"raise_memoryerror", raise_memoryerror, METH_NOARGS},
Antoine Pitrou6bc217d2015-06-23 14:31:11 +02005259 {"set_errno", set_errno, METH_VARARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305260 {"test_config", test_config, METH_NOARGS},
5261 {"test_sizeof_c_types", test_sizeof_c_types, METH_NOARGS},
Edison A98ff4d52019-05-17 13:28:42 -07005262 {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
Paul Ganssle04af5b12018-01-24 17:29:30 -05005263 {"datetime_check_date", datetime_check_date, METH_VARARGS},
5264 {"datetime_check_time", datetime_check_time, METH_VARARGS},
5265 {"datetime_check_datetime", datetime_check_datetime, METH_VARARGS},
5266 {"datetime_check_delta", datetime_check_delta, METH_VARARGS},
5267 {"datetime_check_tzinfo", datetime_check_tzinfo, METH_VARARGS},
5268 {"make_timezones_capi", make_timezones_capi, METH_NOARGS},
Paul Gansslea049f572018-02-22 15:15:32 -05005269 {"get_timezones_offset_zero", get_timezones_offset_zero, METH_NOARGS},
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04005270 {"get_timezone_utc_capi", get_timezone_utc_capi, METH_VARARGS},
Edison A98ff4d52019-05-17 13:28:42 -07005271 {"get_date_fromdate", get_date_fromdate, METH_VARARGS},
5272 {"get_datetime_fromdateandtime", get_datetime_fromdateandtime, METH_VARARGS},
5273 {"get_datetime_fromdateandtimeandfold", get_datetime_fromdateandtimeandfold, METH_VARARGS},
5274 {"get_time_fromtime", get_time_fromtime, METH_VARARGS},
5275 {"get_time_fromtimeandfold", get_time_fromtimeandfold, METH_VARARGS},
5276 {"get_delta_fromdsu", get_delta_fromdsu, METH_VARARGS},
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04005277 {"get_date_fromtimestamp", get_date_fromtimestamp, METH_VARARGS},
5278 {"get_datetime_fromtimestamp", get_datetime_fromtimestamp, METH_VARARGS},
Joannah Nanjekye2c5fb172019-08-29 09:54:46 -03005279 {"PyDateTime_GET", test_PyDateTime_GET, METH_O},
5280 {"PyDateTime_DATE_GET", test_PyDateTime_DATE_GET, METH_O},
5281 {"PyDateTime_TIME_GET", test_PyDateTime_TIME_GET, METH_O},
5282 {"PyDateTime_DELTA_GET", test_PyDateTime_DELTA_GET, METH_O},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305283 {"test_list_api", test_list_api, METH_NOARGS},
5284 {"test_dict_iteration", test_dict_iteration, METH_NOARGS},
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02005285 {"dict_getitem_knownhash", dict_getitem_knownhash, METH_VARARGS},
Victor Stinner3d3f2642016-12-15 17:21:23 +01005286 {"dict_hassplittable", dict_hassplittable, METH_O},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305287 {"test_lazy_hash_inheritance", test_lazy_hash_inheritance,METH_NOARGS},
5288 {"test_long_api", test_long_api, METH_NOARGS},
5289 {"test_xincref_doesnt_leak",test_xincref_doesnt_leak, METH_NOARGS},
5290 {"test_incref_doesnt_leak", test_incref_doesnt_leak, METH_NOARGS},
5291 {"test_xdecref_doesnt_leak",test_xdecref_doesnt_leak, METH_NOARGS},
5292 {"test_decref_doesnt_leak", test_decref_doesnt_leak, METH_NOARGS},
Eddie Elizondo474eedf2018-11-13 04:09:31 -08005293 {"test_structseq_newtype_doesnt_leak",
5294 test_structseq_newtype_doesnt_leak, METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305295 {"test_incref_decref_API", test_incref_decref_API, METH_NOARGS},
5296 {"test_long_and_overflow", test_long_and_overflow, METH_NOARGS},
5297 {"test_long_as_double", test_long_as_double, METH_NOARGS},
5298 {"test_long_as_size_t", test_long_as_size_t, METH_NOARGS},
Zackery Spytzdc247652019-06-06 14:39:23 -06005299 {"test_long_as_unsigned_long_long_mask",
5300 test_long_as_unsigned_long_long_mask, METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305301 {"test_long_numbits", test_long_numbits, METH_NOARGS},
5302 {"test_k_code", test_k_code, METH_NOARGS},
5303 {"test_empty_argparse", test_empty_argparse, METH_NOARGS},
Larry Hastings8f904da2012-06-22 03:56:29 -07005304 {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305305 {"test_null_strings", test_null_strings, METH_NOARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305307 {"test_with_docstring", test_with_docstring, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 PyDoc_STR("This is a pretty normal docstring.")},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305309 {"test_string_to_double", test_string_to_double, METH_NOARGS},
5310 {"test_unicode_compare_with_ascii", test_unicode_compare_with_ascii,
5311 METH_NOARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
Stefan Krah7213fcc2015-02-01 16:19:23 +01005313 {"test_from_contiguous", (PyCFunction)test_from_contiguous, METH_NOARGS},
Stefan Kraha7559c02015-02-03 22:27:21 +01005314#if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
Stefan Krah5178d912015-02-03 16:57:21 +01005315 {"test_pep3118_obsolete_write_locks", (PyCFunction)test_pep3118_obsolete_write_locks, METH_NOARGS},
Stefan Kraha7559c02015-02-03 22:27:21 +01005316#endif
Stefan Krah650c1e82015-02-03 21:43:23 +01005317 {"getbuffer_with_null_view", getbuffer_with_null_view, METH_O},
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -03005318 {"PyBuffer_SizeFromFormat", test_PyBuffer_SizeFromFormat, METH_VARARGS},
Serhiy Storchaka13e602e2016-05-20 22:31:14 +03005319 {"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
Serhiy Storchakace412872016-05-08 23:36:44 +03005320 {"get_args", get_args, METH_VARARGS},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005321 {"get_kwargs", (PyCFunction)(void(*)(void))get_kwargs, METH_VARARGS|METH_KEYWORDS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 {"getargs_tuple", getargs_tuple, METH_VARARGS},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005323 {"getargs_keywords", (PyCFunction)(void(*)(void))getargs_keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 METH_VARARGS|METH_KEYWORDS},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005325 {"getargs_keyword_only", (PyCFunction)(void(*)(void))getargs_keyword_only,
Larry Hastings83a9f482012-03-20 20:06:16 +00005326 METH_VARARGS|METH_KEYWORDS},
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +03005327 {"getargs_positional_only_and_keywords",
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005328 (PyCFunction)(void(*)(void))getargs_positional_only_and_keywords,
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +03005329 METH_VARARGS|METH_KEYWORDS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 {"getargs_b", getargs_b, METH_VARARGS},
5331 {"getargs_B", getargs_B, METH_VARARGS},
5332 {"getargs_h", getargs_h, METH_VARARGS},
5333 {"getargs_H", getargs_H, METH_VARARGS},
5334 {"getargs_I", getargs_I, METH_VARARGS},
5335 {"getargs_k", getargs_k, METH_VARARGS},
5336 {"getargs_i", getargs_i, METH_VARARGS},
5337 {"getargs_l", getargs_l, METH_VARARGS},
5338 {"getargs_n", getargs_n, METH_VARARGS},
Larry Hastingsfaf91e72012-05-05 16:54:29 -07005339 {"getargs_p", getargs_p, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 {"getargs_L", getargs_L, METH_VARARGS},
5341 {"getargs_K", getargs_K, METH_VARARGS},
5342 {"test_longlong_api", test_longlong_api, METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305343 {"test_long_long_and_overflow",test_long_long_and_overflow, METH_NOARGS},
5344 {"test_L_code", test_L_code, METH_NOARGS},
Serhiy Storchakaf95455d2016-05-16 10:11:47 +03005345 {"getargs_f", getargs_f, METH_VARARGS},
5346 {"getargs_d", getargs_d, METH_VARARGS},
5347 {"getargs_D", getargs_D, METH_VARARGS},
5348 {"getargs_S", getargs_S, METH_VARARGS},
5349 {"getargs_Y", getargs_Y, METH_VARARGS},
5350 {"getargs_U", getargs_U, METH_VARARGS},
Eli Bendersky906b88f2011-07-29 07:05:08 +03005351 {"getargs_c", getargs_c, METH_VARARGS},
Serhiy Storchakac8241fd2016-01-28 19:49:54 +02005352 {"getargs_C", getargs_C, METH_VARARGS},
Victor Stinner06e49dd2010-06-13 18:21:50 +00005353 {"getargs_s", getargs_s, METH_VARARGS},
5354 {"getargs_s_star", getargs_s_star, METH_VARARGS},
5355 {"getargs_s_hash", getargs_s_hash, METH_VARARGS},
5356 {"getargs_z", getargs_z, METH_VARARGS},
5357 {"getargs_z_star", getargs_z_star, METH_VARARGS},
5358 {"getargs_z_hash", getargs_z_hash, METH_VARARGS},
5359 {"getargs_y", getargs_y, METH_VARARGS},
5360 {"getargs_y_star", getargs_y_star, METH_VARARGS},
5361 {"getargs_y_hash", getargs_y_hash, METH_VARARGS},
5362 {"getargs_u", getargs_u, METH_VARARGS},
5363 {"getargs_u_hash", getargs_u_hash, METH_VARARGS},
5364 {"getargs_Z", getargs_Z, METH_VARARGS},
5365 {"getargs_Z_hash", getargs_Z_hash, METH_VARARGS},
Victor Stinner25e8ec42010-06-25 00:02:38 +00005366 {"getargs_w_star", getargs_w_star, METH_VARARGS},
Serhiy Storchakac8241fd2016-01-28 19:49:54 +02005367 {"getargs_es", getargs_es, METH_VARARGS},
5368 {"getargs_et", getargs_et, METH_VARARGS},
5369 {"getargs_es_hash", getargs_es_hash, METH_VARARGS},
5370 {"getargs_et_hash", getargs_et_hash, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 {"codec_incrementalencoder",
Victor Stinner1c24bd02010-10-02 11:03:13 +00005372 (PyCFunction)codec_incrementalencoder, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 {"codec_incrementaldecoder",
Victor Stinner1c24bd02010-10-02 11:03:13 +00005374 (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305375 {"test_s_code", test_s_code, METH_NOARGS},
5376 {"test_u_code", test_u_code, METH_NOARGS},
5377 {"test_Z_code", test_Z_code, METH_NOARGS},
5378 {"test_widechar", test_widechar, METH_NOARGS},
Victor Stinner42bf7752011-11-21 22:52:58 +01005379 {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS},
5380 {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS},
Serhiy Storchakacc164232016-10-02 21:29:26 +03005381 {"unicode_asucs4", unicode_asucs4, METH_VARARGS},
Hai Shi5623ac82019-07-20 02:56:23 -05005382 {"unicode_asutf8", unicode_asutf8, METH_VARARGS},
5383 {"unicode_asutf8andsize", unicode_asutf8andsize, METH_VARARGS},
Xiang Zhangb2110682016-12-20 22:52:33 +08005384 {"unicode_findchar", unicode_findchar, METH_VARARGS},
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03005385 {"unicode_copycharacters", unicode_copycharacters, METH_VARARGS},
Victor Stinner42bf7752011-11-21 22:52:58 +01005386 {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS},
5387 {"unicode_transformdecimaltoascii", unicode_transformdecimaltoascii, METH_VARARGS},
Stefan Krahe6996ed2012-11-02 14:44:20 +01005388 {"unicode_legacy_string", unicode_legacy_string, METH_VARARGS},
Victor Stinner1c24bd02010-10-02 11:03:13 +00005389 {"_test_thread_state", test_thread_state, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
Guido van Rossumddefaf32007-01-14 03:31:43 +00005391#ifdef HAVE_GETTIMEOFDAY
Victor Stinner1c24bd02010-10-02 11:03:13 +00005392 {"profile_int", profile_int, METH_NOARGS},
Guido van Rossumddefaf32007-01-14 03:31:43 +00005393#endif
Victor Stinner1c24bd02010-10-02 11:03:13 +00005394 {"traceback_print", traceback_print, METH_VARARGS},
5395 {"exception_print", exception_print, METH_VARARGS},
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +02005396 {"set_exc_info", test_set_exc_info, METH_VARARGS},
Victor Stinner1c24bd02010-10-02 11:03:13 +00005397 {"argparsing", argparsing, METH_VARARGS},
5398 {"code_newempty", code_newempty, METH_VARARGS},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005399 {"make_exception_with_doc", (PyCFunction)(void(*)(void))make_exception_with_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 METH_VARARGS | METH_KEYWORDS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305401 {"make_memoryview_from_NULL_pointer", make_memoryview_from_NULL_pointer,
Antoine Pitrou5bffa792011-02-24 20:50:49 +00005402 METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305403 {"crash_no_current_thread", crash_no_current_thread, METH_NOARGS},
Antoine Pitrou2f828f22012-01-18 00:21:11 +01005404 {"run_in_subinterp", run_in_subinterp, METH_VARARGS},
Victor Stinner5d272cc2012-03-13 13:35:55 +01005405 {"pytime_object_to_time_t", test_pytime_object_to_time_t, METH_VARARGS},
5406 {"pytime_object_to_timeval", test_pytime_object_to_timeval, METH_VARARGS},
Victor Stinner643cd682012-03-02 22:54:03 +01005407 {"pytime_object_to_timespec", test_pytime_object_to_timespec, METH_VARARGS},
Antoine Pitrou796564c2013-07-30 19:59:21 +02005408 {"with_tp_del", with_tp_del, METH_VARARGS},
Antoine Pitroub349e4c2014-08-06 19:31:40 -04005409 {"create_cfunction", create_cfunction, METH_NOARGS},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305410 {"test_pymem_alloc0", test_pymem_alloc0, METH_NOARGS},
5411 {"test_pymem_setrawallocators",test_pymem_setrawallocators, METH_NOARGS},
5412 {"test_pymem_setallocators",test_pymem_setallocators, METH_NOARGS},
5413 {"test_pyobject_setallocators",test_pyobject_setallocators, METH_NOARGS},
xdegaye85f64302017-07-01 14:14:45 +02005414 {"set_nomemory", (PyCFunction)set_nomemory, METH_VARARGS,
5415 PyDoc_STR("set_nomemory(start:int, stop:int = 0)")},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305416 {"remove_mem_hooks", remove_mem_hooks, METH_NOARGS,
xdegaye85f64302017-07-01 14:14:45 +02005417 PyDoc_STR("Remove memory hooks.")},
Larry Hastings44e2eaa2013-11-23 15:37:55 -08005418 {"no_docstring",
5419 (PyCFunction)test_with_docstring, METH_NOARGS},
5420 {"docstring_empty",
5421 (PyCFunction)test_with_docstring, METH_NOARGS,
5422 docstring_empty},
5423 {"docstring_no_signature",
5424 (PyCFunction)test_with_docstring, METH_NOARGS,
5425 docstring_no_signature},
5426 {"docstring_with_invalid_signature",
5427 (PyCFunction)test_with_docstring, METH_NOARGS,
5428 docstring_with_invalid_signature},
Larry Hastings2623c8c2014-02-08 22:15:29 -08005429 {"docstring_with_invalid_signature2",
5430 (PyCFunction)test_with_docstring, METH_NOARGS,
5431 docstring_with_invalid_signature2},
Larry Hastings44e2eaa2013-11-23 15:37:55 -08005432 {"docstring_with_signature",
5433 (PyCFunction)test_with_docstring, METH_NOARGS,
5434 docstring_with_signature},
Zachary Ware8ef887c2015-04-13 18:22:35 -05005435 {"docstring_with_signature_but_no_doc",
5436 (PyCFunction)test_with_docstring, METH_NOARGS,
5437 docstring_with_signature_but_no_doc},
Larry Hastings44e2eaa2013-11-23 15:37:55 -08005438 {"docstring_with_signature_and_extra_newlines",
5439 (PyCFunction)test_with_docstring, METH_NOARGS,
5440 docstring_with_signature_and_extra_newlines},
Larry Hastings16c51912014-01-07 11:53:01 -08005441 {"docstring_with_signature_with_defaults",
5442 (PyCFunction)test_with_docstring, METH_NOARGS,
5443 docstring_with_signature_with_defaults},
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005444 {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O,
5445 PyDoc_STR("set_error_class(error_class) -> None")},
Serhiy Storchakab5181342015-02-06 08:58:56 +02005446 {"pymarshal_write_long_to_file",
5447 pymarshal_write_long_to_file, METH_VARARGS},
5448 {"pymarshal_write_object_to_file",
5449 pymarshal_write_object_to_file, METH_VARARGS},
5450 {"pymarshal_read_short_from_file",
5451 pymarshal_read_short_from_file, METH_VARARGS},
5452 {"pymarshal_read_long_from_file",
5453 pymarshal_read_long_from_file, METH_VARARGS},
5454 {"pymarshal_read_last_object_from_file",
5455 pymarshal_read_last_object_from_file, METH_VARARGS},
5456 {"pymarshal_read_object_from_file",
5457 pymarshal_read_object_from_file, METH_VARARGS},
Victor Stinnerefde1462015-03-21 15:04:43 +01005458 {"return_null_without_error",
5459 return_null_without_error, METH_NOARGS},
5460 {"return_result_with_error",
5461 return_result_with_error, METH_NOARGS},
Victor Stinner13019fd2015-04-03 13:10:54 +02005462 {"PyTime_FromSeconds", test_pytime_fromseconds, METH_VARARGS},
Victor Stinner4bfb4602015-03-27 22:27:24 +01005463 {"PyTime_FromSecondsObject", test_pytime_fromsecondsobject, METH_VARARGS},
5464 {"PyTime_AsSecondsDouble", test_pytime_assecondsdouble, METH_VARARGS},
Victor Stinner95e9cef2015-03-28 01:26:47 +01005465 {"PyTime_AsTimeval", test_PyTime_AsTimeval, METH_VARARGS},
Victor Stinner34dc0f42015-03-27 18:19:03 +01005466#ifdef HAVE_CLOCK_GETTIME
5467 {"PyTime_AsTimespec", test_PyTime_AsTimespec, METH_VARARGS},
5468#endif
Victor Stinner62d1c702015-04-01 17:47:07 +02005469 {"PyTime_AsMilliseconds", test_PyTime_AsMilliseconds, METH_VARARGS},
5470 {"PyTime_AsMicroseconds", test_PyTime_AsMicroseconds, METH_VARARGS},
Victor Stinner50856d52015-10-13 00:11:21 +02005471 {"get_recursion_depth", get_recursion_depth, METH_NOARGS},
Victor Stinner34be807c2016-03-14 12:04:26 +01005472 {"pymem_buffer_overflow", pymem_buffer_overflow, METH_NOARGS},
5473 {"pymem_api_misuse", pymem_api_misuse, METH_NOARGS},
Victor Stinnerad524372016-03-16 12:12:53 +01005474 {"pymem_malloc_without_gil", pymem_malloc_without_gil, METH_NOARGS},
Victor Stinner5d39e042017-11-29 17:20:38 +01005475 {"pymem_getallocatorsname", test_pymem_getallocatorsname, METH_NOARGS},
Victor Stinner3bf0f3a2019-06-07 16:22:21 +02005476 {"check_pyobject_uninitialized_is_freed", check_pyobject_uninitialized_is_freed, METH_NOARGS},
5477 {"check_pyobject_forbidden_bytes_is_freed", check_pyobject_forbidden_bytes_is_freed, METH_NOARGS},
5478 {"check_pyobject_freed_is_freed", check_pyobject_freed_is_freed, METH_NOARGS},
Victor Stinnerc4aec362016-03-14 22:26:53 +01005479 {"pyobject_malloc_without_gil", pyobject_malloc_without_gil, METH_NOARGS},
Victor Stinner10b73e12016-03-22 13:39:05 +01005480 {"tracemalloc_track", tracemalloc_track, METH_VARARGS},
5481 {"tracemalloc_untrack", tracemalloc_untrack, METH_VARARGS},
5482 {"tracemalloc_get_traceback", tracemalloc_get_traceback, METH_VARARGS},
Victor Stinner3b6a6b42016-09-08 12:51:24 -07005483 {"dict_get_version", dict_get_version, METH_VARARGS},
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07005484 {"raise_SIGINT_then_send_None", raise_SIGINT_then_send_None, METH_VARARGS},
Victor Stinner3b5cf852017-06-09 16:48:45 +02005485 {"pyobject_fastcall", test_pyobject_fastcall, METH_VARARGS},
5486 {"pyobject_fastcalldict", test_pyobject_fastcalldict, METH_VARARGS},
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005487 {"pyobject_vectorcall", test_pyobject_vectorcall, METH_VARARGS},
5488 {"pyvectorcall_call", test_pyvectorcall_call, METH_VARARGS},
Victor Stinner64fa4492017-07-10 14:37:49 +02005489 {"stack_pointer", stack_pointer, METH_NOARGS},
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02005490#ifdef W_STOPCODE
5491 {"W_STOPCODE", py_w_stopcode, METH_VARARGS},
5492#endif
Oren Milman0ccc0f62017-10-08 11:17:46 +03005493 {"get_mapping_keys", get_mapping_keys, METH_O},
5494 {"get_mapping_values", get_mapping_values, METH_O},
5495 {"get_mapping_items", get_mapping_items, METH_O},
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09005496 {"test_pythread_tss_key_state", test_pythread_tss_key_state, METH_VARARGS},
Yury Selivanovf23746a2018-01-22 19:11:18 -05005497 {"hamt", new_hamt, METH_NOARGS},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02005498 {"bad_get", (PyCFunction)(void(*)(void))bad_get, METH_FASTCALL},
Victor Stinner3d4226a2018-08-29 22:21:32 +02005499 {"EncodeLocaleEx", encode_locale_ex, METH_VARARGS},
5500 {"DecodeLocaleEx", decode_locale_ex, METH_VARARGS},
Victor Stinner18618e652018-10-25 17:28:11 +02005501#ifdef Py_REF_DEBUG
5502 {"negative_refcount", negative_refcount, METH_NOARGS},
5503#endif
Victor Stinneref9d9b62019-05-22 11:28:22 +02005504 {"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
Sergey Fedoseev92709a22019-09-09 21:28:34 +05005505 {"sequence_getitem", sequence_getitem, METH_VARARGS},
Petr Viktorinf9583772019-09-10 12:21:09 +01005506 {"meth_varargs", meth_varargs, METH_VARARGS},
5507 {"meth_varargs_keywords", (PyCFunction)(void(*)(void))meth_varargs_keywords, METH_VARARGS|METH_KEYWORDS},
5508 {"meth_o", meth_o, METH_O},
5509 {"meth_noargs", meth_noargs, METH_NOARGS},
5510 {"meth_fastcall", (PyCFunction)(void(*)(void))meth_fastcall, METH_FASTCALL},
5511 {"meth_fastcall_keywords", (PyCFunction)(void(*)(void))meth_fastcall_keywords, METH_FASTCALL|METH_KEYWORDS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 {NULL, NULL} /* sentinel */
Tim Peters9ea17ac2001-02-02 05:57:15 +00005513};
5514
Thomas Hellera4ea6032003-04-17 18:55:45 +00005515#define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
5516
Thomas Wouters89f507f2006-12-13 04:49:30 +00005517typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 char bool_member;
5519 char byte_member;
5520 unsigned char ubyte_member;
5521 short short_member;
5522 unsigned short ushort_member;
5523 int int_member;
5524 unsigned int uint_member;
5525 long long_member;
5526 unsigned long ulong_member;
5527 Py_ssize_t pyssizet_member;
5528 float float_member;
5529 double double_member;
5530 char inplace_member[6];
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005531 long long longlong_member;
5532 unsigned long long ulonglong_member;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005533} all_structmembers;
5534
5535typedef struct {
5536 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 all_structmembers structmembers;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005538} test_structmembers;
5539
5540static struct PyMemberDef test_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
5542 {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
5543 {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
5544 {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
5545 {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
5546 {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
5547 {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
5548 {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
5549 {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
5550 {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
5551 {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
5552 {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
5553 {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
5555 {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 {NULL}
Thomas Wouters89f507f2006-12-13 04:49:30 +00005557};
5558
5559
Christian Heimes1af737c2008-01-23 08:24:23 +00005560static PyObject *
5561test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
5562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 static char *keywords[] = {
5564 "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
5565 "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
5566 "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 "T_LONGLONG", "T_ULONGLONG",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 NULL};
Benjamin Petersoned4aa832016-09-05 17:44:18 -07005569 static const char fmt[] = "|bbBhHiIlknfds#LK";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 test_structmembers *ob;
5571 const char *s = NULL;
5572 Py_ssize_t string_len = 0;
5573 ob = PyObject_New(test_structmembers, type);
5574 if (ob == NULL)
5575 return NULL;
5576 memset(&ob->structmembers, 0, sizeof(all_structmembers));
5577 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
5578 &ob->structmembers.bool_member,
5579 &ob->structmembers.byte_member,
5580 &ob->structmembers.ubyte_member,
5581 &ob->structmembers.short_member,
5582 &ob->structmembers.ushort_member,
5583 &ob->structmembers.int_member,
5584 &ob->structmembers.uint_member,
5585 &ob->structmembers.long_member,
5586 &ob->structmembers.ulong_member,
5587 &ob->structmembers.pyssizet_member,
5588 &ob->structmembers.float_member,
5589 &ob->structmembers.double_member,
5590 &s, &string_len
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 , &ob->structmembers.longlong_member,
5592 &ob->structmembers.ulonglong_member
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 )) {
5594 Py_DECREF(ob);
5595 return NULL;
5596 }
5597 if (s != NULL) {
5598 if (string_len > 5) {
5599 Py_DECREF(ob);
5600 PyErr_SetString(PyExc_ValueError, "string too long");
5601 return NULL;
5602 }
5603 strcpy(ob->structmembers.inplace_member, s);
5604 }
5605 else {
5606 strcpy(ob->structmembers.inplace_member, "");
5607 }
5608 return (PyObject *)ob;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005609}
5610
Christian Heimes1af737c2008-01-23 08:24:23 +00005611static void
5612test_structmembers_free(PyObject *ob)
5613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 PyObject_FREE(ob);
Thomas Wouters89f507f2006-12-13 04:49:30 +00005615}
5616
5617static PyTypeObject test_structmembersType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005618 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 "test_structmembersType",
5620 sizeof(test_structmembers), /* tp_basicsize */
5621 0, /* tp_itemsize */
5622 test_structmembers_free, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005623 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 0, /* tp_getattr */
5625 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005626 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 0, /* tp_repr */
5628 0, /* tp_as_number */
5629 0, /* tp_as_sequence */
5630 0, /* tp_as_mapping */
5631 0, /* tp_hash */
5632 0, /* tp_call */
5633 0, /* tp_str */
5634 PyObject_GenericGetAttr, /* tp_getattro */
5635 PyObject_GenericSetAttr, /* tp_setattro */
5636 0, /* tp_as_buffer */
5637 0, /* tp_flags */
5638 "Type containing all structmember types",
5639 0, /* traverseproc tp_traverse */
5640 0, /* tp_clear */
5641 0, /* tp_richcompare */
5642 0, /* tp_weaklistoffset */
5643 0, /* tp_iter */
5644 0, /* tp_iternext */
5645 0, /* tp_methods */
5646 test_members, /* tp_members */
5647 0,
5648 0,
5649 0,
5650 0,
5651 0,
5652 0,
5653 0,
5654 0,
5655 test_structmembers_new, /* tp_new */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005656};
5657
5658
Benjamin Petersond51374e2014-04-09 23:55:56 -04005659typedef struct {
5660 PyObject_HEAD
5661} matmulObject;
5662
5663static PyObject *
5664matmulType_matmul(PyObject *self, PyObject *other)
5665{
5666 return Py_BuildValue("(sOO)", "matmul", self, other);
5667}
5668
5669static PyObject *
5670matmulType_imatmul(PyObject *self, PyObject *other)
5671{
5672 return Py_BuildValue("(sOO)", "imatmul", self, other);
5673}
5674
5675static void
5676matmulType_dealloc(PyObject *self)
5677{
Zachary Ware420dc562014-04-23 13:51:27 -05005678 Py_TYPE(self)->tp_free(self);
Benjamin Petersond51374e2014-04-09 23:55:56 -04005679}
5680
5681static PyNumberMethods matmulType_as_number = {
5682 0, /* nb_add */
5683 0, /* nb_subtract */
5684 0, /* nb_multiply */
5685 0, /* nb_remainde r*/
5686 0, /* nb_divmod */
5687 0, /* nb_power */
5688 0, /* nb_negative */
5689 0, /* tp_positive */
5690 0, /* tp_absolute */
5691 0, /* tp_bool */
5692 0, /* nb_invert */
5693 0, /* nb_lshift */
5694 0, /* nb_rshift */
5695 0, /* nb_and */
5696 0, /* nb_xor */
5697 0, /* nb_or */
5698 0, /* nb_int */
5699 0, /* nb_reserved */
5700 0, /* nb_float */
5701 0, /* nb_inplace_add */
5702 0, /* nb_inplace_subtract */
5703 0, /* nb_inplace_multiply */
5704 0, /* nb_inplace_remainder */
5705 0, /* nb_inplace_power */
5706 0, /* nb_inplace_lshift */
5707 0, /* nb_inplace_rshift */
5708 0, /* nb_inplace_and */
5709 0, /* nb_inplace_xor */
5710 0, /* nb_inplace_or */
5711 0, /* nb_floor_divide */
5712 0, /* nb_true_divide */
5713 0, /* nb_inplace_floor_divide */
5714 0, /* nb_inplace_true_divide */
5715 0, /* nb_index */
5716 matmulType_matmul, /* nb_matrix_multiply */
5717 matmulType_imatmul /* nb_matrix_inplace_multiply */
5718};
5719
5720static PyTypeObject matmulType = {
5721 PyVarObject_HEAD_INIT(NULL, 0)
5722 "matmulType",
5723 sizeof(matmulObject), /* tp_basicsize */
5724 0, /* tp_itemsize */
5725 matmulType_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005726 0, /* tp_vectorcall_offset */
Benjamin Petersond51374e2014-04-09 23:55:56 -04005727 0, /* tp_getattr */
5728 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005729 0, /* tp_as_async */
Benjamin Petersond51374e2014-04-09 23:55:56 -04005730 0, /* tp_repr */
5731 &matmulType_as_number, /* tp_as_number */
5732 0, /* tp_as_sequence */
5733 0, /* tp_as_mapping */
5734 0, /* tp_hash */
5735 0, /* tp_call */
5736 0, /* tp_str */
5737 PyObject_GenericGetAttr, /* tp_getattro */
5738 PyObject_GenericSetAttr, /* tp_setattro */
5739 0, /* tp_as_buffer */
5740 0, /* tp_flags */
5741 "C level type with matrix operations defined",
5742 0, /* traverseproc tp_traverse */
5743 0, /* tp_clear */
5744 0, /* tp_richcompare */
5745 0, /* tp_weaklistoffset */
5746 0, /* tp_iter */
5747 0, /* tp_iternext */
5748 0, /* tp_methods */
5749 0, /* tp_members */
5750 0,
5751 0,
5752 0,
5753 0,
5754 0,
5755 0,
5756 0,
5757 0,
5758 PyType_GenericNew, /* tp_new */
5759 PyObject_Del, /* tp_free */
5760};
5761
Zackery Spytzc7f803b2019-05-31 03:46:36 -06005762typedef struct {
5763 PyObject_HEAD
5764} ipowObject;
5765
5766static PyObject *
5767ipowType_ipow(PyObject *self, PyObject *other, PyObject *mod)
5768{
5769 return Py_BuildValue("OO", other, mod);
5770}
5771
5772static PyNumberMethods ipowType_as_number = {
5773 .nb_inplace_power = ipowType_ipow
5774};
5775
5776static PyTypeObject ipowType = {
5777 PyVarObject_HEAD_INIT(NULL, 0)
5778 .tp_name = "ipowType",
5779 .tp_basicsize = sizeof(ipowObject),
5780 .tp_as_number = &ipowType_as_number,
5781 .tp_new = PyType_GenericNew
5782};
Martin v. Löwis1a214512008-06-11 05:26:20 +00005783
Yury Selivanov75445082015-05-11 22:57:16 -04005784typedef struct {
5785 PyObject_HEAD
5786 PyObject *ao_iterator;
5787} awaitObject;
5788
5789
5790static PyObject *
5791awaitObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5792{
5793 PyObject *v;
5794 awaitObject *ao;
5795
5796 if (!PyArg_UnpackTuple(args, "awaitObject", 1, 1, &v))
5797 return NULL;
5798
5799 ao = (awaitObject *)type->tp_alloc(type, 0);
5800 if (ao == NULL) {
5801 return NULL;
5802 }
5803
5804 Py_INCREF(v);
5805 ao->ao_iterator = v;
5806
5807 return (PyObject *)ao;
5808}
5809
5810
5811static void
5812awaitObject_dealloc(awaitObject *ao)
5813{
5814 Py_CLEAR(ao->ao_iterator);
5815 Py_TYPE(ao)->tp_free(ao);
5816}
5817
5818
5819static PyObject *
5820awaitObject_await(awaitObject *ao)
5821{
5822 Py_INCREF(ao->ao_iterator);
5823 return ao->ao_iterator;
5824}
5825
5826static PyAsyncMethods awaitType_as_async = {
Yury Selivanov6ef05902015-05-28 11:21:31 -04005827 (unaryfunc)awaitObject_await, /* am_await */
Yury Selivanov75445082015-05-11 22:57:16 -04005828 0, /* am_aiter */
5829 0 /* am_anext */
5830};
5831
5832
5833static PyTypeObject awaitType = {
5834 PyVarObject_HEAD_INIT(NULL, 0)
5835 "awaitType",
5836 sizeof(awaitObject), /* tp_basicsize */
5837 0, /* tp_itemsize */
5838 (destructor)awaitObject_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005839 0, /* tp_vectorcall_offset */
Yury Selivanov75445082015-05-11 22:57:16 -04005840 0, /* tp_getattr */
5841 0, /* tp_setattr */
5842 &awaitType_as_async, /* tp_as_async */
5843 0, /* tp_repr */
5844 0, /* tp_as_number */
5845 0, /* tp_as_sequence */
5846 0, /* tp_as_mapping */
5847 0, /* tp_hash */
5848 0, /* tp_call */
5849 0, /* tp_str */
5850 PyObject_GenericGetAttr, /* tp_getattro */
5851 PyObject_GenericSetAttr, /* tp_setattro */
5852 0, /* tp_as_buffer */
5853 0, /* tp_flags */
5854 "C level type with tp_as_async",
5855 0, /* traverseproc tp_traverse */
5856 0, /* tp_clear */
5857 0, /* tp_richcompare */
5858 0, /* tp_weaklistoffset */
5859 0, /* tp_iter */
5860 0, /* tp_iternext */
5861 0, /* tp_methods */
5862 0, /* tp_members */
5863 0,
5864 0,
5865 0,
5866 0,
5867 0,
5868 0,
5869 0,
5870 0,
5871 awaitObject_new, /* tp_new */
5872 PyObject_Del, /* tp_free */
5873};
5874
5875
xdegaye56d1f5c2017-10-26 15:09:06 +02005876static int recurse_infinitely_error_init(PyObject *, PyObject *, PyObject *);
5877
5878static PyTypeObject PyRecursingInfinitelyError_Type = {
5879 PyVarObject_HEAD_INIT(NULL, 0)
5880 "RecursingInfinitelyError", /* tp_name */
5881 sizeof(PyBaseExceptionObject), /* tp_basicsize */
5882 0, /* tp_itemsize */
5883 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005884 0, /* tp_vectorcall_offset */
xdegaye56d1f5c2017-10-26 15:09:06 +02005885 0, /* tp_getattr */
5886 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005887 0, /* tp_as_async */
xdegaye56d1f5c2017-10-26 15:09:06 +02005888 0, /* tp_repr */
5889 0, /* tp_as_number */
5890 0, /* tp_as_sequence */
5891 0, /* tp_as_mapping */
5892 0, /* tp_hash */
5893 0, /* tp_call */
5894 0, /* tp_str */
5895 0, /* tp_getattro */
5896 0, /* tp_setattro */
5897 0, /* tp_as_buffer */
5898 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5899 "Instantiating this exception starts infinite recursion.", /* tp_doc */
5900 0, /* tp_traverse */
5901 0, /* tp_clear */
5902 0, /* tp_richcompare */
5903 0, /* tp_weaklistoffset */
5904 0, /* tp_iter */
5905 0, /* tp_iternext */
5906 0, /* tp_methods */
5907 0, /* tp_members */
5908 0, /* tp_getset */
5909 0, /* tp_base */
5910 0, /* tp_dict */
5911 0, /* tp_descr_get */
5912 0, /* tp_descr_set */
5913 0, /* tp_dictoffset */
5914 (initproc)recurse_infinitely_error_init, /* tp_init */
5915 0, /* tp_alloc */
5916 0, /* tp_new */
5917};
5918
5919static int
5920recurse_infinitely_error_init(PyObject *self, PyObject *args, PyObject *kwds)
5921{
5922 PyObject *type = (PyObject *)&PyRecursingInfinitelyError_Type;
5923
5924 /* Instantiating this exception starts infinite recursion. */
5925 Py_INCREF(type);
5926 PyErr_SetObject(type, NULL);
5927 return -1;
5928}
5929
5930
Jeroen Demeyer351c6742019-05-10 19:21:11 +02005931/* Test bpo-35983: create a subclass of "list" which checks that instances
5932 * are not deallocated twice */
5933
5934typedef struct {
5935 PyListObject list;
5936 int deallocated;
5937} MyListObject;
5938
5939static PyObject *
5940MyList_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5941{
5942 PyObject* op = PyList_Type.tp_new(type, args, kwds);
5943 ((MyListObject*)op)->deallocated = 0;
5944 return op;
5945}
5946
5947void
5948MyList_dealloc(MyListObject* op)
5949{
5950 if (op->deallocated) {
5951 /* We cannot raise exceptions here but we still want the testsuite
5952 * to fail when we hit this */
5953 Py_FatalError("MyList instance deallocated twice");
5954 }
5955 op->deallocated = 1;
5956 PyList_Type.tp_dealloc((PyObject *)op);
5957}
5958
5959static PyTypeObject MyList_Type = {
5960 PyVarObject_HEAD_INIT(NULL, 0)
5961 "MyList",
5962 sizeof(MyListObject),
5963 0,
5964 (destructor)MyList_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005965 0, /* tp_vectorcall_offset */
Jeroen Demeyer351c6742019-05-10 19:21:11 +02005966 0, /* tp_getattr */
5967 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005968 0, /* tp_as_async */
Jeroen Demeyer351c6742019-05-10 19:21:11 +02005969 0, /* tp_repr */
5970 0, /* tp_as_number */
5971 0, /* tp_as_sequence */
5972 0, /* tp_as_mapping */
5973 0, /* tp_hash */
5974 0, /* tp_call */
5975 0, /* tp_str */
5976 0, /* tp_getattro */
5977 0, /* tp_setattro */
5978 0, /* tp_as_buffer */
5979 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5980 0, /* tp_doc */
5981 0, /* tp_traverse */
5982 0, /* tp_clear */
5983 0, /* tp_richcompare */
5984 0, /* tp_weaklistoffset */
5985 0, /* tp_iter */
5986 0, /* tp_iternext */
5987 0, /* tp_methods */
5988 0, /* tp_members */
5989 0, /* tp_getset */
5990 0, /* &PyList_Type */ /* tp_base */
5991 0, /* tp_dict */
5992 0, /* tp_descr_get */
5993 0, /* tp_descr_set */
5994 0, /* tp_dictoffset */
5995 0, /* tp_init */
5996 0, /* tp_alloc */
5997 MyList_new, /* tp_new */
5998};
5999
6000
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006001/* Test PEP 560 */
6002
6003typedef struct {
6004 PyObject_HEAD
6005 PyObject *item;
6006} PyGenericAliasObject;
6007
6008static void
6009generic_alias_dealloc(PyGenericAliasObject *self)
6010{
6011 Py_CLEAR(self->item);
Victor Stinnere8600892018-01-17 23:08:18 +01006012 Py_TYPE(self)->tp_free((PyObject *)self);
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006013}
6014
6015static PyObject *
6016generic_alias_mro_entries(PyGenericAliasObject *self, PyObject *bases)
6017{
6018 return PyTuple_Pack(1, self->item);
6019}
6020
6021static PyMethodDef generic_alias_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006022 {"__mro_entries__", (PyCFunction)(void(*)(void))generic_alias_mro_entries, METH_O, NULL},
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006023 {NULL} /* sentinel */
6024};
6025
Benjamin Peterson97ae32c2018-07-03 22:39:09 -07006026static PyTypeObject GenericAlias_Type = {
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006027 PyVarObject_HEAD_INIT(NULL, 0)
6028 "GenericAlias",
6029 sizeof(PyGenericAliasObject),
6030 0,
6031 .tp_dealloc = (destructor)generic_alias_dealloc,
6032 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
6033 .tp_methods = generic_alias_methods,
6034};
6035
6036static PyObject *
6037generic_alias_new(PyObject *item)
6038{
6039 PyGenericAliasObject *o = PyObject_New(PyGenericAliasObject, &GenericAlias_Type);
6040 if (o == NULL) {
6041 return NULL;
6042 }
6043 Py_INCREF(item);
6044 o->item = item;
6045 return (PyObject*) o;
6046}
6047
6048typedef struct {
6049 PyObject_HEAD
6050} PyGenericObject;
6051
6052static PyObject *
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02006053generic_class_getitem(PyObject *type, PyObject *item)
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006054{
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006055 return generic_alias_new(item);
6056}
6057
6058static PyMethodDef generic_methods[] = {
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02006059 {"__class_getitem__", generic_class_getitem, METH_O|METH_CLASS, NULL},
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006060 {NULL} /* sentinel */
6061};
6062
Benjamin Peterson97ae32c2018-07-03 22:39:09 -07006063static PyTypeObject Generic_Type = {
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006064 PyVarObject_HEAD_INIT(NULL, 0)
6065 "Generic",
6066 sizeof(PyGenericObject),
6067 0,
6068 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
6069 .tp_methods = generic_methods,
6070};
6071
6072
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006073/* Test PEP 590 */
6074
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006075typedef struct {
6076 PyObject_HEAD
6077 vectorcallfunc vectorcall;
6078} MethodDescriptorObject;
6079
6080static PyObject *
6081MethodDescriptor_vectorcall(PyObject *callable, PyObject *const *args,
6082 size_t nargsf, PyObject *kwnames)
6083{
6084 /* True if using the vectorcall function in MethodDescriptorObject
6085 * but False for MethodDescriptor2Object */
6086 MethodDescriptorObject *md = (MethodDescriptorObject *)callable;
6087 return PyBool_FromLong(md->vectorcall != NULL);
6088}
6089
6090static PyObject *
6091MethodDescriptor_new(PyTypeObject* type, PyObject* args, PyObject *kw)
6092{
Petr Viktorine584cbf2019-06-03 01:08:14 +02006093 MethodDescriptorObject *op = (MethodDescriptorObject *)type->tp_alloc(type, 0);
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006094 op->vectorcall = MethodDescriptor_vectorcall;
6095 return (PyObject *)op;
6096}
6097
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006098static PyObject *
6099func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
6100{
6101 if (obj == Py_None || obj == NULL) {
6102 Py_INCREF(func);
6103 return func;
6104 }
6105 return PyMethod_New(func, obj);
6106}
6107
6108static PyObject *
6109nop_descr_get(PyObject *func, PyObject *obj, PyObject *type)
6110{
6111 Py_INCREF(func);
6112 return func;
6113}
6114
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006115static PyObject *
6116call_return_args(PyObject *self, PyObject *args, PyObject *kwargs)
6117{
6118 Py_INCREF(args);
6119 return args;
6120}
6121
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006122static PyTypeObject MethodDescriptorBase_Type = {
6123 PyVarObject_HEAD_INIT(NULL, 0)
6124 "MethodDescriptorBase",
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006125 sizeof(MethodDescriptorObject),
6126 .tp_new = MethodDescriptor_new,
6127 .tp_call = PyVectorcall_Call,
6128 .tp_vectorcall_offset = offsetof(MethodDescriptorObject, vectorcall),
6129 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
6130 Py_TPFLAGS_METHOD_DESCRIPTOR | _Py_TPFLAGS_HAVE_VECTORCALL,
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006131 .tp_descr_get = func_descr_get,
6132};
6133
6134static PyTypeObject MethodDescriptorDerived_Type = {
6135 PyVarObject_HEAD_INIT(NULL, 0)
6136 "MethodDescriptorDerived",
6137 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
6138};
6139
6140static PyTypeObject MethodDescriptorNopGet_Type = {
6141 PyVarObject_HEAD_INIT(NULL, 0)
6142 "MethodDescriptorNopGet",
6143 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006144 .tp_call = call_return_args,
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006145 .tp_descr_get = nop_descr_get,
6146};
6147
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006148typedef struct {
6149 MethodDescriptorObject base;
6150 vectorcallfunc vectorcall;
6151} MethodDescriptor2Object;
6152
6153static PyObject *
6154MethodDescriptor2_new(PyTypeObject* type, PyObject* args, PyObject *kw)
6155{
6156 MethodDescriptor2Object *op = PyObject_New(MethodDescriptor2Object, type);
6157 op->base.vectorcall = NULL;
6158 op->vectorcall = MethodDescriptor_vectorcall;
6159 return (PyObject *)op;
6160}
6161
6162static PyTypeObject MethodDescriptor2_Type = {
6163 PyVarObject_HEAD_INIT(NULL, 0)
6164 "MethodDescriptor2",
6165 sizeof(MethodDescriptor2Object),
6166 .tp_new = MethodDescriptor2_new,
6167 .tp_call = PyVectorcall_Call,
6168 .tp_vectorcall_offset = offsetof(MethodDescriptor2Object, vectorcall),
6169 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | _Py_TPFLAGS_HAVE_VECTORCALL,
6170};
6171
Petr Viktorinf9583772019-09-10 12:21:09 +01006172static PyMethodDef meth_instance_methods[] = {
6173 {"meth_varargs", meth_varargs, METH_VARARGS},
6174 {"meth_varargs_keywords", (PyCFunction)(void(*)(void))meth_varargs_keywords, METH_VARARGS|METH_KEYWORDS},
6175 {"meth_o", meth_o, METH_O},
6176 {"meth_noargs", meth_noargs, METH_NOARGS},
6177 {"meth_fastcall", (PyCFunction)(void(*)(void))meth_fastcall, METH_FASTCALL},
6178 {"meth_fastcall_keywords", (PyCFunction)(void(*)(void))meth_fastcall_keywords, METH_FASTCALL|METH_KEYWORDS},
6179 {NULL, NULL} /* sentinel */
6180};
6181
6182
6183static PyTypeObject MethInstance_Type = {
6184 PyVarObject_HEAD_INIT(NULL, 0)
6185 "MethInstance",
6186 sizeof(PyObject),
6187 .tp_new = PyType_GenericNew,
6188 .tp_flags = Py_TPFLAGS_DEFAULT,
6189 .tp_methods = meth_instance_methods,
6190 .tp_doc = PyDoc_STR(
6191 "Class with normal (instance) methods to test calling conventions"),
6192};
6193
6194static PyMethodDef meth_class_methods[] = {
6195 {"meth_varargs", meth_varargs, METH_VARARGS|METH_CLASS},
6196 {"meth_varargs_keywords", (PyCFunction)(void(*)(void))meth_varargs_keywords, METH_VARARGS|METH_KEYWORDS|METH_CLASS},
6197 {"meth_o", meth_o, METH_O|METH_CLASS},
6198 {"meth_noargs", meth_noargs, METH_NOARGS|METH_CLASS},
6199 {"meth_fastcall", (PyCFunction)(void(*)(void))meth_fastcall, METH_FASTCALL|METH_CLASS},
6200 {"meth_fastcall_keywords", (PyCFunction)(void(*)(void))meth_fastcall_keywords, METH_FASTCALL|METH_KEYWORDS|METH_CLASS},
6201 {NULL, NULL} /* sentinel */
6202};
6203
6204
6205static PyTypeObject MethClass_Type = {
6206 PyVarObject_HEAD_INIT(NULL, 0)
6207 "MethClass",
6208 sizeof(PyObject),
6209 .tp_new = PyType_GenericNew,
6210 .tp_flags = Py_TPFLAGS_DEFAULT,
6211 .tp_methods = meth_class_methods,
6212 .tp_doc = PyDoc_STR(
6213 "Class with class methods to test calling conventions"),
6214};
6215
6216static PyMethodDef meth_static_methods[] = {
6217 {"meth_varargs", meth_varargs, METH_VARARGS|METH_STATIC},
6218 {"meth_varargs_keywords", (PyCFunction)(void(*)(void))meth_varargs_keywords, METH_VARARGS|METH_KEYWORDS|METH_STATIC},
6219 {"meth_o", meth_o, METH_O|METH_STATIC},
6220 {"meth_noargs", meth_noargs, METH_NOARGS|METH_STATIC},
6221 {"meth_fastcall", (PyCFunction)(void(*)(void))meth_fastcall, METH_FASTCALL|METH_STATIC},
6222 {"meth_fastcall_keywords", (PyCFunction)(void(*)(void))meth_fastcall_keywords, METH_FASTCALL|METH_KEYWORDS|METH_STATIC},
6223 {NULL, NULL} /* sentinel */
6224};
6225
6226
6227static PyTypeObject MethStatic_Type = {
6228 PyVarObject_HEAD_INIT(NULL, 0)
6229 "MethStatic",
6230 sizeof(PyObject),
6231 .tp_new = PyType_GenericNew,
6232 .tp_flags = Py_TPFLAGS_DEFAULT,
6233 .tp_methods = meth_static_methods,
6234 .tp_doc = PyDoc_STR(
6235 "Class with static methods to test calling conventions"),
6236};
6237
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006238
Martin v. Löwis1a214512008-06-11 05:26:20 +00006239static struct PyModuleDef _testcapimodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006240 PyModuleDef_HEAD_INIT,
6241 "_testcapi",
6242 NULL,
6243 -1,
6244 TestMethods,
6245 NULL,
6246 NULL,
6247 NULL,
6248 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00006249};
6250
Nick Coghland5cacbb2015-05-23 22:24:10 +10006251/* Per PEP 489, this module will not be converted to multi-phase initialization
6252 */
6253
Mark Hammond62b1ab12002-07-23 06:31:15 +00006254PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00006255PyInit__testcapi(void)
Tim Peters9ea17ac2001-02-02 05:57:15 +00006256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006257 PyObject *m;
Tim Peters9ea17ac2001-02-02 05:57:15 +00006258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 m = PyModule_Create(&_testcapimodule);
6260 if (m == NULL)
6261 return NULL;
Tim Peters9ea17ac2001-02-02 05:57:15 +00006262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
Hirokazu Yamamoto8ebab5d2008-12-31 06:05:46 +00006264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 Py_TYPE(&test_structmembersType)=&PyType_Type;
6266 Py_INCREF(&test_structmembersType);
6267 /* don't use a name starting with "test", since we don't want
6268 test_capi to automatically call this */
6269 PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
Benjamin Petersond51374e2014-04-09 23:55:56 -04006270 if (PyType_Ready(&matmulType) < 0)
6271 return NULL;
6272 Py_INCREF(&matmulType);
6273 PyModule_AddObject(m, "matmulType", (PyObject *)&matmulType);
Zackery Spytzc7f803b2019-05-31 03:46:36 -06006274 if (PyType_Ready(&ipowType) < 0) {
6275 return NULL;
6276 }
6277 Py_INCREF(&ipowType);
6278 PyModule_AddObject(m, "ipowType", (PyObject *)&ipowType);
Thomas Wouters89f507f2006-12-13 04:49:30 +00006279
Yury Selivanov75445082015-05-11 22:57:16 -04006280 if (PyType_Ready(&awaitType) < 0)
6281 return NULL;
6282 Py_INCREF(&awaitType);
6283 PyModule_AddObject(m, "awaitType", (PyObject *)&awaitType);
6284
Jeroen Demeyer351c6742019-05-10 19:21:11 +02006285 MyList_Type.tp_base = &PyList_Type;
6286 if (PyType_Ready(&MyList_Type) < 0)
6287 return NULL;
6288 Py_INCREF(&MyList_Type);
6289 PyModule_AddObject(m, "MyList", (PyObject *)&MyList_Type);
6290
Jeroen Demeyereb65e242019-05-28 14:42:53 +02006291 if (PyType_Ready(&MethodDescriptorBase_Type) < 0)
6292 return NULL;
6293 Py_INCREF(&MethodDescriptorBase_Type);
6294 PyModule_AddObject(m, "MethodDescriptorBase", (PyObject *)&MethodDescriptorBase_Type);
6295
6296 MethodDescriptorDerived_Type.tp_base = &MethodDescriptorBase_Type;
6297 if (PyType_Ready(&MethodDescriptorDerived_Type) < 0)
6298 return NULL;
6299 Py_INCREF(&MethodDescriptorDerived_Type);
6300 PyModule_AddObject(m, "MethodDescriptorDerived", (PyObject *)&MethodDescriptorDerived_Type);
6301
6302 MethodDescriptorNopGet_Type.tp_base = &MethodDescriptorBase_Type;
6303 if (PyType_Ready(&MethodDescriptorNopGet_Type) < 0)
6304 return NULL;
6305 Py_INCREF(&MethodDescriptorNopGet_Type);
6306 PyModule_AddObject(m, "MethodDescriptorNopGet", (PyObject *)&MethodDescriptorNopGet_Type);
6307
Jeroen Demeyer735e8af2019-05-30 12:43:19 +02006308 MethodDescriptor2_Type.tp_base = &MethodDescriptorBase_Type;
6309 if (PyType_Ready(&MethodDescriptor2_Type) < 0)
6310 return NULL;
6311 Py_INCREF(&MethodDescriptor2_Type);
6312 PyModule_AddObject(m, "MethodDescriptor2", (PyObject *)&MethodDescriptor2_Type);
6313
Serhiy Storchaka45700fb2017-12-16 11:25:56 +02006314 if (PyType_Ready(&GenericAlias_Type) < 0)
6315 return NULL;
6316 Py_INCREF(&GenericAlias_Type);
6317 PyModule_AddObject(m, "GenericAlias", (PyObject *)&GenericAlias_Type);
6318
6319 if (PyType_Ready(&Generic_Type) < 0)
6320 return NULL;
6321 Py_INCREF(&Generic_Type);
6322 PyModule_AddObject(m, "Generic", (PyObject *)&Generic_Type);
6323
Petr Viktorinf9583772019-09-10 12:21:09 +01006324 if (PyType_Ready(&MethInstance_Type) < 0)
6325 return NULL;
6326 Py_INCREF(&MethInstance_Type);
6327 PyModule_AddObject(m, "MethInstance", (PyObject *)&MethInstance_Type);
6328
6329 if (PyType_Ready(&MethClass_Type) < 0)
6330 return NULL;
6331 Py_INCREF(&MethClass_Type);
6332 PyModule_AddObject(m, "MethClass", (PyObject *)&MethClass_Type);
6333
6334 if (PyType_Ready(&MethStatic_Type) < 0)
6335 return NULL;
6336 Py_INCREF(&MethStatic_Type);
6337 PyModule_AddObject(m, "MethStatic", (PyObject *)&MethStatic_Type);
6338
xdegaye56d1f5c2017-10-26 15:09:06 +02006339 PyRecursingInfinitelyError_Type.tp_base = (PyTypeObject *)PyExc_Exception;
6340 if (PyType_Ready(&PyRecursingInfinitelyError_Type) < 0) {
6341 return NULL;
6342 }
6343 Py_INCREF(&PyRecursingInfinitelyError_Type);
6344 PyModule_AddObject(m, "RecursingInfinitelyError",
6345 (PyObject *)&PyRecursingInfinitelyError_Type);
6346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006347 PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
6348 PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
6349 PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
6350 PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
6351 PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
6352 PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
6353 PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
6354 PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
6355 PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
6356 PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
6357 PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
6358 PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
6359 PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
6360 PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
6361 PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
6362 PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
6363 PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
6364 PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
6365 PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
6366 PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
6367 PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
6368 PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head)));
Victor Stinner4237d342015-09-10 10:10:39 +02006369 PyModule_AddObject(m, "SIZEOF_TIME_T", PyLong_FromSsize_t(sizeof(time_t)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006370 Py_INCREF(&PyInstanceMethod_Type);
6371 PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
Thomas Hellera4ea6032003-04-17 18:55:45 +00006372
Larry Hastings2a727912014-01-16 11:32:01 -08006373 PyModule_AddIntConstant(m, "the_number_three", 3);
Victor Stinner5d39e042017-11-29 17:20:38 +01006374#ifdef WITH_PYMALLOC
6375 PyModule_AddObject(m, "WITH_PYMALLOC", Py_True);
6376#else
6377 PyModule_AddObject(m, "WITH_PYMALLOC", Py_False);
6378#endif
Larry Hastings2a727912014-01-16 11:32:01 -08006379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006380 TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
6381 Py_INCREF(TestError);
6382 PyModule_AddObject(m, "error", TestError);
6383 return m;
Tim Peters9ea17ac2001-02-02 05:57:15 +00006384}