Debian Codegraph @

lib_pypy/_testcapimodule.c

raw symbols SCIP
1 /* Copy of Modules/_testcapimodule.c from CPython,
2 * with things that PyPy doesn't support disabled.
3 */
4 /*
5 * C Extension module to test Python interpreter C APIs.
6 *
7 * The 'test_*' functions exported by this module are run as part of the
8 * standard Python regression test, via Lib/test/test_capi.py.
9 */
10
11 /* This module tests the public (Include/ and Include/cpython/) C API.
12 The internal C API must not be used here: use _testinternalcapi for that.
13
14 The Visual Studio projects builds _testcapi with Py_BUILD_CORE_MODULE
15 macro defined, but only the public C API must be tested here. */
16
17 #undef Py_BUILD_CORE_MODULE
18 #undef Py_BUILD_CORE_BUILTIN
19 #define NEEDS_PY_IDENTIFIER
20
21 /* Always enable assertions */
22 #undef NDEBUG
23
24 #define PY_SSIZE_T_CLEAN
25
26 #include "Python.h"
27 #include "datetime.h" // PyDateTimeAPI
28 #include "frameobject.h" // PyFrame_New
29 #include "marshal.h" // PyMarshal_WriteLongToFile
30 #include "structmember.h" // PyMemberDef
31 #include <float.h> // FLT_MAX
32 #include <signal.h>
33
34 #ifdef MS_WINDOWS
35 # include <winsock2.h> // struct timeval
36 #endif
37
38 #ifdef HAVE_SYS_WAIT_H
39 #include <sys/wait.h> // W_STOPCODE
40 #endif
41
42 #ifdef Py_BUILD_CORE
43 # error "_testcapi must test the public Python C API, not CPython internal C API"
44 #endif
45
46 #ifdef bool
47 # error "The public headers should not include <stdbool.h>, see bpo-46748"
48 #endif
49
50 #define NULLABLE(x) do { if (x == Py_None) x = NULL; } while (0);
51
52 #define RETURN_INT(value) do { \
53 int _ret = (value); \
54 if (_ret == -1) { \
55 return NULL; \
56 } \
57 return PyLong_FromLong(_ret); \
58 } while (0)
59
60 // Forward declarations
61 static struct PyModuleDef _testcapimodule;
62 static PyType_Spec HeapTypeNameType_Spec;
63 static PyObject *TestError; /* set to exception object in init */
64
65
66 /* Raise TestError with test_name + ": " + msg, and return NULL. */
67
68 static PyObject *
69 raiseTestError(const char* test_name, const char* msg)
70 {
71 PyErr_Format(TestError, "%s: %s", test_name, msg);
72 return NULL;
73 }
74
75 /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
76
77 The ones derived from autoconf on the UNIX-like OSes can be relied
78 upon (in the absence of sloppy cross-compiling), but the Windows
79 platforms have these hardcoded. Better safe than sorry.
80 */
81 static PyObject*
82 sizeof_error(const char* fatname, const char* typname,
83 int expected, int got)
84 {
85 PyErr_Format(TestError,
86 "%s #define == %d but sizeof(%s) == %d",
87 fatname, expected, typname, got);
88 return (PyObject*)NULL;
89 }
90
91 static PyObject*
92 test_config(PyObject *self, PyObject *Py_UNUSED(ignored))
93 {
94 #define CHECK_SIZEOF(FATNAME, TYPE) \
95 if (FATNAME != sizeof(TYPE)) \
96 return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
97
98 CHECK_SIZEOF(SIZEOF_SHORT, short);
99 CHECK_SIZEOF(SIZEOF_INT, int);
100 CHECK_SIZEOF(SIZEOF_LONG, long);
101 CHECK_SIZEOF(SIZEOF_VOID_P, void*);
102 CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
103 CHECK_SIZEOF(SIZEOF_LONG_LONG, long long);
104
105 #undef CHECK_SIZEOF
106
107 Py_RETURN_NONE;
108 }
109
110 static PyObject*
111 test_sizeof_c_types(PyObject *self, PyObject *Py_UNUSED(ignored))
112 {
113 #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
114 #pragma GCC diagnostic push
115 #pragma GCC diagnostic ignored "-Wtype-limits"
116 #endif
117 #define CHECK_SIZEOF(TYPE, EXPECTED) \
118 if (EXPECTED != sizeof(TYPE)) { \
119 PyErr_Format(TestError, \
120 "sizeof(%s) = %u instead of %u", \
121 #TYPE, sizeof(TYPE), EXPECTED); \
122 return (PyObject*)NULL; \
123 }
124 #define IS_SIGNED(TYPE) (((TYPE)-1) < (TYPE)0)
125 #define CHECK_SIGNNESS(TYPE, SIGNED) \
126 if (IS_SIGNED(TYPE) != SIGNED) { \
127 PyErr_Format(TestError, \
128 "%s signness is, instead of %i", \
129 #TYPE, IS_SIGNED(TYPE), SIGNED); \
130 return (PyObject*)NULL; \
131 }
132
133 /* integer types */
134 CHECK_SIZEOF(Py_UCS1, 1);
135 CHECK_SIZEOF(Py_UCS2, 2);
136 CHECK_SIZEOF(Py_UCS4, 4);
137 CHECK_SIGNNESS(Py_UCS1, 0);
138 CHECK_SIGNNESS(Py_UCS2, 0);
139 CHECK_SIGNNESS(Py_UCS4, 0);
140 CHECK_SIZEOF(int32_t, 4);
141 CHECK_SIGNNESS(int32_t, 1);
142 CHECK_SIZEOF(uint32_t, 4);
143 CHECK_SIGNNESS(uint32_t, 0);
144 CHECK_SIZEOF(int64_t, 8);
145 CHECK_SIGNNESS(int64_t, 1);
146 CHECK_SIZEOF(uint64_t, 8);
147 CHECK_SIGNNESS(uint64_t, 0);
148
149 /* pointer/size types */
150 CHECK_SIZEOF(size_t, sizeof(void *));
151 CHECK_SIGNNESS(size_t, 0);
152 CHECK_SIZEOF(Py_ssize_t, sizeof(void *));
153 CHECK_SIGNNESS(Py_ssize_t, 1);
154
155 CHECK_SIZEOF(uintptr_t, sizeof(void *));
156 CHECK_SIGNNESS(uintptr_t, 0);
157 CHECK_SIZEOF(intptr_t, sizeof(void *));
158 CHECK_SIGNNESS(intptr_t, 1);
159
160 Py_RETURN_NONE;
161
162 #undef IS_SIGNED
163 #undef CHECK_SIGNESS
164 #undef CHECK_SIZEOF
165 #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
166 #pragma GCC diagnostic pop
167 #endif
168 }
169
170 static PyObject*
171 test_gc_control(PyObject *self, PyObject *Py_UNUSED(ignored))
172 {
173 int orig_enabled = PyGC_IsEnabled();
174 const char* msg = "ok";
175 int old_state;
176
177 old_state = PyGC_Enable();
178 msg = "Enable(1)";
179 if (old_state != orig_enabled) {
180 goto failed;
181 }
182 msg = "IsEnabled(1)";
183 if (!PyGC_IsEnabled()) {
184 goto failed;
185 }
186
187 old_state = PyGC_Disable();
188 msg = "disable(2)";
189 if (!old_state) {
190 goto failed;
191 }
192 msg = "IsEnabled(2)";
193 if (PyGC_IsEnabled()) {
194 goto failed;
195 }
196
197 old_state = PyGC_Enable();
198 msg = "enable(3)";
199 if (old_state) {
200 goto failed;
201 }
202 msg = "IsEnabled(3)";
203 if (!PyGC_IsEnabled()) {
204 goto failed;
205 }
206
207 if (!orig_enabled) {
208 old_state = PyGC_Disable();
209 msg = "disable(4)";
210 if (old_state) {
211 goto failed;
212 }
213 msg = "IsEnabled(4)";
214 if (PyGC_IsEnabled()) {
215 goto failed;
216 }
217 }
218
219 Py_RETURN_NONE;
220
221 failed:
222 /* Try to clean up if we can. */
223 if (orig_enabled) {
224 PyGC_Enable();
225 } else {
226 PyGC_Disable();
227 }
228 PyErr_Format(TestError, "GC control failed in %s", msg);
229 return NULL;
230 }
231
232 static PyObject*
233 test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored))
234 {
235 PyObject* list;
236 int i;
237
238 /* SF bug 132008: PyList_Reverse segfaults */
239 #define NLIST 30
240 list = PyList_New(NLIST);
241 if (list == (PyObject*)NULL)
242 return (PyObject*)NULL;
243 /* list = range(NLIST) */
244 for (i = 0; i < NLIST; ++i) {
245 PyObject* anint = PyLong_FromLong(i);
246 if (anint == (PyObject*)NULL) {
247 Py_DECREF(list);
248 return (PyObject*)NULL;
249 }
250 PyList_SET_ITEM(list, i, anint);
251 }
252 /* list.reverse(), via PyList_Reverse() */
253 i = PyList_Reverse(list); /* should not blow up! */
254 if (i != 0) {
255 Py_DECREF(list);
256 return (PyObject*)NULL;
257 }
258 /* Check that list == range(29, -1, -1) now */
259 for (i = 0; i < NLIST; ++i) {
260 PyObject* anint = PyList_GET_ITEM(list, i);
261 if (PyLong_AS_LONG(anint) != NLIST-1-i) {
262 PyErr_SetString(TestError,
263 "test_list_api: reverse screwed up");
264 Py_DECREF(list);
265 return (PyObject*)NULL;
266 }
267 }
268 Py_DECREF(list);
269 #undef NLIST
270
271 Py_RETURN_NONE;
272 }
273
274 static int
275 test_dict_inner(int count)
276 {
277 Py_ssize_t pos = 0, iterations = 0;
278 int i;
279 PyObject *dict = PyDict_New();
280 PyObject *v, *k;
281
282 if (dict == NULL)
283 return -1;
284
285 for (i = 0; i < count; i++) {
286 v = PyLong_FromLong(i);
287 if (v == NULL) {
288 return -1;
289 }
290 if (PyDict_SetItem(dict, v, v) < 0) {
291 Py_DECREF(v);
292 return -1;
293 }
294 Py_DECREF(v);
295 }
296
297 while (PyDict_Next(dict, &pos, &k, &v)) {
298 PyObject *o;
299 iterations++;
300
301 i = PyLong_AS_LONG(v) + 1;
302 o = PyLong_FromLong(i);
303 if (o == NULL)
304 return -1;
305 if (PyDict_SetItem(dict, k, o) < 0) {
306 Py_DECREF(o);
307 return -1;
308 }
309 Py_DECREF(o);
310 }
311
312 Py_DECREF(dict);
313
314 if (iterations != count) {
315 PyErr_SetString(
316 TestError,
317 "test_dict_iteration: dict iteration went wrong ");
318 return -1;
319 } else {
320 return 0;
321 }
322 }
323
324 static PyObject*
325 test_dict_iteration(PyObject* self, PyObject *Py_UNUSED(ignored))
326 {
327 int i;
328
329 for (i = 0; i < 200; i++) {
330 if (test_dict_inner(i) < 0) {
331 return NULL;
332 }
333 }
334
335 Py_RETURN_NONE;
336 }
337
338 #ifndef PYPY_VERSION
339 static PyObject*
340 dict_getitem_knownhash(PyObject *self, PyObject *args)
341 {
342 PyObject *mp, *key, *result;
343 Py_ssize_t hash;
344
345 if (!PyArg_ParseTuple(args, "OOn:dict_getitem_knownhash",
346 &mp, &key, &hash)) {
347 return NULL;
348 }
349
350 result = _PyDict_GetItem_KnownHash(mp, key, (Py_hash_t)hash);
351 if (result == NULL && !PyErr_Occurred()) {
352 _PyErr_SetKeyError(key);
353 return NULL;
354 }
355
356 Py_XINCREF(result);
357 return result;
358 }
359
360 #endif /* PYPY_VERSION */
361 /* Issue #4701: Check that PyObject_Hash implicitly calls
362 * PyType_Ready if it hasn't already been called
363 */
364 static PyTypeObject _HashInheritanceTester_Type = {
365 PyVarObject_HEAD_INIT(NULL, 0)
366 "hashinheritancetester", /* Name of this type */
367 sizeof(PyObject), /* Basic object size */
368 0, /* Item size for varobject */
369 (destructor)PyObject_Del, /* tp_dealloc */
370 0, /* tp_vectorcall_offset */
371 0, /* tp_getattr */
372 0, /* tp_setattr */
373 0, /* tp_as_async */
374 0, /* tp_repr */
375 0, /* tp_as_number */
376 0, /* tp_as_sequence */
377 0, /* tp_as_mapping */
378 0, /* tp_hash */
379 0, /* tp_call */
380 0, /* tp_str */
381 PyObject_GenericGetAttr, /* tp_getattro */
382 0, /* tp_setattro */
383 0, /* tp_as_buffer */
384 Py_TPFLAGS_DEFAULT, /* tp_flags */
385 0, /* tp_doc */
386 0, /* tp_traverse */
387 0, /* tp_clear */
388 0, /* tp_richcompare */
389 0, /* tp_weaklistoffset */
390 0, /* tp_iter */
391 0, /* tp_iternext */
392 0, /* tp_methods */
393 0, /* tp_members */
394 0, /* tp_getset */
395 0, /* tp_base */
396 0, /* tp_dict */
397 0, /* tp_descr_get */
398 0, /* tp_descr_set */
399 0, /* tp_dictoffset */
400 0, /* tp_init */
401 0, /* tp_alloc */
402 PyType_GenericNew, /* tp_new */
403 };
404
405 static PyObject*
406 pycompilestring(PyObject* self, PyObject *obj) {
407 if (PyBytes_CheckExact(obj) == 0) {
408 PyErr_SetString(PyExc_ValueError, "Argument must be a bytes object");
409 return NULL;
410 }
411 const char *the_string = PyBytes_AsString(obj);
412 if (the_string == NULL) {
413 return NULL;
414 }
415 return Py_CompileString(the_string, "<string>", Py_file_input);
416 }
417
418 static PyObject*
419 test_lazy_hash_inheritance(PyObject* self, PyObject *Py_UNUSED(ignored))
420 {
421 PyTypeObject *type;
422 PyObject *obj;
423 Py_hash_t hash;
424
425 type = &_HashInheritanceTester_Type;
426
427 if (type->tp_dict != NULL)
428 /* The type has already been initialized. This probably means
429 -R is being used. */
430 Py_RETURN_NONE;
431
432
433 obj = PyObject_New(PyObject, type);
434 if (obj == NULL) {
435 PyErr_Clear();
436 PyErr_SetString(
437 TestError,
438 "test_lazy_hash_inheritance: failed to create object");
439 return NULL;
440 }
441
442 if (type->tp_dict != NULL) {
443 PyErr_SetString(
444 TestError,
445 "test_lazy_hash_inheritance: type initialised too soon");
446 Py_DECREF(obj);
447 return NULL;
448 }
449
450 hash = PyObject_Hash(obj);
451 if ((hash == -1) && PyErr_Occurred()) {
452 PyErr_Clear();
453 PyErr_SetString(
454 TestError,
455 "test_lazy_hash_inheritance: could not hash object");
456 Py_DECREF(obj);
457 return NULL;
458 }
459
460 if (type->tp_dict == NULL) {
461 PyErr_SetString(
462 TestError,
463 "test_lazy_hash_inheritance: type not initialised by hash()");
464 Py_DECREF(obj);
465 return NULL;
466 }
467
468 #ifndef PYPY_VERSION /* PyPy only fills slots when calling type_attach */
469 if (type->tp_hash != PyType_Type.tp_hash) {
470 PyErr_SetString(
471 TestError,
472 "test_lazy_hash_inheritance: unexpected hash function");
473 Py_DECREF(obj);
474 return NULL;
475 }
476 #endif
477
478 Py_DECREF(obj);
479
480 Py_RETURN_NONE;
481 }
482
483
484 /* Tests of PyLong_{As, From}{Unsigned,}Long(), and
485 PyLong_{As, From}{Unsigned,}LongLong().
486
487 Note that the meat of the test is contained in testcapi_long.h.
488 This is revolting, but delicate code duplication is worse: "almost
489 exactly the same" code is needed to test long long, but the ubiquitous
490 dependence on type names makes it impossible to use a parameterized
491 function. A giant macro would be even worse than this. A C++ template
492 would be perfect.
493
494 The "report an error" functions are deliberately not part of the #include
495 file: if the test fails, you can set a breakpoint in the appropriate
496 error function directly, and crawl back from there in the debugger.
497 */
498
499 #define UNBIND(X) Py_DECREF(X); (X) = NULL
500
501 static PyObject *
502 raise_test_long_error(const char* msg)
503 {
504 return raiseTestError("test_long_api", msg);
505 }
506
507 #define TESTNAME test_long_api_inner
508 #define TYPENAME long
509 #define F_S_TO_PY PyLong_FromLong
510 #define F_PY_TO_S PyLong_AsLong
511 #define F_U_TO_PY PyLong_FromUnsignedLong
512 #define F_PY_TO_U PyLong_AsUnsignedLong
513
514 #include "testcapi_long.h"
515
516 static PyObject *
517 test_long_api(PyObject* self, PyObject *Py_UNUSED(ignored))
518 {
519 return TESTNAME(raise_test_long_error);
520 }
521
522 #undef TESTNAME
523 #undef TYPENAME
524 #undef F_S_TO_PY
525 #undef F_PY_TO_S
526 #undef F_U_TO_PY
527 #undef F_PY_TO_U
528
529 static PyObject *
530 raise_test_longlong_error(const char* msg)
531 {
532 return raiseTestError("test_longlong_api", msg);
533 }
534
535 #define TESTNAME test_longlong_api_inner
536 #define TYPENAME long long
537 #define F_S_TO_PY PyLong_FromLongLong
538 #define F_PY_TO_S PyLong_AsLongLong
539 #define F_U_TO_PY PyLong_FromUnsignedLongLong
540 #define F_PY_TO_U PyLong_AsUnsignedLongLong
541
542 #include "testcapi_long.h"
543
544 static PyObject *
545 test_longlong_api(PyObject* self, PyObject *args)
546 {
547 return TESTNAME(raise_test_longlong_error);
548 }
549
550 #undef TESTNAME
551 #undef TYPENAME
552 #undef F_S_TO_PY
553 #undef F_PY_TO_S
554 #undef F_U_TO_PY
555 #undef F_PY_TO_U
556
557 /* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG
558 is tested by test_long_api_inner. This test will concentrate on proper
559 handling of overflow.
560 */
561
562 static PyObject *
563 test_long_and_overflow(PyObject *self, PyObject *Py_UNUSED(ignored))
564 {
565 PyObject *num, *one, *temp;
566 long value;
567 int overflow;
568
569 /* Test that overflow is set properly for a large value. */
570 /* num is a number larger than LONG_MAX even on 64-bit platforms */
571 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
572 if (num == NULL)
573 return NULL;
574 overflow = 1234;
575 value = PyLong_AsLongAndOverflow(num, &overflow);
576 Py_DECREF(num);
577 if (value == -1 && PyErr_Occurred())
578 return NULL;
579 if (value != -1)
580 return raiseTestError("test_long_and_overflow",
581 "return value was not set to -1");
582 if (overflow != 1)
583 return raiseTestError("test_long_and_overflow",
584 "overflow was not set to 1");
585
586 /* Same again, with num = LONG_MAX + 1 */
587 num = PyLong_FromLong(LONG_MAX);
588 if (num == NULL)
589 return NULL;
590 one = PyLong_FromLong(1L);
591 if (one == NULL) {
592 Py_DECREF(num);
593 return NULL;
594 }
595 temp = PyNumber_Add(num, one);
596 Py_DECREF(one);
597 Py_DECREF(num);
598 num = temp;
599 if (num == NULL)
600 return NULL;
601 overflow = 0;
602 value = PyLong_AsLongAndOverflow(num, &overflow);
603 Py_DECREF(num);
604 if (value == -1 && PyErr_Occurred())
605 return NULL;
606 if (value != -1)
607 return raiseTestError("test_long_and_overflow",
608 "return value was not set to -1");
609 if (overflow != 1)
610 return raiseTestError("test_long_and_overflow",
611 "overflow was not set to 1");
612
613 /* Test that overflow is set properly for a large negative value. */
614 /* num is a number smaller than LONG_MIN even on 64-bit platforms */
615 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
616 if (num == NULL)
617 return NULL;
618 overflow = 1234;
619 value = PyLong_AsLongAndOverflow(num, &overflow);
620 Py_DECREF(num);
621 if (value == -1 && PyErr_Occurred())
622 return NULL;
623 if (value != -1)
624 return raiseTestError("test_long_and_overflow",
625 "return value was not set to -1");
626 if (overflow != -1)
627 return raiseTestError("test_long_and_overflow",
628 "overflow was not set to -1");
629
630 /* Same again, with num = LONG_MIN - 1 */
631 num = PyLong_FromLong(LONG_MIN);
632 if (num == NULL)
633 return NULL;
634 one = PyLong_FromLong(1L);
635 if (one == NULL) {
636 Py_DECREF(num);
637 return NULL;
638 }
639 temp = PyNumber_Subtract(num, one);
640 Py_DECREF(one);
641 Py_DECREF(num);
642 num = temp;
643 if (num == NULL)
644 return NULL;
645 overflow = 0;
646 value = PyLong_AsLongAndOverflow(num, &overflow);
647 Py_DECREF(num);
648 if (value == -1 && PyErr_Occurred())
649 return NULL;
650 if (value != -1)
651 return raiseTestError("test_long_and_overflow",
652 "return value was not set to -1");
653 if (overflow != -1)
654 return raiseTestError("test_long_and_overflow",
655 "overflow was not set to -1");
656
657 /* Test that overflow is cleared properly for small values. */
658 num = PyLong_FromString("FF", NULL, 16);
659 if (num == NULL)
660 return NULL;
661 overflow = 1234;
662 value = PyLong_AsLongAndOverflow(num, &overflow);
663 Py_DECREF(num);
664 if (value == -1 && PyErr_Occurred())
665 return NULL;
666 if (value != 0xFF)
667 return raiseTestError("test_long_and_overflow",
668 "expected return value 0xFF");
669 if (overflow != 0)
670 return raiseTestError("test_long_and_overflow",
671 "overflow was not cleared");
672
673 num = PyLong_FromString("-FF", NULL, 16);
674 if (num == NULL)
675 return NULL;
676 overflow = 0;
677 value = PyLong_AsLongAndOverflow(num, &overflow);
678 Py_DECREF(num);
679 if (value == -1 && PyErr_Occurred())
680 return NULL;
681 if (value != -0xFF)
682 return raiseTestError("test_long_and_overflow",
683 "expected return value 0xFF");
684 if (overflow != 0)
685 return raiseTestError("test_long_and_overflow",
686 "overflow was set incorrectly");
687
688 num = PyLong_FromLong(LONG_MAX);
689 if (num == NULL)
690 return NULL;
691 overflow = 1234;
692 value = PyLong_AsLongAndOverflow(num, &overflow);
693 Py_DECREF(num);
694 if (value == -1 && PyErr_Occurred())
695 return NULL;
696 if (value != LONG_MAX)
697 return raiseTestError("test_long_and_overflow",
698 "expected return value LONG_MAX");
699 if (overflow != 0)
700 return raiseTestError("test_long_and_overflow",
701 "overflow was not cleared");
702
703 num = PyLong_FromLong(LONG_MIN);
704 if (num == NULL)
705 return NULL;
706 overflow = 0;
707 value = PyLong_AsLongAndOverflow(num, &overflow);
708 Py_DECREF(num);
709 if (value == -1 && PyErr_Occurred())
710 return NULL;
711 if (value != LONG_MIN)
712 return raiseTestError("test_long_and_overflow",
713 "expected return value LONG_MIN");
714 if (overflow != 0)
715 return raiseTestError("test_long_and_overflow",
716 "overflow was not cleared");
717
718 Py_RETURN_NONE;
719 }
720
721 /* Test the PyLong_AsLongLongAndOverflow API. General conversion to
722 long long is tested by test_long_api_inner. This test will
723 concentrate on proper handling of overflow.
724 */
725
726 static PyObject *
727 test_long_long_and_overflow(PyObject *self, PyObject *Py_UNUSED(ignored))
728 {
729 PyObject *num, *one, *temp;
730 long long value;
731 int overflow;
732
733 /* Test that overflow is set properly for a large value. */
734 /* num is a number larger than LLONG_MAX on a typical machine. */
735 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
736 if (num == NULL)
737 return NULL;
738 overflow = 1234;
739 value = PyLong_AsLongLongAndOverflow(num, &overflow);
740 Py_DECREF(num);
741 if (value == -1 && PyErr_Occurred())
742 return NULL;
743 if (value != -1)
744 return raiseTestError("test_long_long_and_overflow",
745 "return value was not set to -1");
746 if (overflow != 1)
747 return raiseTestError("test_long_long_and_overflow",
748 "overflow was not set to 1");
749
750 /* Same again, with num = LLONG_MAX + 1 */
751 num = PyLong_FromLongLong(LLONG_MAX);
752 if (num == NULL)
753 return NULL;
754 one = PyLong_FromLong(1L);
755 if (one == NULL) {
756 Py_DECREF(num);
757 return NULL;
758 }
759 temp = PyNumber_Add(num, one);
760 Py_DECREF(one);
761 Py_DECREF(num);
762 num = temp;
763 if (num == NULL)
764 return NULL;
765 overflow = 0;
766 value = PyLong_AsLongLongAndOverflow(num, &overflow);
767 Py_DECREF(num);
768 if (value == -1 && PyErr_Occurred())
769 return NULL;
770 if (value != -1)
771 return raiseTestError("test_long_long_and_overflow",
772 "return value was not set to -1");
773 if (overflow != 1)
774 return raiseTestError("test_long_long_and_overflow",
775 "overflow was not set to 1");
776
777 /* Test that overflow is set properly for a large negative value. */
778 /* num is a number smaller than LLONG_MIN on a typical platform */
779 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
780 if (num == NULL)
781 return NULL;
782 overflow = 1234;
783 value = PyLong_AsLongLongAndOverflow(num, &overflow);
784 Py_DECREF(num);
785 if (value == -1 && PyErr_Occurred())
786 return NULL;
787 if (value != -1)
788 return raiseTestError("test_long_long_and_overflow",
789 "return value was not set to -1");
790 if (overflow != -1)
791 return raiseTestError("test_long_long_and_overflow",
792 "overflow was not set to -1");
793
794 /* Same again, with num = LLONG_MIN - 1 */
795 num = PyLong_FromLongLong(LLONG_MIN);
796 if (num == NULL)
797 return NULL;
798 one = PyLong_FromLong(1L);
799 if (one == NULL) {
800 Py_DECREF(num);
801 return NULL;
802 }
803 temp = PyNumber_Subtract(num, one);
804 Py_DECREF(one);
805 Py_DECREF(num);
806 num = temp;
807 if (num == NULL)
808 return NULL;
809 overflow = 0;
810 value = PyLong_AsLongLongAndOverflow(num, &overflow);
811 Py_DECREF(num);
812 if (value == -1 && PyErr_Occurred())
813 return NULL;
814 if (value != -1)
815 return raiseTestError("test_long_long_and_overflow",
816 "return value was not set to -1");
817 if (overflow != -1)
818 return raiseTestError("test_long_long_and_overflow",
819 "overflow was not set to -1");
820
821 /* Test that overflow is cleared properly for small values. */
822 num = PyLong_FromString("FF", NULL, 16);
823 if (num == NULL)
824 return NULL;
825 overflow = 1234;
826 value = PyLong_AsLongLongAndOverflow(num, &overflow);
827 Py_DECREF(num);
828 if (value == -1 && PyErr_Occurred())
829 return NULL;
830 if (value != 0xFF)
831 return raiseTestError("test_long_long_and_overflow",
832 "expected return value 0xFF");
833 if (overflow != 0)
834 return raiseTestError("test_long_long_and_overflow",
835 "overflow was not cleared");
836
837 num = PyLong_FromString("-FF", NULL, 16);
838 if (num == NULL)
839 return NULL;
840 overflow = 0;
841 value = PyLong_AsLongLongAndOverflow(num, &overflow);
842 Py_DECREF(num);
843 if (value == -1 && PyErr_Occurred())
844 return NULL;
845 if (value != -0xFF)
846 return raiseTestError("test_long_long_and_overflow",
847 "expected return value 0xFF");
848 if (overflow != 0)
849 return raiseTestError("test_long_long_and_overflow",
850 "overflow was set incorrectly");
851
852 num = PyLong_FromLongLong(LLONG_MAX);
853 if (num == NULL)
854 return NULL;
855 overflow = 1234;
856 value = PyLong_AsLongLongAndOverflow(num, &overflow);
857 Py_DECREF(num);
858 if (value == -1 && PyErr_Occurred())
859 return NULL;
860 if (value != LLONG_MAX)
861 return raiseTestError("test_long_long_and_overflow",
862 "expected return value LLONG_MAX");
863 if (overflow != 0)
864 return raiseTestError("test_long_long_and_overflow",
865 "overflow was not cleared");
866
867 num = PyLong_FromLongLong(LLONG_MIN);
868 if (num == NULL)
869 return NULL;
870 overflow = 0;
871 value = PyLong_AsLongLongAndOverflow(num, &overflow);
872 Py_DECREF(num);
873 if (value == -1 && PyErr_Occurred())
874 return NULL;
875 if (value != LLONG_MIN)
876 return raiseTestError("test_long_long_and_overflow",
877 "expected return value LLONG_MIN");
878 if (overflow != 0)
879 return raiseTestError("test_long_long_and_overflow",
880 "overflow was not cleared");
881
882 Py_RETURN_NONE;
883 }
884
885 /* Test the PyLong_As{Size,Ssize}_t API. At present this just tests that
886 non-integer arguments are handled correctly. It should be extended to
887 test overflow handling.
888 */
889
890 static PyObject *
891 test_long_as_size_t(PyObject *self, PyObject *Py_UNUSED(ignored))
892 {
893 size_t out_u;
894 Py_ssize_t out_s;
895
896 Py_INCREF(Py_None);
897
898 out_u = PyLong_AsSize_t(Py_None);
899 if (out_u != (size_t)-1 || !PyErr_Occurred())
900 return raiseTestError("test_long_as_size_t",
901 "PyLong_AsSize_t(None) didn't complain");
902 if (!PyErr_ExceptionMatches(PyExc_TypeError))
903 return raiseTestError("test_long_as_size_t",
904 "PyLong_AsSize_t(None) raised "
905 "something other than TypeError");
906 PyErr_Clear();
907
908 out_s = PyLong_AsSsize_t(Py_None);
909 if (out_s != (Py_ssize_t)-1 || !PyErr_Occurred())
910 return raiseTestError("test_long_as_size_t",
911 "PyLong_AsSsize_t(None) didn't complain");
912 if (!PyErr_ExceptionMatches(PyExc_TypeError))
913 return raiseTestError("test_long_as_size_t",
914 "PyLong_AsSsize_t(None) raised "
915 "something other than TypeError");
916 PyErr_Clear();
917
918 /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
919 return Py_None;
920 }
921
922 static PyObject *
923 test_long_as_unsigned_long_long_mask(PyObject *self,
924 PyObject *Py_UNUSED(ignored))
925 {
926 unsigned long long res = PyLong_AsUnsignedLongLongMask(NULL);
927
928 if (res != (unsigned long long)-1 || !PyErr_Occurred()) {
929 return raiseTestError("test_long_as_unsigned_long_long_mask",
930 "PyLong_AsUnsignedLongLongMask(NULL) didn't "
931 "complain");
932 }
933 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
934 return raiseTestError("test_long_as_unsigned_long_long_mask",
935 "PyLong_AsUnsignedLongLongMask(NULL) raised "
936 "something other than SystemError");
937 }
938 PyErr_Clear();
939 Py_RETURN_NONE;
940 }
941
942 /* Test the PyLong_AsDouble API. At present this just tests that
943 non-integer arguments are handled correctly.
944 */
945
946 static PyObject *
947 test_long_as_double(PyObject *self, PyObject *Py_UNUSED(ignored))
948 {
949 double out;
950
951 Py_INCREF(Py_None);
952
953 out = PyLong_AsDouble(Py_None);
954 if (out != -1.0 || !PyErr_Occurred())
955 return raiseTestError("test_long_as_double",
956 "PyLong_AsDouble(None) didn't complain");
957 if (!PyErr_ExceptionMatches(PyExc_TypeError))
958 return raiseTestError("test_long_as_double",
959 "PyLong_AsDouble(None) raised "
960 "something other than TypeError");
961 PyErr_Clear();
962
963 /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
964 return Py_None;
965 }
966
967 /* Test the L code for PyArg_ParseTuple. This should deliver a long long
968 for both long and int arguments. The test may leak a little memory if
969 it fails.
970 */
971 static PyObject *
972 test_L_code(PyObject *self, PyObject *Py_UNUSED(ignored))
973 {
974 PyObject *tuple, *num;
975 long long value;
976
977 tuple = PyTuple_New(1);
978 if (tuple == NULL)
979 return NULL;
980
981 num = PyLong_FromLong(42);
982 if (num == NULL)
983 return NULL;
984
985 PyTuple_SET_ITEM(tuple, 0, num);
986
987 value = -1;
988 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
989 return NULL;
990 }
991 if (value != 42)
992 return raiseTestError("test_L_code",
993 "L code returned wrong value for long 42");
994
995 /* Py_DECREF(num); <== CPython bug */
996 num = PyLong_FromLong(42);
997 if (num == NULL)
998 return NULL;
999
1000 PyTuple_SET_ITEM(tuple, 0, num);
1001
1002 value = -1;
1003 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
1004 return NULL;
1005 }
1006 if (value != 42)
1007 return raiseTestError("test_L_code",
1008 "L code returned wrong value for int 42");
1009
1010 Py_DECREF(tuple);
1011 Py_RETURN_NONE;
1012 }
1013
1014 static PyObject *
1015 return_none(void *unused)
1016 {
1017 Py_RETURN_NONE;
1018 }
1019
1020 static PyObject *
1021 raise_error(void *unused)
1022 {
1023 PyErr_SetNone(PyExc_ValueError);
1024 return NULL;
1025 }
1026
1027
1028 static int
1029 test_buildvalue_N_error(const char *fmt)
1030 {
1031 PyObject *arg, *res;
1032
1033 arg = PyList_New(0);
1034 if (arg == NULL) {
1035 return -1;
1036 }
1037
1038 size_t arg_cnt = Py_REFCNT(arg);
1039 Py_INCREF(arg);
1040 res = Py_BuildValue(fmt, return_none, NULL, arg);
1041 if (res == NULL) {
1042 return -1;
1043 }
1044 /* This should call the dealloc function for res, which should release arg
1045 * But if res is a list, it created the RPython object, so we need the PyPy
1046 * gc to collect the object
1047 */
1048 Py_DECREF(res);
1049 PyGC_Collect();
1050 size_t diff = Py_REFCNT(arg) - arg_cnt;
1051 if (diff != 0) {
1052 PyErr_Format(TestError, "test_buildvalue_N: "
1053 "arg was not decrefed in successful "
1054 "Py_BuildValue(\"%s\"): %ld", fmt, diff);
1055 return -1;
1056 }
1057
1058 Py_INCREF(arg);
1059 res = Py_BuildValue(fmt, raise_error, NULL, arg);
1060 if (res != NULL || !PyErr_Occurred()) {
1061 PyErr_Format(TestError, "test_buildvalue_N: "
1062 "Py_BuildValue(\"%s\") didn't complain", fmt);
1063 return -1;
1064 }
1065 PyErr_Clear();
1066 if (Py_REFCNT(arg) - arg_cnt != 0) {
1067 PyErr_Format(TestError, "test_buildvalue_N: "
1068 "arg was not decrefed in failed "
1069 "Py_BuildValue(\"%s\")", fmt);
1070 return -1;
1071 }
1072 Py_DECREF(arg);
1073 return 0;
1074 }
1075
1076 static PyObject *
1077 test_buildvalue_N(PyObject *self, PyObject *Py_UNUSED(ignored))
1078 {
1079 PyObject *arg, *res;
1080
1081 arg = PyList_New(0);
1082 if (arg == NULL) {
1083 return NULL;
1084 }
1085 Py_INCREF(arg);
1086 size_t arg_cnt = Py_REFCNT(arg);
1087 res = Py_BuildValue("N", arg);
1088 if (res == NULL) {
1089 return NULL;
1090 }
1091 if (res != arg) {
1092 return raiseTestError("test_buildvalue_N",
1093 "Py_BuildValue(\"N\") returned wrong result");
1094 }
1095 if (Py_REFCNT(arg) - arg_cnt != 0) {
1096 return raiseTestError("test_buildvalue_N",
1097 "arg was not decrefed in Py_BuildValue(\"N\")");
1098 }
1099 Py_DECREF(res);
1100 Py_DECREF(arg);
1101
1102 if (test_buildvalue_N_error("O&N") < 0)
1103 return NULL;
1104 if (test_buildvalue_N_error("(O&N)") < 0)
1105 return NULL;
1106 if (test_buildvalue_N_error("[O&N]") < 0)
1107 return NULL;
1108 if (test_buildvalue_N_error("{O&N}") < 0)
1109 return NULL;
1110 if (test_buildvalue_N_error("{()O&(())N}") < 0)
1111 return NULL;
1112
1113 Py_RETURN_NONE;
1114 }
1115
1116
1117 static PyObject *
1118 test_get_statictype_slots(PyObject *self, PyObject *Py_UNUSED(ignored))
1119 {
1120 newfunc tp_new = PyType_GetSlot(&PyLong_Type, Py_tp_new);
1121 if (PyLong_Type.tp_new != tp_new) {
1122 PyErr_SetString(PyExc_AssertionError, "mismatch: tp_new of long");
1123 return NULL;
1124 }
1125
1126 reprfunc tp_repr = PyType_GetSlot(&PyLong_Type, Py_tp_repr);
1127 if (PyLong_Type.tp_repr != tp_repr) {
1128 PyErr_SetString(PyExc_AssertionError, "mismatch: tp_repr of long");
1129 return NULL;
1130 }
1131
1132 ternaryfunc tp_call = PyType_GetSlot(&PyLong_Type, Py_tp_call);
1133 if (tp_call != NULL) {
1134 PyErr_SetString(PyExc_AssertionError, "mismatch: tp_call of long");
1135 return NULL;
1136 }
1137
1138 binaryfunc nb_add = PyType_GetSlot(&PyLong_Type, Py_nb_add);
1139 if (PyLong_Type.tp_as_number->nb_add != nb_add) {
1140 PyErr_SetString(PyExc_AssertionError, "mismatch: nb_add of long");
1141 return NULL;
1142 }
1143
1144 lenfunc mp_length = PyType_GetSlot(&PyLong_Type, Py_mp_length);
1145 if (mp_length != NULL) {
1146 PyErr_SetString(PyExc_AssertionError, "mismatch: mp_length of long");
1147 return NULL;
1148 }
1149
1150 void *over_value = PyType_GetSlot(&PyLong_Type, Py_bf_releasebuffer + 1);
1151 if (over_value != NULL) {
1152 PyErr_SetString(PyExc_AssertionError, "mismatch: max+1 of long");
1153 return NULL;
1154 }
1155
1156 tp_new = PyType_GetSlot(&PyLong_Type, 0);
1157 if (tp_new != NULL) {
1158 PyErr_SetString(PyExc_AssertionError, "mismatch: slot 0 of long");
1159 return NULL;
1160 }
1161 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemError)) {
1162 // This is the right exception
1163 PyErr_Clear();
1164 }
1165 else if (PyErr_Occurred()){
1166 return NULL;
1167 }
1168 else {
1169 PyErr_SetString(PyExc_AssertionError, "PyType_GetSlot returned NULL without setting an error");
1170 return NULL;
1171 }
1172
1173 Py_RETURN_NONE;
1174 }
1175
1176
1177 static PyObject *
1178 test_get_type_name(PyObject *self, PyObject *Py_UNUSED(ignored))
1179 {
1180 PyObject *tp_name = PyType_GetName(&PyLong_Type);
1181 assert(strcmp(PyUnicode_AsUTF8(tp_name), "int") == 0);
1182 Py_DECREF(tp_name);
1183
1184 tp_name = PyType_GetName(&PyModule_Type);
1185 assert(strcmp(PyUnicode_AsUTF8(tp_name), "module") == 0);
1186 Py_DECREF(tp_name);
1187
1188 PyObject *HeapTypeNameType = PyType_FromSpec(&HeapTypeNameType_Spec);
1189 if (HeapTypeNameType == NULL) {
1190 Py_RETURN_NONE;
1191 }
1192 tp_name = PyType_GetName((PyTypeObject *)HeapTypeNameType);
1193 assert(strcmp(PyUnicode_AsUTF8(tp_name), "HeapTypeNameType") == 0);
1194 Py_DECREF(tp_name);
1195
1196 PyObject *name = PyUnicode_FromString("test_name");
1197 if (name == NULL) {
1198 goto done;
1199 }
1200 if (PyObject_SetAttrString(HeapTypeNameType, "__name__", name) < 0) {
1201 Py_DECREF(name);
1202 goto done;
1203 }
1204 tp_name = PyType_GetName((PyTypeObject *)HeapTypeNameType);
1205 #ifndef PYPY_VERSION
1206 assert(strcmp(PyUnicode_AsUTF8(tp_name), "test_name") == 0);
1207 #endif
1208 Py_DECREF(name);
1209 Py_DECREF(tp_name);
1210
1211 done:
1212 Py_DECREF(HeapTypeNameType);
1213 #ifdef PYPY_VERSION
1214 Py_RETURN_FALSE;
1215 #else
1216 Py_RETURN_NONE;
1217 #endif
1218 }
1219
1220
1221 static PyObject *
1222 simple_str(PyObject *self) {
1223 return PyUnicode_FromString("<test>");
1224 }
1225
1226
1227 static PyObject *
1228 test_type_from_ephemeral_spec(PyObject *self, PyObject *Py_UNUSED(ignored))
1229 {
1230 // Test that a heap type can be created from a spec that's later deleted
1231 // (along with all its contents).
1232 // All necessary data must be copied and held by the class
1233 PyType_Spec *spec = NULL;
1234 char *name = NULL;
1235 char *doc = NULL;
1236 PyType_Slot *slots = NULL;
1237 PyObject *class = NULL;
1238 PyObject *instance = NULL;
1239 PyObject *obj = NULL;
1240 PyObject *result = NULL;
1241
1242 /* create a spec (and all its contents) on the heap */
1243
1244 const char NAME[] = "testcapi._Test";
1245 const char DOC[] = "a test class";
1246
1247 spec = PyMem_New(PyType_Spec, 1);
1248 if (spec == NULL) {
1249 PyErr_NoMemory();
1250 goto finally;
1251 }
1252 name = PyMem_New(char, sizeof(NAME));
1253 if (name == NULL) {
1254 PyErr_NoMemory();
1255 goto finally;
1256 }
1257 memcpy(name, NAME, sizeof(NAME));
1258
1259 doc = PyMem_New(char, sizeof(DOC));
1260 if (doc == NULL) {
1261 PyErr_NoMemory();
1262 goto finally;
1263 }
1264 memcpy(doc, DOC, sizeof(DOC));
1265
1266 spec->name = name;
1267 spec->basicsize = sizeof(PyObject);
1268 spec->itemsize = 0;
1269 spec->flags = Py_TPFLAGS_DEFAULT;
1270 slots = PyMem_New(PyType_Slot, 3);
1271 if (slots == NULL) {
1272 PyErr_NoMemory();
1273 goto finally;
1274 }
1275 slots[0].slot = Py_tp_str;
1276 slots[0].pfunc = simple_str;
1277 slots[1].slot = Py_tp_doc;
1278 slots[1].pfunc = doc;
1279 slots[2].slot = 0;
1280 slots[2].pfunc = NULL;
1281 spec->slots = slots;
1282
1283 /* create the class */
1284
1285 class = PyType_FromSpec(spec);
1286 if (class == NULL) {
1287 goto finally;
1288 }
1289
1290 /* deallocate the spec (and all contents) */
1291
1292 // (Explicitly ovewrite memory before freeing,
1293 // so bugs show themselves even without the debug allocator's help.)
1294 memset(spec, 0xdd, sizeof(PyType_Spec));
1295 PyMem_Del(spec);
1296 spec = NULL;
1297 memset(name, 0xdd, sizeof(NAME));
1298 PyMem_Del(name);
1299 name = NULL;
1300 memset(doc, 0xdd, sizeof(DOC));
1301 PyMem_Del(doc);
1302 doc = NULL;
1303 memset(slots, 0xdd, 3 * sizeof(PyType_Slot));
1304 PyMem_Del(slots);
1305 slots = NULL;
1306
1307 /* check that everything works */
1308
1309 PyTypeObject *class_tp = (PyTypeObject *)class;
1310 PyHeapTypeObject *class_ht = (PyHeapTypeObject *)class;
1311 // PyPy
1312 //assert(strcmp(class_tp->tp_name, "testcapi._Test") == 0);
1313 assert(strcmp(PyUnicode_AsUTF8(class_ht->ht_name), "_Test") == 0);
1314 assert(strcmp(PyUnicode_AsUTF8(class_ht->ht_qualname), "_Test") == 0);
1315 assert(strcmp(class_tp->tp_doc, "a test class") == 0);
1316
1317 // call and check __str__
1318 instance = PyObject_CallNoArgs(class);
1319 if (instance == NULL) {
1320 goto finally;
1321 }
1322 obj = PyObject_Str(instance);
1323 if (obj == NULL) {
1324 goto finally;
1325 }
1326 assert(strcmp(PyUnicode_AsUTF8(obj), "<test>") == 0);
1327 Py_CLEAR(obj);
1328
1329 result = Py_NewRef(Py_None);
1330 finally:
1331 PyMem_Del(spec);
1332 PyMem_Del(name);
1333 PyMem_Del(doc);
1334 PyMem_Del(slots);
1335 Py_XDECREF(class);
1336 Py_XDECREF(instance);
1337 Py_XDECREF(obj);
1338 return result;
1339 }
1340
1341
1342 static PyObject *
1343 test_get_type_qualname(PyObject *self, PyObject *Py_UNUSED(ignored))
1344 {
1345 PyObject *tp_qualname = PyType_GetQualName(&PyLong_Type);
1346 assert(strcmp(PyUnicode_AsUTF8(tp_qualname), "int") == 0);
1347 Py_DECREF(tp_qualname);
1348
1349 #ifndef PYPY_VERSION
1350 tp_qualname = PyType_GetQualName(&PyODict_Type);
1351 assert(strcmp(PyUnicode_AsUTF8(tp_qualname), "OrderedDict") == 0);
1352 Py_DECREF(tp_qualname);
1353 #endif
1354
1355 PyObject *HeapTypeNameType = PyType_FromSpec(&HeapTypeNameType_Spec);
1356 if (HeapTypeNameType == NULL) {
1357 Py_RETURN_NONE;
1358 }
1359 tp_qualname = PyType_GetQualName((PyTypeObject *)HeapTypeNameType);
1360 assert(strcmp(PyUnicode_AsUTF8(tp_qualname), "HeapTypeNameType") == 0);
1361 Py_DECREF(tp_qualname);
1362
1363 PyObject *spec_name = PyUnicode_FromString(HeapTypeNameType_Spec.name);
1364 if (spec_name == NULL) {
1365 goto done;
1366 }
1367 if (PyObject_SetAttrString(HeapTypeNameType,
1368 "__qualname__", spec_name) < 0) {
1369 Py_DECREF(spec_name);
1370 goto done;
1371 }
1372 tp_qualname = PyType_GetQualName((PyTypeObject *)HeapTypeNameType);
1373 #ifndef PYPY_VERSION
1374 assert(strcmp(PyUnicode_AsUTF8(tp_qualname),
1375 "_testcapi.HeapTypeNameType") == 0);
1376 #endif
1377 Py_DECREF(spec_name);
1378 Py_DECREF(tp_qualname);
1379
1380 done:
1381 Py_DECREF(HeapTypeNameType);
1382 #ifdef PYPY_VERSION
1383 Py_RETURN_FALSE;
1384 #else
1385 Py_RETURN_NONE;
1386 #endif
1387 }
1388
1389
1390 static PyObject *
1391 get_args(PyObject *self, PyObject *args)
1392 {
1393 if (args == NULL) {
1394 args = Py_None;
1395 }
1396 Py_INCREF(args);
1397 return args;
1398 }
1399
1400 static PyObject *
1401 get_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
1402 {
1403 if (kwargs == NULL) {
1404 kwargs = Py_None;
1405 }
1406 Py_INCREF(kwargs);
1407 return kwargs;
1408 }
1409
1410 /* Test tuple argument processing */
1411 static PyObject *
1412 getargs_tuple(PyObject *self, PyObject *args)
1413 {
1414 int a, b, c;
1415 if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
1416 return NULL;
1417 return Py_BuildValue("iii", a, b, c);
1418 }
1419
1420 /* test PyArg_ParseTupleAndKeywords */
1421 static PyObject *
1422 getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1423 {
1424 static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
1425 static const char fmt[] = "(ii)i|(i(ii))(iii)i";
1426 int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
1427
1428 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
1429 &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
1430 &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
1431 return NULL;
1432 return Py_BuildValue("iiiiiiiiii",
1433 int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
1434 int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
1435 }
1436
1437 /* test PyArg_ParseTupleAndKeywords keyword-only arguments */
1438 static PyObject *
1439 getargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs)
1440 {
1441 static char *keywords[] = {"required", "optional", "keyword_only", NULL};
1442 int required = -1;
1443 int optional = -1;
1444 int keyword_only = -1;
1445
1446 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", keywords,
1447 &required, &optional, &keyword_only))
1448 return NULL;
1449 return Py_BuildValue("iii", required, optional, keyword_only);
1450 }
1451
1452 /* test PyArg_ParseTupleAndKeywords positional-only arguments */
1453 static PyObject *
1454 getargs_positional_only_and_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1455 {
1456 static char *keywords[] = {"", "", "keyword", NULL};
1457 int required = -1;
1458 int optional = -1;
1459 int keyword = -1;
1460
1461 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii", keywords,
1462 &required, &optional, &keyword))
1463 return NULL;
1464 return Py_BuildValue("iii", required, optional, keyword);
1465 }
1466
1467 /* Functions to call PyArg_ParseTuple with integer format codes,
1468 and return the result.
1469 */
1470 static PyObject *
1471 getargs_b(PyObject *self, PyObject *args)
1472 {
1473 unsigned char value;
1474 if (!PyArg_ParseTuple(args, "b", &value))
1475 return NULL;
1476 return PyLong_FromUnsignedLong((unsigned long)value);
1477 }
1478
1479 static PyObject *
1480 getargs_B(PyObject *self, PyObject *args)
1481 {
1482 unsigned char value;
1483 if (!PyArg_ParseTuple(args, "B", &value))
1484 return NULL;
1485 return PyLong_FromUnsignedLong((unsigned long)value);
1486 }
1487
1488 static PyObject *
1489 getargs_h(PyObject *self, PyObject *args)
1490 {
1491 short value;
1492 if (!PyArg_ParseTuple(args, "h", &value))
1493 return NULL;
1494 return PyLong_FromLong((long)value);
1495 }
1496
1497 static PyObject *
1498 getargs_H(PyObject *self, PyObject *args)
1499 {
1500 unsigned short value;
1501 if (!PyArg_ParseTuple(args, "H", &value))
1502 return NULL;
1503 return PyLong_FromUnsignedLong((unsigned long)value);
1504 }
1505
1506 static PyObject *
1507 getargs_I(PyObject *self, PyObject *args)
1508 {
1509 unsigned int value;
1510 if (!PyArg_ParseTuple(args, "I", &value))
1511 return NULL;
1512 return PyLong_FromUnsignedLong((unsigned long)value);
1513 }
1514
1515 static PyObject *
1516 getargs_k(PyObject *self, PyObject *args)
1517 {
1518 unsigned long value;
1519 if (!PyArg_ParseTuple(args, "k", &value))
1520 return NULL;
1521 return PyLong_FromUnsignedLong(value);
1522 }
1523
1524 static PyObject *
1525 getargs_i(PyObject *self, PyObject *args)
1526 {
1527 int value;
1528 if (!PyArg_ParseTuple(args, "i", &value))
1529 return NULL;
1530 return PyLong_FromLong((long)value);
1531 }
1532
1533 static PyObject *
1534 getargs_l(PyObject *self, PyObject *args)
1535 {
1536 long value;
1537 if (!PyArg_ParseTuple(args, "l", &value))
1538 return NULL;
1539 return PyLong_FromLong(value);
1540 }
1541
1542 static PyObject *
1543 getargs_n(PyObject *self, PyObject *args)
1544 {
1545 Py_ssize_t value;
1546 if (!PyArg_ParseTuple(args, "n", &value))
1547 return NULL;
1548 return PyLong_FromSsize_t(value);
1549 }
1550
1551 static PyObject *
1552 getargs_p(PyObject *self, PyObject *args)
1553 {
1554 int value;
1555 if (!PyArg_ParseTuple(args, "p", &value))
1556 return NULL;
1557 return PyLong_FromLong(value);
1558 }
1559
1560 static PyObject *
1561 getargs_L(PyObject *self, PyObject *args)
1562 {
1563 long long value;
1564 if (!PyArg_ParseTuple(args, "L", &value))
1565 return NULL;
1566 return PyLong_FromLongLong(value);
1567 }
1568
1569 static PyObject *
1570 getargs_K(PyObject *self, PyObject *args)
1571 {
1572 unsigned long long value;
1573 if (!PyArg_ParseTuple(args, "K", &value))
1574 return NULL;
1575 return PyLong_FromUnsignedLongLong(value);
1576 }
1577
1578 /* This function not only tests the 'k' getargs code, but also the
1579 PyLong_AsUnsignedLongMask() function. */
1580 static PyObject *
1581 test_k_code(PyObject *self, PyObject *Py_UNUSED(ignored))
1582 {
1583 PyObject *tuple, *num;
1584 unsigned long value;
1585
1586 tuple = PyTuple_New(1);
1587 if (tuple == NULL)
1588 return NULL;
1589
1590 /* a number larger than ULONG_MAX even on 64-bit platforms */
1591 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
1592 if (num == NULL)
1593 return NULL;
1594
1595 value = PyLong_AsUnsignedLongMask(num);
1596 if (value != ULONG_MAX)
1597 return raiseTestError("test_k_code",
1598 "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
1599
1600 PyTuple_SET_ITEM(tuple, 0, num);
1601
1602 value = 0;
1603 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
1604 return NULL;
1605 }
1606 if (value != ULONG_MAX)
1607 return raiseTestError("test_k_code",
1608 "k code returned wrong value for long 0xFFF...FFF");
1609
1610 /* Py_DECREF(num); <== CPython bug */
1611 num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
1612 if (num == NULL)
1613 return NULL;
1614
1615 value = PyLong_AsUnsignedLongMask(num);
1616 if (value != (unsigned long)-0x42)
1617 return raiseTestError("test_k_code",
1618 "PyLong_AsUnsignedLongMask() returned wrong "
1619 "value for long -0xFFF..000042");
1620
1621 PyTuple_SET_ITEM(tuple, 0, num);
1622
1623 value = 0;
1624 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
1625 return NULL;
1626 }
1627 if (value != (unsigned long)-0x42)
1628 return raiseTestError("test_k_code",
1629 "k code returned wrong value for long -0xFFF..000042");
1630
1631 Py_DECREF(tuple);
1632 Py_RETURN_NONE;
1633 }
1634
1635 static PyObject *
1636 getargs_f(PyObject *self, PyObject *args)
1637 {
1638 float f;
1639 if (!PyArg_ParseTuple(args, "f", &f))
1640 return NULL;
1641 return PyFloat_FromDouble(f);
1642 }
1643
1644 static PyObject *
1645 getargs_d(PyObject *self, PyObject *args)
1646 {
1647 double d;
1648 if (!PyArg_ParseTuple(args, "d", &d))
1649 return NULL;
1650 return PyFloat_FromDouble(d);
1651 }
1652
1653 static PyObject *
1654 getargs_D(PyObject *self, PyObject *args)
1655 {
1656 Py_complex cval;
1657 if (!PyArg_ParseTuple(args, "D", &cval))
1658 return NULL;
1659 return PyComplex_FromCComplex(cval);
1660 }
1661
1662 static PyObject *
1663 getargs_S(PyObject *self, PyObject *args)
1664 {
1665 PyObject *obj;
1666 if (!PyArg_ParseTuple(args, "S", &obj))
1667 return NULL;
1668 Py_INCREF(obj);
1669 return obj;
1670 }
1671
1672 static PyObject *
1673 getargs_Y(PyObject *self, PyObject *args)
1674 {
1675 PyObject *obj;
1676 if (!PyArg_ParseTuple(args, "Y", &obj))
1677 return NULL;
1678 Py_INCREF(obj);
1679 return obj;
1680 }
1681
1682 static PyObject *
1683 getargs_U(PyObject *self, PyObject *args)
1684 {
1685 PyObject *obj;
1686 if (!PyArg_ParseTuple(args, "U", &obj))
1687 return NULL;
1688 Py_INCREF(obj);
1689 return obj;
1690 }
1691
1692 static PyObject *
1693 getargs_c(PyObject *self, PyObject *args)
1694 {
1695 char c;
1696 if (!PyArg_ParseTuple(args, "c", &c))
1697 return NULL;
1698 return PyLong_FromLong((unsigned char)c);
1699 }
1700
1701 static PyObject *
1702 getargs_C(PyObject *self, PyObject *args)
1703 {
1704 int c;
1705 if (!PyArg_ParseTuple(args, "C", &c))
1706 return NULL;
1707 return PyLong_FromLong(c);
1708 }
1709
1710 static PyObject *
1711 getargs_s(PyObject *self, PyObject *args)
1712 {
1713 char *str;
1714 if (!PyArg_ParseTuple(args, "s", &str))
1715 return NULL;
1716 return PyBytes_FromString(str);
1717 }
1718
1719 static PyObject *
1720 getargs_s_star(PyObject *self, PyObject *args)
1721 {
1722 Py_buffer buffer;
1723 PyObject *bytes;
1724 if (!PyArg_ParseTuple(args, "s*", &buffer))
1725 return NULL;
1726 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1727 PyBuffer_Release(&buffer);
1728 return bytes;
1729 }
1730
1731 static PyObject *
1732 getargs_s_hash(PyObject *self, PyObject *args)
1733 {
1734 char *str;
1735 Py_ssize_t size;
1736 if (!PyArg_ParseTuple(args, "s#", &str, &size))
1737 return NULL;
1738 return PyBytes_FromStringAndSize(str, size);
1739 }
1740
1741 static PyObject *
1742 getargs_z(PyObject *self, PyObject *args)
1743 {
1744 char *str;
1745 if (!PyArg_ParseTuple(args, "z", &str))
1746 return NULL;
1747 if (str != NULL)
1748 return PyBytes_FromString(str);
1749 else
1750 Py_RETURN_NONE;
1751 }
1752
1753 static PyObject *
1754 getargs_z_star(PyObject *self, PyObject *args)
1755 {
1756 Py_buffer buffer;
1757 PyObject *bytes;
1758 if (!PyArg_ParseTuple(args, "z*", &buffer))
1759 return NULL;
1760 if (buffer.buf != NULL)
1761 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1762 else {
1763 Py_INCREF(Py_None);
1764 bytes = Py_None;
1765 }
1766 PyBuffer_Release(&buffer);
1767 return bytes;
1768 }
1769
1770 static PyObject *
1771 getargs_z_hash(PyObject *self, PyObject *args)
1772 {
1773 char *str;
1774 Py_ssize_t size;
1775 if (!PyArg_ParseTuple(args, "z#", &str, &size))
1776 return NULL;
1777 if (str != NULL)
1778 return PyBytes_FromStringAndSize(str, size);
1779 else
1780 Py_RETURN_NONE;
1781 }
1782
1783 static PyObject *
1784 getargs_y(PyObject *self, PyObject *args)
1785 {
1786 char *str;
1787 if (!PyArg_ParseTuple(args, "y", &str))
1788 return NULL;
1789 return PyBytes_FromString(str);
1790 }
1791
1792 static PyObject *
1793 getargs_y_star(PyObject *self, PyObject *args)
1794 {
1795 Py_buffer buffer;
1796 PyObject *bytes;
1797 if (!PyArg_ParseTuple(args, "y*", &buffer))
1798 return NULL;
1799 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1800 PyBuffer_Release(&buffer);
1801 return bytes;
1802 }
1803
1804 static PyObject *
1805 getargs_y_hash(PyObject *self, PyObject *args)
1806 {
1807 char *str;
1808 Py_ssize_t size;
1809 if (!PyArg_ParseTuple(args, "y#", &str, &size))
1810 return NULL;
1811 return PyBytes_FromStringAndSize(str, size);
1812 }
1813
1814 static PyObject *
1815 getargs_u(PyObject *self, PyObject *args)
1816 {
1817 Py_UNICODE *str;
1818 if (!PyArg_ParseTuple(args, "u", &str))
1819 return NULL;
1820 return PyUnicode_FromWideChar(str, -1);
1821 }
1822
1823 static PyObject *
1824 getargs_u_hash(PyObject *self, PyObject *args)
1825 {
1826 Py_UNICODE *str;
1827 Py_ssize_t size;
1828 if (!PyArg_ParseTuple(args, "u#", &str, &size))
1829 return NULL;
1830 return PyUnicode_FromWideChar(str, size);
1831 }
1832
1833 static PyObject *
1834 getargs_Z(PyObject *self, PyObject *args)
1835 {
1836 Py_UNICODE *str;
1837 if (!PyArg_ParseTuple(args, "Z", &str))
1838 return NULL;
1839 if (str != NULL) {
1840 return PyUnicode_FromWideChar(str, -1);
1841 } else
1842 Py_RETURN_NONE;
1843 }
1844
1845 static PyObject *
1846 getargs_Z_hash(PyObject *self, PyObject *args)
1847 {
1848 Py_UNICODE *str;
1849 Py_ssize_t size;
1850 if (!PyArg_ParseTuple(args, "Z#", &str, &size))
1851 return NULL;
1852 if (str != NULL)
1853 return PyUnicode_FromWideChar(str, size);
1854 else
1855 Py_RETURN_NONE;
1856 }
1857
1858 static PyObject *
1859 getargs_es(PyObject *self, PyObject *args)
1860 {
1861 PyObject *arg, *result;
1862 const char *encoding = NULL;
1863 char *str;
1864
1865 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1866 return NULL;
1867 if (!PyArg_Parse(arg, "es", encoding, &str))
1868 return NULL;
1869 result = PyBytes_FromString(str);
1870 PyMem_Free(str);
1871 return result;
1872 }
1873
1874 static PyObject *
1875 getargs_et(PyObject *self, PyObject *args)
1876 {
1877 PyObject *arg, *result;
1878 const char *encoding = NULL;
1879 char *str;
1880
1881 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1882 return NULL;
1883 if (!PyArg_Parse(arg, "et", encoding, &str))
1884 return NULL;
1885 result = PyBytes_FromString(str);
1886 PyMem_Free(str);
1887 return result;
1888 }
1889
1890 static PyObject *
1891 getargs_es_hash(PyObject *self, PyObject *args)
1892 {
1893 PyObject *arg, *result;
1894 const char *encoding = NULL;
1895 PyByteArrayObject *buffer = NULL;
1896 char *str = NULL;
1897 Py_ssize_t size;
1898
1899 if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1900 return NULL;
1901 if (buffer != NULL) {
1902 str = PyByteArray_AS_STRING(buffer);
1903 size = PyByteArray_GET_SIZE(buffer);
1904 }
1905 if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
1906 return NULL;
1907 result = PyBytes_FromStringAndSize(str, size);
1908 if (buffer == NULL)
1909 PyMem_Free(str);
1910 return result;
1911 }
1912
1913 static PyObject *
1914 getargs_et_hash(PyObject *self, PyObject *args)
1915 {
1916 PyObject *arg, *result;
1917 const char *encoding = NULL;
1918 PyByteArrayObject *buffer = NULL;
1919 char *str = NULL;
1920 Py_ssize_t size;
1921
1922 if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1923 return NULL;
1924 if (buffer != NULL) {
1925 str = PyByteArray_AS_STRING(buffer);
1926 size = PyByteArray_GET_SIZE(buffer);
1927 }
1928 if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
1929 return NULL;
1930 result = PyBytes_FromStringAndSize(str, size);
1931 if (buffer == NULL)
1932 PyMem_Free(str);
1933 return result;
1934 }
1935
1936 /* Test the s and z codes for PyArg_ParseTuple.
1937 */
1938 static PyObject *
1939 test_s_code(PyObject *self, PyObject *Py_UNUSED(ignored))
1940 {
1941 /* Unicode strings should be accepted */
1942 PyObject *tuple, *obj;
1943 char *value;
1944
1945 tuple = PyTuple_New(1);
1946 if (tuple == NULL)
1947 return NULL;
1948
1949 obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"),
1950 "latin-1", NULL);
1951 if (obj == NULL)
1952 return NULL;
1953
1954 PyTuple_SET_ITEM(tuple, 0, obj);
1955
1956 /* These two blocks used to raise a TypeError:
1957 * "argument must be string without null bytes, not str"
1958 */
1959 if (!PyArg_ParseTuple(tuple, "s:test_s_code1", &value)) {
1960 return NULL;
1961 }
1962
1963 if (!PyArg_ParseTuple(tuple, "z:test_s_code2", &value)) {
1964 return NULL;
1965 }
1966
1967 Py_DECREF(tuple);
1968 Py_RETURN_NONE;
1969 }
1970
1971 static PyObject *
1972 parse_tuple_and_keywords(PyObject *self, PyObject *args)
1973 {
1974 PyObject *sub_args;
1975 PyObject *sub_kwargs;
1976 const char *sub_format;
1977 PyObject *sub_keywords;
1978
1979 Py_ssize_t i, size;
1980 char *keywords[8 + 1]; /* space for NULL at end */
1981 PyObject *o;
1982 PyObject *converted[8];
1983
1984 int result;
1985 PyObject *return_value = NULL;
1986
1987 double buffers[8][4]; /* double ensures alignment where necessary */
1988
1989 if (!PyArg_ParseTuple(args, "OOsO:parse_tuple_and_keywords",
1990 &sub_args, &sub_kwargs,
1991 &sub_format, &sub_keywords))
1992 return NULL;
1993
1994 if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) {
1995 PyErr_SetString(PyExc_ValueError,
1996 "parse_tuple_and_keywords: sub_keywords must be either list or tuple");
1997 return NULL;
1998 }
1999
2000 memset(buffers, 0, sizeof(buffers));
2001 memset(converted, 0, sizeof(converted));
2002 memset(keywords, 0, sizeof(keywords));
2003
2004 size = PySequence_Fast_GET_SIZE(sub_keywords);
2005 if (size > 8) {
2006 PyErr_SetString(PyExc_ValueError,
2007 "parse_tuple_and_keywords: too many keywords in sub_keywords");
2008 goto exit;
2009 }
2010
2011 for (i = 0; i < size; i++) {
2012 o = PySequence_Fast_GET_ITEM(sub_keywords, i);
2013 if (!PyUnicode_FSConverter(o, (void *)(converted + i))) {
2014 PyErr_Format(PyExc_ValueError,
2015 "parse_tuple_and_keywords: could not convert keywords[%zd] to narrow string", i);
2016 goto exit;
2017 }
2018 keywords[i] = PyBytes_AS_STRING(converted[i]);
2019 }
2020
2021 result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs,
2022 sub_format, keywords,
2023 buffers + 0, buffers + 1, buffers + 2, buffers + 3,
2024 buffers + 4, buffers + 5, buffers + 6, buffers + 7);
2025
2026 if (result) {
2027 return_value = Py_None;
2028 Py_INCREF(Py_None);
2029 }
2030
2031 exit:
2032 size = sizeof(converted) / sizeof(converted[0]);
2033 for (i = 0; i < size; i++) {
2034 Py_XDECREF(converted[i]);
2035 }
2036 return return_value;
2037 }
2038
2039 static volatile int x;
2040
2041 #if USE_UNICODE_WCHAR_CACHE
2042 /* Ignore use of deprecated APIs */
2043 _Py_COMP_DIAG_PUSH
2044 _Py_COMP_DIAG_IGNORE_DEPR_DECLS
2045
2046 /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
2047 of an error.
2048 */
2049 static PyObject *
2050 test_u_code(PyObject *self, PyObject *Py_UNUSED(ignored))
2051 {
2052 PyObject *tuple, *obj;
2053 Py_UNICODE *value;
2054 Py_ssize_t len;
2055
2056 /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
2057 /* Just use the macro and check that it compiles */
2058 x = Py_UNICODE_ISSPACE(25);
2059
2060 tuple = PyTuple_New(1);
2061 if (tuple == NULL)
2062 return NULL;
2063
2064 obj = PyUnicode_Decode("test", strlen("test"),
2065 "ascii", NULL);
2066 if (obj == NULL)
2067 return NULL;
2068
2069 PyTuple_SET_ITEM(tuple, 0, obj);
2070
2071 value = 0;
2072 if (!PyArg_ParseTuple(tuple, "u:test_u_code", &value)) {
2073 return NULL;
2074 }
2075 if (value != PyUnicode_AS_UNICODE(obj))
2076 return raiseTestError("test_u_code",
2077 "u code returned wrong value for u'test'");
2078 value = 0;
2079 if (!PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len)) {
2080 return NULL;
2081 }
2082 if (value != PyUnicode_AS_UNICODE(obj) ||
2083 len != PyUnicode_GET_SIZE(obj))
2084 return raiseTestError("test_u_code",
2085 "u# code returned wrong values for u'test'");
2086
2087 Py_DECREF(tuple);
2088 Py_RETURN_NONE;
2089 }
2090
2091 /* Test Z and Z# codes for PyArg_ParseTuple */
2092 static PyObject *
2093 test_Z_code(PyObject *self, PyObject *Py_UNUSED(ignored))
2094 {
2095 PyObject *tuple, *obj;
2096 const Py_UNICODE *value1, *value2;
2097 Py_ssize_t len1, len2;
2098
2099 tuple = PyTuple_New(2);
2100 if (tuple == NULL)
2101 return NULL;
2102
2103 obj = PyUnicode_FromString("test");
2104 PyTuple_SET_ITEM(tuple, 0, obj);
2105 Py_INCREF(Py_None);
2106 PyTuple_SET_ITEM(tuple, 1, Py_None);
2107
2108 /* swap values on purpose */
2109 value1 = NULL;
2110 value2 = PyUnicode_AS_UNICODE(obj);
2111
2112 /* Test Z for both values */
2113 if (!PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2)) {
2114 return NULL;
2115 }
2116 if (value1 != PyUnicode_AS_UNICODE(obj))
2117 return raiseTestError("test_Z_code",
2118 "Z code returned wrong value for 'test'");
2119 if (value2 != NULL)
2120 return raiseTestError("test_Z_code",
2121 "Z code returned wrong value for None");
2122
2123 value1 = NULL;
2124 value2 = PyUnicode_AS_UNICODE(obj);
2125 len1 = -1;
2126 len2 = -1;
2127
2128 /* Test Z# for both values */
2129 if (!PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
2130 &value2, &len2))
2131 {
2132 return NULL;
2133 }
2134 if (value1 != PyUnicode_AS_UNICODE(obj) ||
2135 len1 != PyUnicode_GET_SIZE(obj))
2136 return raiseTestError("test_Z_code",
2137 "Z# code returned wrong values for 'test'");
2138 if (value2 != NULL ||
2139 len2 != 0)
2140 return raiseTestError("test_Z_code",
2141 "Z# code returned wrong values for None'");
2142
2143 Py_DECREF(tuple);
2144 Py_RETURN_NONE;
2145 }
2146 _Py_COMP_DIAG_POP
2147 #endif /* USE_UNICODE_WCHAR_CACHE */
2148
2149 static PyObject *
2150 test_widechar(PyObject *self, PyObject *Py_UNUSED(ignored))
2151 {
2152 #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
2153 const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
2154 size_t wtextlen = 1;
2155 const wchar_t invalid[1] = {(wchar_t)0x110000u};
2156 #else
2157 const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
2158 size_t wtextlen = 2;
2159 #endif
2160 PyObject *wide, *utf8;
2161
2162 wide = PyUnicode_FromWideChar(wtext, wtextlen);
2163 if (wide == NULL)
2164 return NULL;
2165
2166 utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
2167 if (utf8 == NULL) {
2168 Py_DECREF(wide);
2169 return NULL;
2170 }
2171
2172 if (PyUnicode_GET_LENGTH(wide) != PyUnicode_GET_LENGTH(utf8)) {
2173 Py_DECREF(wide);
2174 Py_DECREF(utf8);
2175 return raiseTestError("test_widechar",
2176 "wide string and utf8 string "
2177 "have different length");
2178 }
2179 if (PyUnicode_Compare(wide, utf8)) {
2180 Py_DECREF(wide);
2181 Py_DECREF(utf8);
2182 if (PyErr_Occurred())
2183 return NULL;
2184 return raiseTestError("test_widechar",
2185 "wide string and utf8 string "
2186 "are different");
2187 }
2188
2189 Py_DECREF(wide);
2190 Py_DECREF(utf8);
2191
2192 #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
2193 wide = PyUnicode_FromWideChar(invalid, 1);
2194 if (wide == NULL)
2195 PyErr_Clear();
2196 else
2197 return raiseTestError("test_widechar",
2198 "PyUnicode_FromWideChar(L\"\\U00110000\", 1) didn't fail");
2199
2200 #if USE_UNICODE_WCHAR_CACHE
2201 /* Ignore use of deprecated APIs */
2202 _Py_COMP_DIAG_PUSH
2203 _Py_COMP_DIAG_IGNORE_DEPR_DECLS
2204 wide = PyUnicode_FromUnicode(invalid, 1);
2205 if (wide == NULL)
2206 PyErr_Clear();
2207 else
2208 return raiseTestError("test_widechar",
2209 "PyUnicode_FromUnicode(L\"\\U00110000\", 1) didn't fail");
2210
2211 wide = PyUnicode_FromUnicode(NULL, 1);
2212 if (wide == NULL)
2213 return NULL;
2214 PyUnicode_AS_UNICODE(wide)[0] = invalid[0];
2215 if (_PyUnicode_Ready(wide) < 0) {
2216 Py_DECREF(wide);
2217 PyErr_Clear();
2218 }
2219 else {
2220 Py_DECREF(wide);
2221 return raiseTestError("test_widechar",
2222 "PyUnicode_Ready() didn't fail");
2223 }
2224 _Py_COMP_DIAG_POP
2225 #endif /* USE_UNICODE_WCHAR_CACHE */
2226 #endif
2227
2228 Py_RETURN_NONE;
2229 }
2230
2231 static PyObject *
2232 unicode_aswidechar(PyObject *self, PyObject *args)
2233 {
2234 PyObject *unicode, *result;
2235 Py_ssize_t buflen, size;
2236 wchar_t *buffer;
2237
2238 if (!PyArg_ParseTuple(args, "Un", &unicode, &buflen))
2239 return NULL;
2240 buffer = PyMem_New(wchar_t, buflen);
2241 if (buffer == NULL)
2242 return PyErr_NoMemory();
2243
2244 size = PyUnicode_AsWideChar(unicode, buffer, buflen);
2245 if (size == -1) {
2246 PyMem_Free(buffer);
2247 return NULL;
2248 }
2249
2250 if (size < buflen)
2251 buflen = size + 1;
2252 else
2253 buflen = size;
2254 result = PyUnicode_FromWideChar(buffer, buflen);
2255 PyMem_Free(buffer);
2256 if (result == NULL)
2257 return NULL;
2258
2259 return Py_BuildValue("(Nn)", result, size);
2260 }
2261
2262 static PyObject *
2263 unicode_aswidecharstring(PyObject *self, PyObject *args)
2264 {
2265 PyObject *unicode, *result;
2266 Py_ssize_t size;
2267 wchar_t *buffer;
2268
2269 if (!PyArg_ParseTuple(args, "U", &unicode))
2270 return NULL;
2271
2272 buffer = PyUnicode_AsWideCharString(unicode, &size);
2273 if (buffer == NULL)
2274 return NULL;
2275
2276 result = PyUnicode_FromWideChar(buffer, size + 1);
2277 PyMem_Free(buffer);
2278 if (result == NULL)
2279 return NULL;
2280 return Py_BuildValue("(Nn)", result, size);
2281 }
2282
2283 static PyObject *
2284 unicode_asucs4(PyObject *self, PyObject *args)
2285 {
2286 PyObject *unicode, *result;
2287 Py_UCS4 *buffer;
2288 int copy_null;
2289 Py_ssize_t str_len, buf_len;
2290
2291 if (!PyArg_ParseTuple(args, "Unp:unicode_asucs4", &unicode, &str_len, &copy_null)) {
2292 return NULL;
2293 }
2294
2295 buf_len = str_len + 1;
2296 buffer = PyMem_NEW(Py_UCS4, buf_len);
2297 if (buffer == NULL) {
2298 return PyErr_NoMemory();
2299 }
2300 memset(buffer, 0, sizeof(Py_UCS4)*buf_len);
2301 buffer[str_len] = 0xffffU;
2302
2303 if (!PyUnicode_AsUCS4(unicode, buffer, buf_len, copy_null)) {
2304 PyMem_Free(buffer);
2305 return NULL;
2306 }
2307
2308 result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buffer, buf_len);
2309 PyMem_Free(buffer);
2310 return result;
2311 }
2312
2313 static PyObject *
2314 unicode_asutf8(PyObject *self, PyObject *args)
2315 {
2316 PyObject *unicode;
2317 const char *buffer;
2318
2319 if (!PyArg_ParseTuple(args, "U", &unicode)) {
2320 return NULL;
2321 }
2322
2323 buffer = PyUnicode_AsUTF8(unicode);
2324 if (buffer == NULL) {
2325 return NULL;
2326 }
2327
2328 return PyBytes_FromString(buffer);
2329 }
2330
2331 static PyObject *
2332 unicode_asutf8andsize(PyObject *self, PyObject *args)
2333 {
2334 PyObject *unicode, *result;
2335 const char *buffer;
2336 Py_ssize_t utf8_len;
2337
2338 if(!PyArg_ParseTuple(args, "U", &unicode)) {
2339 return NULL;
2340 }
2341
2342 buffer = PyUnicode_AsUTF8AndSize(unicode, &utf8_len);
2343 if (buffer == NULL) {
2344 return NULL;
2345 }
2346
2347 result = PyBytes_FromString(buffer);
2348 if (result == NULL) {
2349 return NULL;
2350 }
2351
2352 return Py_BuildValue("(Nn)", result, utf8_len);
2353 }
2354
2355 /* Test PyUnicode_DecodeUTF8() */
2356 static PyObject *
2357 unicode_decodeutf8(PyObject *self, PyObject *args)
2358 {
2359 const char *data;
2360 Py_ssize_t size;
2361 const char *errors = NULL;
2362
2363 if (!PyArg_ParseTuple(args, "y#|z", &data, &size, &errors))
2364 return NULL;
2365
2366 return PyUnicode_DecodeUTF8(data, size, errors);
2367 }
2368
2369 #ifndef PYPY_VERSION
2370
2371 /* Test PyUnicode_DecodeUTF8Stateful() */
2372 static PyObject *
2373 unicode_decodeutf8stateful(PyObject *self, PyObject *args)
2374 {
2375 const char *data;
2376 Py_ssize_t size;
2377 const char *errors = NULL;
2378 Py_ssize_t consumed = 123456789;
2379 PyObject *result;
2380
2381 if (!PyArg_ParseTuple(args, "y#|z", &data, &size, &errors))
2382 return NULL;
2383
2384 result = PyUnicode_DecodeUTF8Stateful(data, size, errors, &consumed);
2385 if (!result) {
2386 return NULL;
2387 }
2388 return Py_BuildValue("(Nn)", result, consumed);
2389 }
2390
2391 #endif
2392
2393 static PyObject *
2394 unicode_findchar(PyObject *self, PyObject *args)
2395 {
2396 PyObject *str;
2397 int direction;
2398 unsigned int ch;
2399 Py_ssize_t result;
2400 Py_ssize_t start, end;
2401
2402 if (!PyArg_ParseTuple(args, "UInni:unicode_findchar", &str, &ch,
2403 &start, &end, &direction)) {
2404 return NULL;
2405 }
2406
2407 result = PyUnicode_FindChar(str, (Py_UCS4)ch, start, end, direction);
2408 if (result == -2)
2409 return NULL;
2410 else
2411 return PyLong_FromSsize_t(result);
2412 }
2413
2414 #ifndef PYPY_VERSION
2415
2416 static PyObject *
2417 unicode_copycharacters(PyObject *self, PyObject *args)
2418 {
2419 PyObject *from, *to, *to_copy;
2420 Py_ssize_t from_start, to_start, how_many, copied;
2421
2422 if (!PyArg_ParseTuple(args, "UnOnn:unicode_copycharacters", &to, &to_start,
2423 &from, &from_start, &how_many)) {
2424 return NULL;
2425 }
2426
2427 if (!(to_copy = PyUnicode_New(PyUnicode_GET_LENGTH(to),
2428 PyUnicode_MAX_CHAR_VALUE(to)))) {
2429 return NULL;
2430 }
2431 if (PyUnicode_Fill(to_copy, 0, PyUnicode_GET_LENGTH(to_copy), 0U) < 0) {
2432 Py_DECREF(to_copy);
2433 return NULL;
2434 }
2435
2436 if ((copied = PyUnicode_CopyCharacters(to_copy, to_start, from,
2437 from_start, how_many)) < 0) {
2438 Py_DECREF(to_copy);
2439 return NULL;
2440 }
2441
2442 return Py_BuildValue("(Nn)", to_copy, copied);
2443 }
2444 #endif
2445
2446 #if USE_UNICODE_WCHAR_CACHE
2447 /* Ignore use of deprecated APIs */
2448 _Py_COMP_DIAG_PUSH
2449 _Py_COMP_DIAG_IGNORE_DEPR_DECLS
2450
2451 static PyObject *
2452 unicode_legacy_string(PyObject *self, PyObject *args)
2453 {
2454 Py_UNICODE *data;
2455 Py_ssize_t len;
2456 PyObject *u;
2457
2458 if (!PyArg_ParseTuple(args, "u#", &data, &len))
2459 return NULL;
2460
2461 u = PyUnicode_FromUnicode(NULL, len);
2462 if (u == NULL)
2463 return NULL;
2464
2465 memcpy(PyUnicode_AS_UNICODE(u), data, len * sizeof(Py_UNICODE));
2466
2467 if (len > 0) { /* The empty string is always ready. */
2468 assert(!PyUnicode_IS_READY(u));
2469 }
2470
2471 return u;
2472 }
2473 _Py_COMP_DIAG_POP
2474 #endif /* USE_UNICODE_WCHAR_CACHE */
2475
2476 static PyObject *
2477 getargs_w_star(PyObject *self, PyObject *args)
2478 {
2479 Py_buffer buffer;
2480 PyObject *result;
2481 char *str;
2482
2483 if (!PyArg_ParseTuple(args, "w*:getargs_w_star", &buffer))
2484 return NULL;
2485
2486 if (2 <= buffer.len) {
2487 str = buffer.buf;
2488 str[0] = '[';
2489 str[buffer.len-1] = ']';
2490 }
2491
2492 result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
2493 PyBuffer_Release(&buffer);
2494 return result;
2495 }
2496
2497
2498 static PyObject *
2499 test_empty_argparse(PyObject *self, PyObject *Py_UNUSED(ignored))
2500 {
2501 /* Test that formats can begin with '|'. See issue #4720. */
2502 PyObject *tuple, *dict = NULL;
2503 static char *kwlist[] = {NULL};
2504 int result;
2505 tuple = PyTuple_New(0);
2506 if (!tuple)
2507 return NULL;
2508 if (!(result = PyArg_ParseTuple(tuple, "|:test_empty_argparse"))) {
2509 goto done;
2510 }
2511 dict = PyDict_New();
2512 if (!dict)
2513 goto done;
2514 result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
2515 done:
2516 Py_DECREF(tuple);
2517 Py_XDECREF(dict);
2518 if (!result) {
2519 return NULL;
2520 }
2521 else {
2522 Py_RETURN_NONE;
2523 }
2524 }
2525
2526 static PyObject *
2527 codec_incrementalencoder(PyObject *self, PyObject *args)
2528 {
2529 const char *encoding, *errors = NULL;
2530 if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
2531 &encoding, &errors))
2532 return NULL;
2533 return PyCodec_IncrementalEncoder(encoding, errors);
2534 }
2535
2536 static PyObject *
2537 codec_incrementaldecoder(PyObject *self, PyObject *args)
2538 {
2539 const char *encoding, *errors = NULL;
2540 if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
2541 &encoding, &errors))
2542 return NULL;
2543 return PyCodec_IncrementalDecoder(encoding, errors);
2544 }
2545
2546
2547 /* Simple test of _PyLong_NumBits and _PyLong_Sign. */
2548 static PyObject *
2549 test_long_numbits(PyObject *self, PyObject *Py_UNUSED(ignored))
2550 {
2551 struct triple {
2552 long input;
2553 size_t nbits;
2554 int sign;
2555 } testcases[] = {{0, 0, 0},
2556 {1L, 1, 1},
2557 {-1L, 1, -1},
2558 {2L, 2, 1},
2559 {-2L, 2, -1},
2560 {3L, 2, 1},
2561 {-3L, 2, -1},
2562 {4L, 3, 1},
2563 {-4L, 3, -1},
2564 {0x7fffL, 15, 1}, /* one Python int digit */
2565 {-0x7fffL, 15, -1},
2566 {0xffffL, 16, 1},
2567 {-0xffffL, 16, -1},
2568 {0xfffffffL, 28, 1},
2569 {-0xfffffffL, 28, -1}};
2570 size_t i;
2571
2572 for (i = 0; i < Py_ARRAY_LENGTH(testcases); ++i) {
2573 size_t nbits;
2574 int sign;
2575 PyObject *plong;
2576
2577 plong = PyLong_FromLong(testcases[i].input);
2578 if (plong == NULL)
2579 return NULL;
2580 nbits = _PyLong_NumBits(plong);
2581 sign = _PyLong_Sign(plong);
2582
2583 Py_DECREF(plong);
2584 if (nbits != testcases[i].nbits)
2585 return raiseTestError("test_long_numbits",
2586 "wrong result for _PyLong_NumBits");
2587 if (sign != testcases[i].sign)
2588 return raiseTestError("test_long_numbits",
2589 "wrong result for _PyLong_Sign");
2590 }
2591 Py_RETURN_NONE;
2592 }
2593
2594 static PyObject *
2595 pyobject_repr_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
2596 {
2597 return PyObject_Repr(NULL);
2598 }
2599
2600 static PyObject *
2601 pyobject_str_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
2602 {
2603 return PyObject_Str(NULL);
2604 }
2605
2606 static PyObject *
2607 pyobject_bytes_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
2608 {
2609 return PyObject_Bytes(NULL);
2610 }
2611
2612 static PyObject *
2613 exc_set_object(PyObject *self, PyObject *args)
2614 {
2615 PyObject *exc;
2616 PyObject *obj;
2617
2618 if (!PyArg_ParseTuple(args, "OO:exc_set_object", &exc, &obj)) {
2619 return NULL;
2620 }
2621
2622 PyErr_SetObject(exc, obj);
2623 return NULL;
2624 }
2625
2626 static PyObject *
2627 raise_exception(PyObject *self, PyObject *args)
2628 {
2629 PyObject *exc;
2630 PyObject *exc_args, *v;
2631 int num_args, i;
2632
2633 if (!PyArg_ParseTuple(args, "Oi:raise_exception",
2634 &exc, &num_args))
2635 return NULL;
2636
2637 exc_args = PyTuple_New(num_args);
2638 if (exc_args == NULL)
2639 return NULL;
2640 for (i = 0; i < num_args; ++i) {
2641 v = PyLong_FromLong(i);
2642 if (v == NULL) {
2643 Py_DECREF(exc_args);
2644 return NULL;
2645 }
2646 PyTuple_SET_ITEM(exc_args, i, v);
2647 }
2648 PyErr_SetObject(exc, exc_args);
2649 Py_DECREF(exc_args);
2650 return NULL;
2651 }
2652
2653 static PyObject *
2654 set_errno(PyObject *self, PyObject *args)
2655 {
2656 int new_errno;
2657
2658 if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
2659 return NULL;
2660
2661 errno = new_errno;
2662 Py_RETURN_NONE;
2663 }
2664
2665 static PyObject *
2666 test_set_exception(PyObject *self, PyObject *new_exc)
2667 {
2668 PyObject *exc = PyErr_GetHandledException();
2669 assert(PyExceptionInstance_Check(exc) || exc == NULL);
2670
2671 PyErr_SetHandledException(new_exc);
2672 return exc;
2673 }
2674
2675 static PyObject *
2676 test_set_exc_info(PyObject *self, PyObject *args)
2677 {
2678 PyObject *orig_exc;
2679 PyObject *new_type, *new_value, *new_tb;
2680 PyObject *type, *value, *tb;
2681 if (!PyArg_ParseTuple(args, "OOO:test_set_exc_info",
2682 &new_type, &new_value, &new_tb))
2683 return NULL;
2684
2685 PyErr_GetExcInfo(&type, &value, &tb);
2686
2687 Py_INCREF(new_type);
2688 Py_INCREF(new_value);
2689 Py_INCREF(new_tb);
2690 PyErr_SetExcInfo(new_type, new_value, new_tb);
2691
2692 orig_exc = PyTuple_Pack(3, type ? type : Py_None, value ? value : Py_None, tb ? tb : Py_None);
2693 Py_XDECREF(type);
2694 Py_XDECREF(value);
2695 Py_XDECREF(tb);
2696 return orig_exc;
2697 }
2698
2699 static int test_run_counter = 0;
2700
2701 static PyObject *
2702 test_datetime_capi(PyObject *self, PyObject *args) {
2703 if (PyDateTimeAPI) {
2704 if (test_run_counter) {
2705 /* Probably regrtest.py -R */
2706 Py_RETURN_NONE;
2707 }
2708 else {
2709 PyErr_SetString(PyExc_AssertionError,
2710 "PyDateTime_CAPI somehow initialized");
2711 return NULL;
2712 }
2713 }
2714 test_run_counter++;
2715 PyDateTime_IMPORT;
2716
2717 if (PyDateTimeAPI)
2718 Py_RETURN_NONE;
2719 else
2720 return NULL;
2721 }
2722
2723 /* Functions exposing the C API type checking for testing */
2724 #define MAKE_DATETIME_CHECK_FUNC(check_method, exact_method) \
2725 PyObject *obj; \
2726 int exact = 0; \
2727 if (!PyArg_ParseTuple(args, "O|p", &obj, &exact)) { \
2728 return NULL; \
2729 } \
2730 int rv = exact?exact_method(obj):check_method(obj); \
2731 if (rv) { \
2732 Py_RETURN_TRUE; \
2733 } else { \
2734 Py_RETURN_FALSE; \
2735 }
2736
2737 static PyObject *
2738 datetime_check_date(PyObject *self, PyObject *args) {
2739 MAKE_DATETIME_CHECK_FUNC(PyDate_Check, PyDate_CheckExact)
2740 }
2741
2742 static PyObject *
2743 datetime_check_time(PyObject *self, PyObject *args) {
2744 MAKE_DATETIME_CHECK_FUNC(PyTime_Check, PyTime_CheckExact)
2745 }
2746
2747 static PyObject *
2748 datetime_check_datetime(PyObject *self, PyObject *args) {
2749 MAKE_DATETIME_CHECK_FUNC(PyDateTime_Check, PyDateTime_CheckExact)
2750 }
2751
2752 static PyObject *
2753 datetime_check_delta(PyObject *self, PyObject *args) {
2754 MAKE_DATETIME_CHECK_FUNC(PyDelta_Check, PyDelta_CheckExact)
2755 }
2756
2757 static PyObject *
2758 datetime_check_tzinfo(PyObject *self, PyObject *args) {
2759 MAKE_DATETIME_CHECK_FUNC(PyTZInfo_Check, PyTZInfo_CheckExact)
2760 }
2761
2762
2763 /* Makes three variations on timezone representing UTC-5:
2764 1. timezone with offset and name from PyDateTimeAPI
2765 2. timezone with offset and name from PyTimeZone_FromOffsetAndName
2766 3. timezone with offset (no name) from PyTimeZone_FromOffset
2767 */
2768 static PyObject *
2769 make_timezones_capi(PyObject *self, PyObject *args) {
2770 PyObject *offset = PyDelta_FromDSU(0, -18000, 0);
2771 PyObject *name = PyUnicode_FromString("EST");
2772
2773 PyObject *est_zone_capi = PyDateTimeAPI->TimeZone_FromTimeZone(offset, name);
2774 PyObject *est_zone_macro = PyTimeZone_FromOffsetAndName(offset, name);
2775 PyObject *est_zone_macro_noname = PyTimeZone_FromOffset(offset);
2776
2777 Py_DecRef(offset);
2778 Py_DecRef(name);
2779
2780 PyObject *rv = PyTuple_New(3);
2781
2782 PyTuple_SET_ITEM(rv, 0, est_zone_capi);
2783 PyTuple_SET_ITEM(rv, 1, est_zone_macro);
2784 PyTuple_SET_ITEM(rv, 2, est_zone_macro_noname);
2785
2786 return rv;
2787 }
2788
2789 static PyObject *
2790 get_timezones_offset_zero(PyObject *self, PyObject *args) {
2791 PyObject *offset = PyDelta_FromDSU(0, 0, 0);
2792 PyObject *name = PyUnicode_FromString("");
2793
2794 // These two should return the UTC singleton
2795 PyObject *utc_singleton_0 = PyTimeZone_FromOffset(offset);
2796 PyObject *utc_singleton_1 = PyTimeZone_FromOffsetAndName(offset, NULL);
2797
2798 // This one will return +00:00 zone, but not the UTC singleton
2799 PyObject *non_utc_zone = PyTimeZone_FromOffsetAndName(offset, name);
2800
2801 Py_DecRef(offset);
2802 Py_DecRef(name);
2803
2804 PyObject *rv = PyTuple_New(3);
2805 PyTuple_SET_ITEM(rv, 0, utc_singleton_0);
2806 PyTuple_SET_ITEM(rv, 1, utc_singleton_1);
2807 PyTuple_SET_ITEM(rv, 2, non_utc_zone);
2808
2809 return rv;
2810 }
2811
2812 static PyObject *
2813 get_timezone_utc_capi(PyObject* self, PyObject *args) {
2814 int macro = 0;
2815 if (!PyArg_ParseTuple(args, "|p", &macro)) {
2816 return NULL;
2817 }
2818 if (macro) {
2819 Py_INCREF(PyDateTime_TimeZone_UTC);
2820 return PyDateTime_TimeZone_UTC;
2821 } else {
2822 Py_INCREF(PyDateTimeAPI->TimeZone_UTC);
2823 return PyDateTimeAPI->TimeZone_UTC;
2824 }
2825 }
2826
2827 static PyObject *
2828 get_date_fromdate(PyObject *self, PyObject *args)
2829 {
2830 PyObject *rv = NULL;
2831 int macro;
2832 int year, month, day;
2833
2834 if (!PyArg_ParseTuple(args, "piii", &macro, &year, &month, &day)) {
2835 return NULL;
2836 }
2837
2838 if (macro) {
2839 rv = PyDate_FromDate(year, month, day);
2840 }
2841 else {
2842 rv = PyDateTimeAPI->Date_FromDate(
2843 year, month, day,
2844 PyDateTimeAPI->DateType);
2845 }
2846 return rv;
2847 }
2848
2849
2850 static PyObject *
2851 get_datetime_fromdateandtime(PyObject *self, PyObject *args)
2852 {
2853 PyObject *rv = NULL;
2854 int macro;
2855 int year, month, day;
2856 int hour, minute, second, microsecond;
2857
2858 if (!PyArg_ParseTuple(args, "piiiiiii",
2859 &macro,
2860 &year, &month, &day,
2861 &hour, &minute, &second, &microsecond)) {
2862 return NULL;
2863 }
2864
2865 if (macro) {
2866 rv = PyDateTime_FromDateAndTime(
2867 year, month, day,
2868 hour, minute, second, microsecond);
2869 }
2870 else {
2871 rv = PyDateTimeAPI->DateTime_FromDateAndTime(
2872 year, month, day,
2873 hour, minute, second, microsecond,
2874 Py_None,
2875 PyDateTimeAPI->DateTimeType);
2876 }
2877 return rv;
2878 }
2879
2880 static PyObject *
2881 get_datetime_fromdateandtimeandfold(PyObject *self, PyObject *args)
2882 {
2883 PyObject *rv = NULL;
2884 int macro;
2885 int year, month, day;
2886 int hour, minute, second, microsecond, fold;
2887
2888 if (!PyArg_ParseTuple(args, "piiiiiiii",
2889 &macro,
2890 &year, &month, &day,
2891 &hour, &minute, &second, &microsecond,
2892 &fold)) {
2893 return NULL;
2894 }
2895
2896 if (macro) {
2897 rv = PyDateTime_FromDateAndTimeAndFold(
2898 year, month, day,
2899 hour, minute, second, microsecond,
2900 fold);
2901 }
2902 else {
2903 rv = PyDateTimeAPI->DateTime_FromDateAndTimeAndFold(
2904 year, month, day,
2905 hour, minute, second, microsecond,
2906 Py_None,
2907 fold,
2908 PyDateTimeAPI->DateTimeType);
2909 }
2910 return rv;
2911 }
2912
2913 static PyObject *
2914 get_time_fromtime(PyObject *self, PyObject *args)
2915 {
2916 PyObject *rv = NULL;
2917 int macro;
2918 int hour, minute, second, microsecond;
2919
2920 if (!PyArg_ParseTuple(args, "piiii",
2921 &macro,
2922 &hour, &minute, &second, &microsecond)) {
2923 return NULL;
2924 }
2925
2926 if (macro) {
2927 rv = PyTime_FromTime(hour, minute, second, microsecond);
2928 }
2929 else {
2930 rv = PyDateTimeAPI->Time_FromTime(
2931 hour, minute, second, microsecond,
2932 Py_None,
2933 PyDateTimeAPI->TimeType);
2934 }
2935 return rv;
2936 }
2937
2938 static PyObject *
2939 get_time_fromtimeandfold(PyObject *self, PyObject *args)
2940 {
2941 PyObject *rv = NULL;
2942 int macro;
2943 int hour, minute, second, microsecond, fold;
2944
2945 if (!PyArg_ParseTuple(args, "piiiii",
2946 &macro,
2947 &hour, &minute, &second, &microsecond,
2948 &fold)) {
2949 return NULL;
2950 }
2951
2952 if (macro) {
2953 rv = PyTime_FromTimeAndFold(hour, minute, second, microsecond, fold);
2954 }
2955 else {
2956 rv = PyDateTimeAPI->Time_FromTimeAndFold(
2957 hour, minute, second, microsecond,
2958 Py_None,
2959 fold,
2960 PyDateTimeAPI->TimeType);
2961 }
2962 return rv;
2963 }
2964
2965 static PyObject *
2966 get_delta_fromdsu(PyObject *self, PyObject *args)
2967 {
2968 PyObject *rv = NULL;
2969 int macro;
2970 int days, seconds, microseconds;
2971
2972 if (!PyArg_ParseTuple(args, "piii",
2973 &macro,
2974 &days, &seconds, &microseconds)) {
2975 return NULL;
2976 }
2977
2978 if (macro) {
2979 rv = PyDelta_FromDSU(days, seconds, microseconds);
2980 }
2981 else {
2982 rv = PyDateTimeAPI->Delta_FromDelta(
2983 days, seconds, microseconds, 1,
2984 PyDateTimeAPI->DeltaType);
2985 }
2986
2987 return rv;
2988 }
2989
2990 static PyObject *
2991 get_date_fromtimestamp(PyObject* self, PyObject *args)
2992 {
2993 PyObject *tsargs = NULL, *ts = NULL, *rv = NULL;
2994 int macro = 0;
2995
2996 if (!PyArg_ParseTuple(args, "O|p", &ts, &macro)) {
2997 return NULL;
2998 }
2999
3000 // Construct the argument tuple
3001 if ((tsargs = PyTuple_Pack(1, ts)) == NULL) {
3002 return NULL;
3003 }
3004
3005 // Pass along to the API function
3006 if (macro) {
3007 rv = PyDate_FromTimestamp(tsargs);
3008 }
3009 else {
3010 rv = PyDateTimeAPI->Date_FromTimestamp(
3011 (PyObject *)PyDateTimeAPI->DateType, tsargs
3012 );
3013 }
3014
3015 Py_DECREF(tsargs);
3016 return rv;
3017 }
3018
3019 static PyObject *
3020 get_datetime_fromtimestamp(PyObject* self, PyObject *args)
3021 {
3022 int macro = 0;
3023 int usetz = 0;
3024 PyObject *tsargs = NULL, *ts = NULL, *tzinfo = Py_None, *rv = NULL;
3025 if (!PyArg_ParseTuple(args, "OO|pp", &ts, &tzinfo, &usetz, &macro)) {
3026 return NULL;
3027 }
3028
3029 // Construct the argument tuple
3030 if (usetz) {
3031 tsargs = PyTuple_Pack(2, ts, tzinfo);
3032 }
3033 else {
3034 tsargs = PyTuple_Pack(1, ts);
3035 }
3036
3037 if (tsargs == NULL) {
3038 return NULL;
3039 }
3040
3041 // Pass along to the API function
3042 if (macro) {
3043 rv = PyDateTime_FromTimestamp(tsargs);
3044 }
3045 else {
3046 rv = PyDateTimeAPI->DateTime_FromTimestamp(
3047 (PyObject *)PyDateTimeAPI->DateTimeType, tsargs, NULL
3048 );
3049 }
3050
3051 Py_DECREF(tsargs);
3052 return rv;
3053 }
3054
3055 static PyObject *
3056 test_PyDateTime_GET(PyObject *self, PyObject *obj)
3057 {
3058 int year, month, day;
3059
3060 year = PyDateTime_GET_YEAR(obj);
3061 month = PyDateTime_GET_MONTH(obj);
3062 day = PyDateTime_GET_DAY(obj);
3063
3064 return Py_BuildValue("(iii)", year, month, day);
3065 }
3066
3067 static PyObject *
3068 test_PyDateTime_DATE_GET(PyObject *self, PyObject *obj)
3069 {
3070 int hour, minute, second, microsecond;
3071
3072 hour = PyDateTime_DATE_GET_HOUR(obj);
3073 minute = PyDateTime_DATE_GET_MINUTE(obj);
3074 second = PyDateTime_DATE_GET_SECOND(obj);
3075 microsecond = PyDateTime_DATE_GET_MICROSECOND(obj);
3076 PyObject *tzinfo = PyDateTime_DATE_GET_TZINFO(obj);
3077
3078 return Py_BuildValue("(iiiiO)", hour, minute, second, microsecond, tzinfo);
3079 }
3080
3081 static PyObject *
3082 test_PyDateTime_TIME_GET(PyObject *self, PyObject *obj)
3083 {
3084 int hour, minute, second, microsecond;
3085
3086 hour = PyDateTime_TIME_GET_HOUR(obj);
3087 minute = PyDateTime_TIME_GET_MINUTE(obj);
3088 second = PyDateTime_TIME_GET_SECOND(obj);
3089 microsecond = PyDateTime_TIME_GET_MICROSECOND(obj);
3090 PyObject *tzinfo = PyDateTime_TIME_GET_TZINFO(obj);
3091
3092 return Py_BuildValue("(iiiiO)", hour, minute, second, microsecond, tzinfo);
3093 }
3094
3095 static PyObject *
3096 test_PyDateTime_DELTA_GET(PyObject *self, PyObject *obj)
3097 {
3098 int days, seconds, microseconds;
3099
3100 days = PyDateTime_DELTA_GET_DAYS(obj);
3101 seconds = PyDateTime_DELTA_GET_SECONDS(obj);
3102 microseconds = PyDateTime_DELTA_GET_MICROSECONDS(obj);
3103
3104 return Py_BuildValue("(iii)", days, seconds, microseconds);
3105 }
3106
3107 /* test_thread_state spawns a thread of its own, and that thread releases
3108 * `thread_done` when it's finished. The driver code has to know when the
3109 * thread finishes, because the thread uses a PyObject (the callable) that
3110 * may go away when the driver finishes. The former lack of this explicit
3111 * synchronization caused rare segfaults, so rare that they were seen only
3112 * on a Mac buildbot (although they were possible on any box).
3113 */
3114 static PyThread_type_lock thread_done = NULL;
3115
3116 static int
3117 _make_call(void *callable)
3118 {
3119 PyObject *rc;
3120 int success;
3121 PyGILState_STATE s = PyGILState_Ensure();
3122 rc = PyObject_CallNoArgs((PyObject *)callable);
3123 success = (rc != NULL);
3124 Py_XDECREF(rc);
3125 PyGILState_Release(s);
3126 return success;
3127 }
3128
3129 /* Same thing, but releases `thread_done` when it returns. This variant
3130 * should be called only from threads spawned by test_thread_state().
3131 */
3132 static void
3133 _make_call_from_thread(void *callable)
3134 {
3135 _make_call(callable);
3136 PyThread_release_lock(thread_done);
3137 }
3138
3139 static PyObject *
3140 test_thread_state(PyObject *self, PyObject *args)
3141 {
3142 PyObject *fn;
3143 int success = 1;
3144
3145 if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
3146 return NULL;
3147
3148 if (!PyCallable_Check(fn)) {
3149 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
3150 Py_TYPE(fn)->tp_name);
3151 return NULL;
3152 }
3153
3154 thread_done = PyThread_allocate_lock();
3155 if (thread_done == NULL)
3156 return PyErr_NoMemory();
3157 PyThread_acquire_lock(thread_done, 1);
3158
3159 /* Start a new thread with our callback. */
3160 PyThread_start_new_thread(_make_call_from_thread, fn);
3161 /* Make the callback with the thread lock held by this thread */
3162 success &= _make_call(fn);
3163 /* Do it all again, but this time with the thread-lock released */
3164 Py_BEGIN_ALLOW_THREADS
3165 success &= _make_call(fn);
3166 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
3167 Py_END_ALLOW_THREADS
3168
3169 /* And once more with and without a thread
3170 XXX - should use a lock and work out exactly what we are trying
3171 to test <wink>
3172 */
3173 Py_BEGIN_ALLOW_THREADS
3174 PyThread_start_new_thread(_make_call_from_thread, fn);
3175 success &= _make_call(fn);
3176 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
3177 Py_END_ALLOW_THREADS
3178
3179 /* Release lock we acquired above. This is required on HP-UX. */
3180 PyThread_release_lock(thread_done);
3181
3182 PyThread_free_lock(thread_done);
3183 if (!success)
3184 return NULL;
3185 Py_RETURN_NONE;
3186 }
3187
3188 /* test Py_AddPendingCalls using threads */
3189 static int _pending_callback(void *arg)
3190 {
3191 /* we assume the argument is callable object to which we own a reference */
3192 PyObject *callable = (PyObject *)arg;
3193 PyObject *r = PyObject_CallNoArgs(callable);
3194 Py_DECREF(callable);
3195 Py_XDECREF(r);
3196 return r != NULL ? 0 : -1;
3197 }
3198
3199 /* The following requests n callbacks to _pending_callback. It can be
3200 * run from any python thread.
3201 */
3202 static PyObject *
3203 pending_threadfunc(PyObject *self, PyObject *arg)
3204 {
3205 PyObject *callable;
3206 int r;
3207 if (PyArg_ParseTuple(arg, "O", &callable) == 0)
3208 return NULL;
3209
3210 /* create the reference for the callbackwhile we hold the lock */
3211 Py_INCREF(callable);
3212
3213 Py_BEGIN_ALLOW_THREADS
3214 r = Py_AddPendingCall(&_pending_callback, callable);
3215 Py_END_ALLOW_THREADS
3216
3217 if (r<0) {
3218 Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
3219 Py_RETURN_FALSE;
3220 }
3221 Py_RETURN_TRUE;
3222 }
3223
3224 /* Some tests of PyUnicode_FromFormat(). This needs more tests. */
3225 static PyObject *
3226 test_string_from_format(PyObject *self, PyObject *Py_UNUSED(ignored))
3227 {
3228 PyObject *result;
3229 char *msg;
3230
3231 #define CHECK_1_FORMAT(FORMAT, TYPE) \
3232 result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
3233 if (result == NULL) \
3234 return NULL; \
3235 if (!_PyUnicode_EqualToASCIIString(result, "1")) { \
3236 msg = FORMAT " failed at 1"; \
3237 goto Fail; \
3238 } \
3239 Py_DECREF(result)
3240
3241 CHECK_1_FORMAT("%d", int);
3242 CHECK_1_FORMAT("%ld", long);
3243 /* The z width modifier was added in Python 2.5. */
3244 CHECK_1_FORMAT("%zd", Py_ssize_t);
3245
3246 /* The u type code was added in Python 2.5. */
3247 CHECK_1_FORMAT("%u", unsigned int);
3248 CHECK_1_FORMAT("%lu", unsigned long);
3249 CHECK_1_FORMAT("%zu", size_t);
3250
3251 /* "%lld" and "%llu" support added in Python 2.7. */
3252 CHECK_1_FORMAT("%llu", unsigned long long);
3253 CHECK_1_FORMAT("%lld", long long);
3254
3255 Py_RETURN_NONE;
3256
3257 Fail:
3258 Py_XDECREF(result);
3259 return raiseTestError("test_string_from_format", msg);
3260
3261 #undef CHECK_1_FORMAT
3262 }
3263
3264
3265 static PyObject *
3266 test_unicode_compare_with_ascii(PyObject *self, PyObject *Py_UNUSED(ignored)) {
3267 PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
3268 int result;
3269 if (py_s == NULL)
3270 return NULL;
3271 result = PyUnicode_CompareWithASCIIString(py_s, "str");
3272 Py_DECREF(py_s);
3273 if (!result) {
3274 PyErr_SetString(TestError, "Python string ending in NULL "
3275 "should not compare equal to c string.");
3276 return NULL;
3277 }
3278 Py_RETURN_NONE;
3279 }
3280
3281 /* This is here to provide a docstring for test_descr. */
3282 static PyObject *
3283 test_with_docstring(PyObject *self, PyObject *Py_UNUSED(ignored))
3284 {
3285 Py_RETURN_NONE;
3286 }
3287
3288 /* Test PyOS_string_to_double. */
3289 static PyObject *
3290 test_string_to_double(PyObject *self, PyObject *Py_UNUSED(ignored)) {
3291 double result;
3292 const char *msg;
3293
3294 #define CHECK_STRING(STR, expected) \
3295 result = PyOS_string_to_double(STR, NULL, NULL); \
3296 if (result == -1.0 && PyErr_Occurred()) \
3297 return NULL; \
3298 if (result != (double)expected) { \
3299 msg = "conversion of " STR " to float failed"; \
3300 goto fail; \
3301 }
3302
3303 #define CHECK_INVALID(STR) \
3304 result = PyOS_string_to_double(STR, NULL, NULL); \
3305 if (result == -1.0 && PyErr_Occurred()) { \
3306 if (PyErr_ExceptionMatches(PyExc_ValueError)) \
3307 PyErr_Clear(); \
3308 else \
3309 return NULL; \
3310 } \
3311 else { \
3312 msg = "conversion of " STR " didn't raise ValueError"; \
3313 goto fail; \
3314 }
3315
3316 CHECK_STRING("0.1", 0.1);
3317 CHECK_STRING("1.234", 1.234);
3318 CHECK_STRING("-1.35", -1.35);
3319 CHECK_STRING(".1e01", 1.0);
3320 CHECK_STRING("2.e-2", 0.02);
3321
3322 CHECK_INVALID(" 0.1");
3323 CHECK_INVALID("\t\n-3");
3324 CHECK_INVALID(".123 ");
3325 CHECK_INVALID("3\n");
3326 CHECK_INVALID("123abc");
3327
3328 Py_RETURN_NONE;
3329 fail:
3330 return raiseTestError("test_string_to_double", msg);
3331 #undef CHECK_STRING
3332 #undef CHECK_INVALID
3333 }
3334
3335
3336 /* Coverage testing of capsule objects. */
3337
3338 static const char *capsule_name = "capsule name";
3339 static char *capsule_pointer = "capsule pointer";
3340 static char *capsule_context = "capsule context";
3341 static const char *capsule_error = NULL;
3342 static int
3343 capsule_destructor_call_count = 0;
3344
3345 static void
3346 capsule_destructor(PyObject *o) {
3347 capsule_destructor_call_count++;
3348 if (PyCapsule_GetContext(o) != capsule_context) {
3349 capsule_error = "context did not match in destructor!";
3350 } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
3351 capsule_error = "destructor did not match in destructor! (woah!)";
3352 } else if (PyCapsule_GetName(o) != capsule_name) {
3353 capsule_error = "name did not match in destructor!";
3354 } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
3355 capsule_error = "pointer did not match in destructor!";
3356 }
3357 }
3358
3359 typedef struct {
3360 char *name;
3361 char *module;
3362 char *attribute;
3363 } known_capsule;
3364
3365 static PyObject *
3366 test_capsule(PyObject *self, PyObject *Py_UNUSED(ignored))
3367 {
3368 PyObject *object;
3369 const char *error = NULL;
3370 void *pointer;
3371 void *pointer2;
3372 known_capsule known_capsules[] = {
3373 #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
3374 #ifndef PYPY_VERSION
3375 KNOWN_CAPSULE("_socket", "CAPI"),
3376 KNOWN_CAPSULE("_curses", "_C_API"),
3377 KNOWN_CAPSULE("datetime", "datetime_CAPI"),
3378 #endif
3379 { NULL, NULL },
3380 };
3381 known_capsule *known = &known_capsules[0];
3382
3383 #define FAIL(x) { error = (x); goto exit; }
3384
3385 // PyPy adds the collect calls
3386 #define CHECK_DESTRUCTOR \
3387 PyGC_Collect(); \
3388 PyGC_Collect(); \
3389 if (capsule_error) { \
3390 FAIL(capsule_error); \
3391 } \
3392 else if (!capsule_destructor_call_count) { \
3393 FAIL("destructor not called!"); \
3394 } \
3395 capsule_destructor_call_count = 0; \
3396
3397 object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
3398 PyCapsule_SetContext(object, capsule_context);
3399 capsule_destructor(object);
3400 CHECK_DESTRUCTOR;
3401 Py_DECREF(object);
3402 CHECK_DESTRUCTOR;
3403
3404 object = PyCapsule_New(known, "ignored", NULL);
3405 PyCapsule_SetPointer(object, capsule_pointer);
3406 PyCapsule_SetName(object, capsule_name);
3407 PyCapsule_SetDestructor(object, capsule_destructor);
3408 PyCapsule_SetContext(object, capsule_context);
3409 capsule_destructor(object);
3410 CHECK_DESTRUCTOR;
3411 /* intentionally access using the wrong name */
3412 pointer2 = PyCapsule_GetPointer(object, "the wrong name");
3413 if (!PyErr_Occurred()) {
3414 FAIL("PyCapsule_GetPointer should have failed but did not!");
3415 }
3416 PyErr_Clear();
3417 if (pointer2) {
3418 if (pointer2 == capsule_pointer) {
3419 FAIL("PyCapsule_GetPointer should not have"
3420 " returned the internal pointer!");
3421 } else {
3422 FAIL("PyCapsule_GetPointer should have "
3423 "returned NULL pointer but did not!");
3424 }
3425 }
3426 PyCapsule_SetDestructor(object, NULL);
3427 Py_DECREF(object);
3428 if (capsule_destructor_call_count) {
3429 FAIL("destructor called when it should not have been!");
3430 }
3431
3432 for (known = &known_capsules[0]; known->module != NULL; known++) {
3433 /* yeah, ordinarily I wouldn't do this either,
3434 but it's fine for this test harness.
3435 */
3436 static char buffer[256];
3437 #undef FAIL
3438 #define FAIL(x) \
3439 { \
3440 sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
3441 x, known->module, known->attribute); \
3442 error = buffer; \
3443 goto exit; \
3444 } \
3445
3446 PyObject *module = PyImport_ImportModule(known->module);
3447 if (module) {
3448 pointer = PyCapsule_Import(known->name, 0);
3449 if (!pointer) {
3450 Py_DECREF(module);
3451 FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
3452 }
3453 object = PyObject_GetAttrString(module, known->attribute);
3454 if (!object) {
3455 Py_DECREF(module);
3456 return NULL;
3457 }
3458 pointer2 = PyCapsule_GetPointer(object,
3459 "weebles wobble but they don't fall down");
3460 if (!PyErr_Occurred()) {
3461 Py_DECREF(object);
3462 Py_DECREF(module);
3463 FAIL("PyCapsule_GetPointer should have failed but did not!");
3464 }
3465 PyErr_Clear();
3466 if (pointer2) {
3467 Py_DECREF(module);
3468 Py_DECREF(object);
3469 if (pointer2 == pointer) {
3470 FAIL("PyCapsule_GetPointer should not have"
3471 " returned its internal pointer!");
3472 } else {
3473 FAIL("PyCapsule_GetPointer should have"
3474 " returned NULL pointer but did not!");
3475 }
3476 }
3477 Py_DECREF(object);
3478 Py_DECREF(module);
3479 }
3480 else
3481 PyErr_Clear();
3482 }
3483
3484 exit:
3485 if (error) {
3486 return raiseTestError("test_capsule", error);
3487 }
3488 Py_RETURN_NONE;
3489 #undef FAIL
3490 }
3491
3492 #ifdef HAVE_GETTIMEOFDAY
3493 /* Profiling of integer performance */
3494 static void print_delta(int test, struct timeval *s, struct timeval *e)
3495 {
3496 e->tv_sec -= s->tv_sec;
3497 e->tv_usec -= s->tv_usec;
3498 if (e->tv_usec < 0) {
3499 e->tv_sec -=1;
3500 e->tv_usec += 1000000;
3501 }
3502 printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
3503 }
3504
3505 static PyObject *
3506 profile_int(PyObject *self, PyObject* args)
3507 {
3508 int i, k;
3509 struct timeval start, stop;
3510 PyObject *single, **multiple, *op1, *result;
3511
3512 /* Test 1: Allocate and immediately deallocate
3513 many small integers */
3514 gettimeofday(&start, NULL);
3515 for(k=0; k < 20000; k++)
3516 for(i=0; i < 1000; i++) {
3517 single = PyLong_FromLong(i);
3518 Py_DECREF(single);
3519 }
3520 gettimeofday(&stop, NULL);
3521 print_delta(1, &start, &stop);
3522
3523 /* Test 2: Allocate and immediately deallocate
3524 many large integers */
3525 gettimeofday(&start, NULL);
3526 for(k=0; k < 20000; k++)
3527 for(i=0; i < 1000; i++) {
3528 single = PyLong_FromLong(i+1000000);
3529 Py_DECREF(single);
3530 }
3531 gettimeofday(&stop, NULL);
3532 print_delta(2, &start, &stop);
3533
3534 /* Test 3: Allocate a few integers, then release
3535 them all simultaneously. */
3536 multiple = malloc(sizeof(PyObject*) * 1000);
3537 if (multiple == NULL)
3538 return PyErr_NoMemory();
3539 gettimeofday(&start, NULL);
3540 for(k=0; k < 20000; k++) {
3541 for(i=0; i < 1000; i++) {
3542 multiple[i] = PyLong_FromLong(i+1000000);
3543 }
3544 for(i=0; i < 1000; i++) {
3545 Py_DECREF(multiple[i]);
3546 }
3547 }
3548 gettimeofday(&stop, NULL);
3549 print_delta(3, &start, &stop);
3550 free(multiple);
3551
3552 /* Test 4: Allocate many integers, then release
3553 them all simultaneously. */
3554 multiple = malloc(sizeof(PyObject*) * 1000000);
3555 if (multiple == NULL)
3556 return PyErr_NoMemory();
3557 gettimeofday(&start, NULL);
3558 for(k=0; k < 20; k++) {
3559 for(i=0; i < 1000000; i++) {
3560 multiple[i] = PyLong_FromLong(i+1000000);
3561 }
3562 for(i=0; i < 1000000; i++) {
3563 Py_DECREF(multiple[i]);
3564 }
3565 }
3566 gettimeofday(&stop, NULL);
3567 print_delta(4, &start, &stop);
3568 free(multiple);
3569
3570 /* Test 5: Allocate many integers < 32000 */
3571 multiple = malloc(sizeof(PyObject*) * 1000000);
3572 if (multiple == NULL)
3573 return PyErr_NoMemory();
3574 gettimeofday(&start, NULL);
3575 for(k=0; k < 10; k++) {
3576 for(i=0; i < 1000000; i++) {
3577 multiple[i] = PyLong_FromLong(i+1000);
3578 }
3579 for(i=0; i < 1000000; i++) {
3580 Py_DECREF(multiple[i]);
3581 }
3582 }
3583 gettimeofday(&stop, NULL);
3584 print_delta(5, &start, &stop);
3585 free(multiple);
3586
3587 /* Test 6: Perform small int addition */
3588 op1 = PyLong_FromLong(1);
3589 gettimeofday(&start, NULL);
3590 for(i=0; i < 10000000; i++) {
3591 result = PyNumber_Add(op1, op1);
3592 Py_DECREF(result);
3593 }
3594 gettimeofday(&stop, NULL);
3595 Py_DECREF(op1);
3596 print_delta(6, &start, &stop);
3597
3598 /* Test 7: Perform medium int addition */
3599 op1 = PyLong_FromLong(1000);
3600 if (op1 == NULL)
3601 return NULL;
3602 gettimeofday(&start, NULL);
3603 for(i=0; i < 10000000; i++) {
3604 result = PyNumber_Add(op1, op1);
3605 Py_XDECREF(result);
3606 }
3607 gettimeofday(&stop, NULL);
3608 Py_DECREF(op1);
3609 print_delta(7, &start, &stop);
3610
3611 Py_RETURN_NONE;
3612 }
3613 #endif
3614
3615 /* To test the format of tracebacks as printed out. */
3616 static PyObject *
3617 traceback_print(PyObject *self, PyObject *args)
3618 {
3619 PyObject *file;
3620 PyObject *traceback;
3621 int result;
3622
3623 if (!PyArg_ParseTuple(args, "OO:traceback_print",
3624 &traceback, &file))
3625 return NULL;
3626
3627 result = PyTraceBack_Print(traceback, file);
3628 if (result < 0)
3629 return NULL;
3630 Py_RETURN_NONE;
3631 }
3632
3633 /* To test the format of exceptions as printed out. */
3634 static PyObject *
3635 exception_print(PyObject *self, PyObject *args)
3636 {
3637 PyObject *value;
3638 PyObject *tb;
3639
3640 if (!PyArg_ParseTuple(args, "O:exception_print",
3641 &value)) {
3642 return NULL;
3643 }
3644
3645 if (PyExceptionInstance_Check(value)) {
3646 tb = PyException_GetTraceback(value);
3647 }
3648
3649 PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
3650 Py_XDECREF(tb);
3651
3652 Py_RETURN_NONE;
3653 }
3654
3655
3656
3657
3658 /* reliably raise a MemoryError */
3659 static PyObject *
3660 raise_memoryerror(PyObject *self, PyObject *Py_UNUSED(ignored))
3661 {
3662 PyErr_NoMemory();
3663 return NULL;
3664 }
3665
3666 /* Issue 6012 */
3667 static PyObject *str1, *str2;
3668 static int
3669 failing_converter(PyObject *obj, void *arg)
3670 {
3671 /* Clone str1, then let the conversion fail. */
3672 assert(str1);
3673 str2 = str1;
3674 Py_INCREF(str2);
3675 return 0;
3676 }
3677 static PyObject*
3678 argparsing(PyObject *o, PyObject *args)
3679 {
3680 PyObject *res;
3681 str1 = str2 = NULL;
3682 if (!PyArg_ParseTuple(args, "O&O&",
3683 PyUnicode_FSConverter, &str1,
3684 failing_converter, &str2)) {
3685 if (!str2)
3686 /* argument converter not called? */
3687 return NULL;
3688 /* Should be 1 */
3689 res = PyLong_FromSsize_t(Py_REFCNT(str2));
3690 Py_DECREF(str2);
3691 PyErr_Clear();
3692 return res;
3693 }
3694 Py_RETURN_NONE;
3695 }
3696
3697 /* To test that the result of PyCode_NewEmpty has the right members. */
3698 static PyObject *
3699 code_newempty(PyObject *self, PyObject *args)
3700 {
3701 const char *filename;
3702 const char *funcname;
3703 int firstlineno;
3704
3705 if (!PyArg_ParseTuple(args, "ssi:code_newempty",
3706 &filename, &funcname, &firstlineno))
3707 return NULL;
3708
3709 return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
3710 }
3711
3712 /* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
3713 Run via Lib/test/test_exceptions.py */
3714 static PyObject *
3715 make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
3716 {
3717 const char *name;
3718 const char *doc = NULL;
3719 PyObject *base = NULL;
3720 PyObject *dict = NULL;
3721
3722 static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
3723
3724 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3725 "s|sOO:make_exception_with_doc", kwlist,
3726 &name, &doc, &base, &dict))
3727 return NULL;
3728
3729 return PyErr_NewExceptionWithDoc(name, doc, base, dict);
3730 }
3731
3732 static PyObject *
3733 make_memoryview_from_NULL_pointer(PyObject *self, PyObject *Py_UNUSED(ignored))
3734 {
3735 Py_buffer info;
3736 if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
3737 return NULL;
3738 return PyMemoryView_FromBuffer(&info);
3739 }
3740
3741 static PyObject *
3742 test_from_contiguous(PyObject* self, PyObject *Py_UNUSED(ignored))
3743 {
3744 int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
3745 int init[5] = {0, 1, 2, 3, 4};
3746 Py_ssize_t itemsize = sizeof(int);
3747 Py_ssize_t shape = 5;
3748 Py_ssize_t strides = 2 * itemsize;
3749 Py_buffer view = {
3750 data,
3751 NULL,
3752 5 * itemsize,
3753 itemsize,
3754 1,
3755 1,
3756 NULL,
3757 &shape,
3758 &strides,
3759 NULL,
3760 NULL
3761 };
3762 int *ptr;
3763 int i;
3764
3765 PyBuffer_FromContiguous(&view, init, view.len, 'C');
3766 ptr = view.buf;
3767 for (i = 0; i < 5; i++) {
3768 if (ptr[2*i] != i) {
3769 PyErr_SetString(TestError,
3770 "test_from_contiguous: incorrect result");
3771 return NULL;
3772 }
3773 }
3774
3775 view.buf = &data[8];
3776 view.strides[0] = -2 * itemsize;
3777
3778 PyBuffer_FromContiguous(&view, init, view.len, 'C');
3779 ptr = view.buf;
3780 for (i = 0; i < 5; i++) {
3781 if (*(ptr-2*i) != i) {
3782 PyErr_SetString(TestError,
3783 "test_from_contiguous: incorrect result");
3784 return NULL;
3785 }
3786 }
3787
3788 Py_RETURN_NONE;
3789 }
3790
3791 #if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__) && !defined(PYPY_VERSION)
3792 extern PyTypeObject _PyBytesIOBuffer_Type;
3793
3794 static PyObject *
3795 test_pep3118_obsolete_write_locks(PyObject* self, PyObject *Py_UNUSED(ignored))
3796 {
3797 PyTypeObject *type = &_PyBytesIOBuffer_Type;
3798 PyObject *b;
3799 char *dummy[1];
3800 int ret, match;
3801
3802 /* PyBuffer_FillInfo() */
3803 ret = PyBuffer_FillInfo(NULL, NULL, dummy, 1, 0, PyBUF_SIMPLE);
3804 match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
3805 PyErr_Clear();
3806 if (ret != -1 || match == 0)
3807 goto error;
3808
3809 /* bytesiobuf_getbuffer() */
3810 b = type->tp_alloc(type, 0);
3811 if (b == NULL) {
3812 return NULL;
3813 }
3814
3815 ret = PyObject_GetBuffer(b, NULL, PyBUF_SIMPLE);
3816 Py_DECREF(b);
3817 match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
3818 PyErr_Clear();
3819 if (ret != -1 || match == 0)
3820 goto error;
3821
3822 Py_RETURN_NONE;
3823
3824 error:
3825 PyErr_SetString(TestError,
3826 "test_pep3118_obsolete_write_locks: failure");
3827 return NULL;
3828 }
3829 #endif
3830
3831 /* This tests functions that historically supported write locks. It is
3832 wrong to call getbuffer() with view==NULL and a compliant getbufferproc
3833 is entitled to segfault in that case. */
3834 static PyObject *
3835 getbuffer_with_null_view(PyObject* self, PyObject *obj)
3836 {
3837 if (PyObject_GetBuffer(obj, NULL, PyBUF_SIMPLE) < 0)
3838 return NULL;
3839
3840 Py_RETURN_NONE;
3841 }
3842
3843 #if !defined(PYPY_VERSION)
3844 /* PyBuffer_SizeFromFormat() */
3845 static PyObject *
3846 test_PyBuffer_SizeFromFormat(PyObject *self, PyObject *args)
3847 {
3848 const char *format;
3849 Py_ssize_t result;
3850
3851 if (!PyArg_ParseTuple(args, "s:test_PyBuffer_SizeFromFormat",
3852 &format)) {
3853 return NULL;
3854 }
3855
3856 result = PyBuffer_SizeFromFormat(format);
3857 if (result == -1) {
3858 return NULL;
3859 }
3860
3861 return PyLong_FromSsize_t(result);
3862 }
3863 #endif
3864
3865 /* Test that the fatal error from not having a current thread doesn't
3866 cause an infinite loop. Run via Lib/test/test_capi.py */
3867 static PyObject *
3868 crash_no_current_thread(PyObject *self, PyObject *Py_UNUSED(ignored))
3869 {
3870 Py_BEGIN_ALLOW_THREADS
3871 /* Using PyThreadState_Get() directly allows the test to pass in
3872 !pydebug mode. However, the test only actually tests anything
3873 in pydebug mode, since that's where the infinite loop was in
3874 the first place. */
3875 PyThreadState_Get();
3876 Py_END_ALLOW_THREADS
3877 return NULL;
3878 }
3879
3880 #ifndef PYPY_VERSION
3881
3882 /* To run some code in a sub-interpreter. */
3883 static PyObject *
3884 run_in_subinterp(PyObject *self, PyObject *args)
3885 {
3886 const char *code;
3887 int r;
3888 PyThreadState *substate, *mainstate;
3889 /* only initialise 'cflags.cf_flags' to test backwards compatibility */
3890 PyCompilerFlags cflags = {0};
3891
3892 if (!PyArg_ParseTuple(args, "s:run_in_subinterp",
3893 &code))
3894 return NULL;
3895
3896 mainstate = PyThreadState_Get();
3897
3898 PyThreadState_Swap(NULL);
3899
3900 substate = Py_NewInterpreter();
3901 if (substate == NULL) {
3902 /* Since no new thread state was created, there is no exception to
3903 propagate; raise a fresh one after swapping in the old thread
3904 state. */
3905 PyThreadState_Swap(mainstate);
3906 PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
3907 return NULL;
3908 }
3909 r = PyRun_SimpleStringFlags(code, &cflags);
3910 Py_EndInterpreter(substate);
3911
3912 PyThreadState_Swap(mainstate);
3913
3914 return PyLong_FromLong(r);
3915 }
3916
3917 #endif /* PYPY_VERSION */
3918
3919 static int
3920 check_time_rounding(int round)
3921 {
3922 if (round != _PyTime_ROUND_FLOOR
3923 && round != _PyTime_ROUND_CEILING
3924 && round != _PyTime_ROUND_HALF_EVEN
3925 && round != _PyTime_ROUND_UP) {
3926 PyErr_SetString(PyExc_ValueError, "invalid rounding");
3927 return -1;
3928 }
3929 return 0;
3930 }
3931
3932 static PyObject *
3933 test_pytime_object_to_time_t(PyObject *self, PyObject *args)
3934 {
3935 PyObject *obj;
3936 time_t sec;
3937 int round;
3938 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_time_t", &obj, &round))
3939 return NULL;
3940 if (check_time_rounding(round) < 0)
3941 return NULL;
3942 if (_PyTime_ObjectToTime_t(obj, &sec, round) == -1)
3943 return NULL;
3944 return _PyLong_FromTime_t(sec);
3945 }
3946
3947 static PyObject *
3948 test_pytime_object_to_timeval(PyObject *self, PyObject *args)
3949 {
3950 PyObject *obj;
3951 time_t sec;
3952 long usec;
3953 int round;
3954 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timeval", &obj, &round))
3955 return NULL;
3956 if (check_time_rounding(round) < 0)
3957 return NULL;
3958 if (_PyTime_ObjectToTimeval(obj, &sec, &usec, round) == -1)
3959 return NULL;
3960 return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), usec);
3961 }
3962
3963 static PyObject *
3964 test_pytime_object_to_timespec(PyObject *self, PyObject *args)
3965 {
3966 PyObject *obj;
3967 time_t sec;
3968 long nsec;
3969 int round;
3970 if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timespec", &obj, &round))
3971 return NULL;
3972 if (check_time_rounding(round) < 0)
3973 return NULL;
3974 if (_PyTime_ObjectToTimespec(obj, &sec, &nsec, round) == -1)
3975 return NULL;
3976 return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), nsec);
3977 }
3978
3979
3980 #ifndef PYPY_VERSION
3981
3982 static void
3983 slot_tp_del(PyObject *self)
3984 {
3985 _Py_IDENTIFIER(__tp_del__);
3986 PyObject *del, *res;
3987 PyObject *error_type, *error_value, *error_traceback;
3988
3989 /* Temporarily resurrect the object. */
3990 assert(Py_REFCNT(self) == 0);
3991 Py_SET_REFCNT(self, 1);
3992
3993 /* Save the current exception, if any. */
3994 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3995
3996 /* Execute __del__ method, if any. */
3997 del = _PyObject_LookupSpecialId(self, &PyId___tp_del__);
3998 if (del != NULL) {
3999 res = PyObject_CallNoArgs(del);
4000 if (res == NULL)
4001 PyErr_WriteUnraisable(del);
4002 else
4003 Py_DECREF(res);
4004 Py_DECREF(del);
4005 }
4006
4007 /* Restore the saved exception. */
4008 PyErr_Restore(error_type, error_value, error_traceback);
4009
4010 /* Undo the temporary resurrection; can't use DECREF here, it would
4011 * cause a recursive call.
4012 */
4013 assert(Py_REFCNT(self) > 0);
4014 Py_SET_REFCNT(self, Py_REFCNT(self) - 1);
4015 if (Py_REFCNT(self) == 0) {
4016 /* this is the normal path out */
4017 return;
4018 }
4019
4020 /* __del__ resurrected it! Make it look like the original Py_DECREF
4021 * never happened.
4022 */
4023 {
4024 Py_ssize_t refcnt = Py_REFCNT(self);
4025 _Py_NewReference(self);
4026 Py_SET_REFCNT(self, refcnt);
4027 }
4028 assert(!PyType_IS_GC(Py_TYPE(self)) || PyObject_GC_IsTracked(self));
4029 /* If Py_REF_DEBUG macro is defined, _Py_NewReference() increased
4030 _Py_RefTotal, so we need to undo that. */
4031 #ifdef Py_REF_DEBUG
4032 _Py_RefTotal--;
4033 #endif
4034 }
4035
4036 static PyObject *
4037 with_tp_del(PyObject *self, PyObject *args)
4038 {
4039 PyObject *obj;
4040 PyTypeObject *tp;
4041
4042 if (!PyArg_ParseTuple(args, "O:with_tp_del", &obj))
4043 return NULL;
4044 tp = (PyTypeObject *) obj;
4045 if (!PyType_Check(obj) || !PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) {
4046 PyErr_Format(PyExc_TypeError,
4047 "heap type expected, got %R", obj);
4048 return NULL;
4049 }
4050 tp->tp_del = slot_tp_del;
4051 Py_INCREF(obj);
4052 return obj;
4053 }
4054
4055 #endif
4056
4057 static PyObject *
4058 without_gc(PyObject *Py_UNUSED(self), PyObject *obj)
4059 {
4060 PyTypeObject *tp = (PyTypeObject*)obj;
4061 if (!PyType_Check(obj) || !PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) {
4062 return PyErr_Format(PyExc_TypeError, "heap type expected, got %R", obj);
4063 }
4064 if (PyType_IS_GC(tp)) {
4065 // Don't try this at home, kids:
4066 tp->tp_flags -= Py_TPFLAGS_HAVE_GC;
4067 tp->tp_free = PyObject_Del;
4068 tp->tp_traverse = NULL;
4069 tp->tp_clear = NULL;
4070 }
4071 assert(!PyType_IS_GC(tp));
4072 Py_INCREF(obj);
4073 return obj;
4074 }
4075
4076 static PyMethodDef ml;
4077
4078 static PyObject *
4079 create_cfunction(PyObject *self, PyObject *args)
4080 {
4081 return PyCFunction_NewEx(&ml, self, NULL);
4082 }
4083
4084 static PyMethodDef ml = {
4085 "create_cfunction",
4086 create_cfunction,
4087 METH_NOARGS,
4088 NULL
4089 };
4090
4091 static PyObject *
4092 _test_incref(PyObject *ob)
4093 {
4094 Py_INCREF(ob);
4095 return ob;
4096 }
4097
4098 static PyObject *
4099 test_xincref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
4100 {
4101 PyObject *obj = PyLong_FromLong(0);
4102 Py_XINCREF(_test_incref(obj));
4103 Py_DECREF(obj);
4104 Py_DECREF(obj);
4105 Py_DECREF(obj);
4106 Py_RETURN_NONE;
4107 }
4108
4109 static PyObject *
4110 test_incref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
4111 {
4112 PyObject *obj = PyLong_FromLong(0);
4113 Py_INCREF(_test_incref(obj));
4114 Py_DECREF(obj);
4115 Py_DECREF(obj);
4116 Py_DECREF(obj);
4117 Py_RETURN_NONE;
4118 }
4119
4120 static PyObject *
4121 test_xdecref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
4122 {
4123 Py_XDECREF(PyLong_FromLong(0));
4124 Py_RETURN_NONE;
4125 }
4126
4127 static PyObject *
4128 test_decref_doesnt_leak(PyObject *ob, PyObject *Py_UNUSED(ignored))
4129 {
4130 Py_DECREF(PyLong_FromLong(0));
4131 Py_RETURN_NONE;
4132 }
4133
4134 #ifndef PYPY_VERSION
4135
4136 static PyObject *
4137 test_structseq_newtype_doesnt_leak(PyObject *Py_UNUSED(self),
4138 PyObject *Py_UNUSED(args))
4139 {
4140 PyStructSequence_Desc descr;
4141 PyStructSequence_Field descr_fields[3];
4142
4143 descr_fields[0] = (PyStructSequence_Field){"foo", "foo value"};
4144 descr_fields[1] = (PyStructSequence_Field){NULL, "some hidden value"};
4145 descr_fields[2] = (PyStructSequence_Field){0, NULL};
4146
4147 descr.name = "_testcapi.test_descr";
4148 descr.doc = "This is used to test for memory leaks in NewType";
4149 descr.fields = descr_fields;
4150 descr.n_in_sequence = 1;
4151
4152 PyTypeObject* structseq_type = PyStructSequence_NewType(&descr);
4153 assert(structseq_type != NULL);
4154 assert(PyType_Check(structseq_type));
4155 assert(PyType_FastSubclass(structseq_type, Py_TPFLAGS_TUPLE_SUBCLASS));
4156 Py_DECREF(structseq_type);
4157
4158 Py_RETURN_NONE;
4159 }
4160
4161 #endif
4162
4163 static PyObject *
4164 test_structseq_newtype_null_descr_doc(PyObject *Py_UNUSED(self),
4165 PyObject *Py_UNUSED(args))
4166 {
4167 PyStructSequence_Field descr_fields[1] = {
4168 (PyStructSequence_Field){NULL, NULL}
4169 };
4170 // Test specifically for NULL .doc field.
4171 PyStructSequence_Desc descr = {"_testcapi.test_descr", NULL, &descr_fields[0], 0};
4172
4173 PyTypeObject* structseq_type = PyStructSequence_NewType(&descr);
4174 assert(structseq_type != NULL);
4175 assert(PyType_Check(structseq_type));
4176 assert(PyType_FastSubclass(structseq_type, Py_TPFLAGS_TUPLE_SUBCLASS));
4177 Py_DECREF(structseq_type);
4178
4179 Py_RETURN_NONE;
4180 }
4181
4182 static PyObject *
4183 test_incref_decref_API(PyObject *ob, PyObject *Py_UNUSED(ignored))
4184 {
4185 PyObject *obj = PyLong_FromLong(0);
4186 Py_IncRef(obj);
4187 Py_DecRef(obj);
4188 Py_DecRef(obj);
4189 Py_RETURN_NONE;
4190 }
4191
4192 static PyObject *
4193 test_pymem_alloc0(PyObject *self, PyObject *Py_UNUSED(ignored))
4194 {
4195 void *ptr;
4196
4197 ptr = PyMem_RawMalloc(0);
4198 if (ptr == NULL) {
4199 PyErr_SetString(PyExc_RuntimeError, "PyMem_RawMalloc(0) returns NULL");
4200 return NULL;
4201 }
4202 PyMem_RawFree(ptr);
4203
4204 ptr = PyMem_RawCalloc(0, 0);
4205 if (ptr == NULL) {
4206 PyErr_SetString(PyExc_RuntimeError, "PyMem_RawCalloc(0, 0) returns NULL");
4207 return NULL;
4208 }
4209 PyMem_RawFree(ptr);
4210
4211 ptr = PyMem_Malloc(0);
4212 if (ptr == NULL) {
4213 PyErr_SetString(PyExc_RuntimeError, "PyMem_Malloc(0) returns NULL");
4214 return NULL;
4215 }
4216 PyMem_Free(ptr);
4217
4218 ptr = PyMem_Calloc(0, 0);
4219 if (ptr == NULL) {
4220 PyErr_SetString(PyExc_RuntimeError, "PyMem_Calloc(0, 0) returns NULL");
4221 return NULL;
4222 }
4223 PyMem_Free(ptr);
4224
4225 ptr = PyObject_Malloc(0);
4226 if (ptr == NULL) {
4227 PyErr_SetString(PyExc_RuntimeError, "PyObject_Malloc(0) returns NULL");
4228 return NULL;
4229 }
4230 PyObject_Free(ptr);
4231
4232 ptr = PyObject_Calloc(0, 0);
4233 if (ptr == NULL) {
4234 PyErr_SetString(PyExc_RuntimeError, "PyObject_Calloc(0, 0) returns NULL");
4235 return NULL;
4236 }
4237 PyObject_Free(ptr);
4238
4239 Py_RETURN_NONE;
4240 }
4241
4242 #ifndef PYPY_VERSION
4243
4244 typedef struct {
4245 PyMemAllocatorEx alloc;
4246
4247 size_t malloc_size;
4248 size_t calloc_nelem;
4249 size_t calloc_elsize;
4250 void *realloc_ptr;
4251 size_t realloc_new_size;
4252 void *free_ptr;
4253 void *ctx;
4254 } alloc_hook_t;
4255
4256 static void* hook_malloc(void* ctx, size_t size)
4257 {
4258 alloc_hook_t *hook = (alloc_hook_t *)ctx;
4259 hook->ctx = ctx;
4260 hook->malloc_size = size;
4261 return hook->alloc.malloc(hook->alloc.ctx, size);
4262 }
4263
4264 static void* hook_calloc(void* ctx, size_t nelem, size_t elsize)
4265 {
4266 alloc_hook_t *hook = (alloc_hook_t *)ctx;
4267 hook->ctx = ctx;
4268 hook->calloc_nelem = nelem;
4269 hook->calloc_elsize = elsize;
4270 return hook->alloc.calloc(hook->alloc.ctx, nelem, elsize);
4271 }
4272
4273 static void* hook_realloc(void* ctx, void* ptr, size_t new_size)
4274 {
4275 alloc_hook_t *hook = (alloc_hook_t *)ctx;
4276 hook->ctx = ctx;
4277 hook->realloc_ptr = ptr;
4278 hook->realloc_new_size = new_size;
4279 return hook->alloc.realloc(hook->alloc.ctx, ptr, new_size);
4280 }
4281
4282 static void hook_free(void *ctx, void *ptr)
4283 {
4284 alloc_hook_t *hook = (alloc_hook_t *)ctx;
4285 hook->ctx = ctx;
4286 hook->free_ptr = ptr;
4287 hook->alloc.free(hook->alloc.ctx, ptr);
4288 }
4289
4290 static PyObject *
4291 test_setallocators(PyMemAllocatorDomain domain)
4292 {
4293 PyObject *res = NULL;
4294 const char *error_msg;
4295 alloc_hook_t hook;
4296 PyMemAllocatorEx alloc;
4297 size_t size, size2, nelem, elsize;
4298 void *ptr, *ptr2;
4299
4300 memset(&hook, 0, sizeof(hook));
4301
4302 alloc.ctx = &hook;
4303 alloc.malloc = &hook_malloc;
4304 alloc.calloc = &hook_calloc;
4305 alloc.realloc = &hook_realloc;
4306 alloc.free = &hook_free;
4307 PyMem_GetAllocator(domain, &hook.alloc);
4308 PyMem_SetAllocator(domain, &alloc);
4309
4310 /* malloc, realloc, free */
4311 size = 42;
4312 hook.ctx = NULL;
4313 switch(domain)
4314 {
4315 case PYMEM_DOMAIN_RAW: ptr = PyMem_RawMalloc(size); break;
4316 case PYMEM_DOMAIN_MEM: ptr = PyMem_Malloc(size); break;
4317 case PYMEM_DOMAIN_OBJ: ptr = PyObject_Malloc(size); break;
4318 default: ptr = NULL; break;
4319 }
4320
4321 #define CHECK_CTX(FUNC) \
4322 if (hook.ctx != &hook) { \
4323 error_msg = FUNC " wrong context"; \
4324 goto fail; \
4325 } \
4326 hook.ctx = NULL; /* reset for next check */
4327
4328 if (ptr == NULL) {
4329 error_msg = "malloc failed";
4330 goto fail;
4331 }
4332 CHECK_CTX("malloc");
4333 if (hook.malloc_size != size) {
4334 error_msg = "malloc invalid size";
4335 goto fail;
4336 }
4337
4338 size2 = 200;
4339 switch(domain)
4340 {
4341 case PYMEM_DOMAIN_RAW: ptr2 = PyMem_RawRealloc(ptr, size2); break;
4342 case PYMEM_DOMAIN_MEM: ptr2 = PyMem_Realloc(ptr, size2); break;
4343 case PYMEM_DOMAIN_OBJ: ptr2 = PyObject_Realloc(ptr, size2); break;
4344 default: ptr2 = NULL; break;
4345 }
4346
4347 if (ptr2 == NULL) {
4348 error_msg = "realloc failed";
4349 goto fail;
4350 }
4351 CHECK_CTX("realloc");
4352 if (hook.realloc_ptr != ptr
4353 || hook.realloc_new_size != size2) {
4354 error_msg = "realloc invalid parameters";
4355 goto fail;
4356 }
4357
4358 switch(domain)
4359 {
4360 case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr2); break;
4361 case PYMEM_DOMAIN_MEM: PyMem_Free(ptr2); break;
4362 case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr2); break;
4363 }
4364
4365 CHECK_CTX("free");
4366 if (hook.free_ptr != ptr2) {
4367 error_msg = "free invalid pointer";
4368 goto fail;
4369 }
4370
4371 /* calloc, free */
4372 nelem = 2;
4373 elsize = 5;
4374 switch(domain)
4375 {
4376 case PYMEM_DOMAIN_RAW: ptr = PyMem_RawCalloc(nelem, elsize); break;
4377 case PYMEM_DOMAIN_MEM: ptr = PyMem_Calloc(nelem, elsize); break;
4378 case PYMEM_DOMAIN_OBJ: ptr = PyObject_Calloc(nelem, elsize); break;
4379 default: ptr = NULL; break;
4380 }
4381
4382 if (ptr == NULL) {
4383 error_msg = "calloc failed";
4384 goto fail;
4385 }
4386 CHECK_CTX("calloc");
4387 if (hook.calloc_nelem != nelem || hook.calloc_elsize != elsize) {
4388 error_msg = "calloc invalid nelem or elsize";
4389 goto fail;
4390 }
4391
4392 hook.free_ptr = NULL;
4393 switch(domain)
4394 {
4395 case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr); break;
4396 case PYMEM_DOMAIN_MEM: PyMem_Free(ptr); break;
4397 case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr); break;
4398 }
4399
4400 CHECK_CTX("calloc free");
4401 if (hook.free_ptr != ptr) {
4402 error_msg = "calloc free invalid pointer";
4403 goto fail;
4404 }
4405
4406 Py_INCREF(Py_None);
4407 res = Py_None;
4408 goto finally;
4409
4410 fail:
4411 PyErr_SetString(PyExc_RuntimeError, error_msg);
4412
4413 finally:
4414 PyMem_SetAllocator(domain, &hook.alloc);
4415 return res;
4416
4417 #undef CHECK_CTX
4418 }
4419
4420 static PyObject *
4421 test_pymem_setrawallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
4422 {
4423 return test_setallocators(PYMEM_DOMAIN_RAW);
4424 }
4425
4426 static PyObject *
4427 test_pymem_setallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
4428 {
4429 return test_setallocators(PYMEM_DOMAIN_MEM);
4430 }
4431
4432 static PyObject *
4433 test_pyobject_setallocators(PyObject *self, PyObject *Py_UNUSED(ignored))
4434 {
4435 return test_setallocators(PYMEM_DOMAIN_OBJ);
4436 }
4437
4438 /* Most part of the following code is inherited from the pyfailmalloc project
4439 * written by Victor Stinner. */
4440 static struct {
4441 int installed;
4442 PyMemAllocatorEx raw;
4443 PyMemAllocatorEx mem;
4444 PyMemAllocatorEx obj;
4445 } FmHook;
4446
4447 static struct {
4448 int start;
4449 int stop;
4450 Py_ssize_t count;
4451 } FmData;
4452
4453 static int
4454 fm_nomemory(void)
4455 {
4456 FmData.count++;
4457 if (FmData.count > FmData.start &&
4458 (FmData.stop <= 0 || FmData.count <= FmData.stop)) {
4459 return 1;
4460 }
4461 return 0;
4462 }
4463
4464 static void *
4465 hook_fmalloc(void *ctx, size_t size)
4466 {
4467 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4468 if (fm_nomemory()) {
4469 return NULL;
4470 }
4471 return alloc->malloc(alloc->ctx, size);
4472 }
4473
4474 static void *
4475 hook_fcalloc(void *ctx, size_t nelem, size_t elsize)
4476 {
4477 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4478 if (fm_nomemory()) {
4479 return NULL;
4480 }
4481 return alloc->calloc(alloc->ctx, nelem, elsize);
4482 }
4483
4484 static void *
4485 hook_frealloc(void *ctx, void *ptr, size_t new_size)
4486 {
4487 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4488 if (fm_nomemory()) {
4489 return NULL;
4490 }
4491 return alloc->realloc(alloc->ctx, ptr, new_size);
4492 }
4493
4494 static void
4495 hook_ffree(void *ctx, void *ptr)
4496 {
4497 PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
4498 alloc->free(alloc->ctx, ptr);
4499 }
4500
4501 static void
4502 fm_setup_hooks(void)
4503 {
4504 PyMemAllocatorEx alloc;
4505
4506 if (FmHook.installed) {
4507 return;
4508 }
4509 FmHook.installed = 1;
4510
4511 alloc.malloc = hook_fmalloc;
4512 alloc.calloc = hook_fcalloc;
4513 alloc.realloc = hook_frealloc;
4514 alloc.free = hook_ffree;
4515 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &FmHook.raw);
4516 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &FmHook.mem);
4517 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &FmHook.obj);
4518
4519 alloc.ctx = &FmHook.raw;
4520 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
4521
4522 alloc.ctx = &FmHook.mem;
4523 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
4524
4525 alloc.ctx = &FmHook.obj;
4526 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
4527 }
4528
4529 static void
4530 fm_remove_hooks(void)
4531 {
4532 if (FmHook.installed) {
4533 FmHook.installed = 0;
4534 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &FmHook.raw);
4535 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &FmHook.mem);
4536 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &FmHook.obj);
4537 }
4538 }
4539
4540 static PyObject*
4541 set_nomemory(PyObject *self, PyObject *args)
4542 {
4543 /* Memory allocation fails after 'start' allocation requests, and until
4544 * 'stop' allocation requests except when 'stop' is negative or equal
4545 * to 0 (default) in which case allocation failures never stop. */
4546 FmData.count = 0;
4547 FmData.stop = 0;
4548 if (!PyArg_ParseTuple(args, "i|i", &FmData.start, &FmData.stop)) {
4549 return NULL;
4550 }
4551 fm_setup_hooks();
4552 Py_RETURN_NONE;
4553 }
4554
4555 static PyObject*
4556 remove_mem_hooks(PyObject *self, PyObject *Py_UNUSED(ignored))
4557 {
4558 fm_remove_hooks();
4559 Py_RETURN_NONE;
4560 }
4561
4562 #endif // ifndef PYPY_VERSION
4563
4564
4565 PyDoc_STRVAR(docstring_empty,
4566 ""
4567 );
4568
4569 PyDoc_STRVAR(docstring_no_signature,
4570 "This docstring has no signature."
4571 );
4572
4573 PyDoc_STRVAR(docstring_with_invalid_signature,
4574 "docstring_with_invalid_signature($module, /, boo)\n"
4575 "\n"
4576 "This docstring has an invalid signature."
4577 );
4578
4579 PyDoc_STRVAR(docstring_with_invalid_signature2,
4580 "docstring_with_invalid_signature2($module, /, boo)\n"
4581 "\n"
4582 "--\n"
4583 "\n"
4584 "This docstring also has an invalid signature."
4585 );
4586
4587 PyDoc_STRVAR(docstring_with_signature,
4588 "docstring_with_signature($module, /, sig)\n"
4589 "--\n"
4590 "\n"
4591 "This docstring has a valid signature."
4592 );
4593
4594 PyDoc_STRVAR(docstring_with_signature_but_no_doc,
4595 "docstring_with_signature_but_no_doc($module, /, sig)\n"
4596 "--\n"
4597 "\n"
4598 );
4599
4600 PyDoc_STRVAR(docstring_with_signature_and_extra_newlines,
4601 "docstring_with_signature_and_extra_newlines($module, /, parameter)\n"
4602 "--\n"
4603 "\n"
4604 "\n"
4605 "This docstring has a valid signature and some extra newlines."
4606 );
4607
4608 PyDoc_STRVAR(docstring_with_signature_with_defaults,
4609 "docstring_with_signature_with_defaults(module, s='avocado',\n"
4610 " b=b'bytes', d=3.14, i=35, n=None, t=True, f=False,\n"
4611 " local=the_number_three, sys=sys.maxsize,\n"
4612 " exp=sys.maxsize - 1)\n"
4613 "--\n"
4614 "\n"
4615 "\n"
4616 "\n"
4617 "This docstring has a valid signature with parameters,\n"
4618 "and the parameters take defaults of varying types."
4619 );
4620
4621 typedef struct {
4622 PyThread_type_lock start_event;
4623 PyThread_type_lock exit_event;
4624 PyObject *callback;
4625 } test_c_thread_t;
4626
4627 static void
4628 temporary_c_thread(void *data)
4629 {
4630 test_c_thread_t *test_c_thread = data;
4631 PyGILState_STATE state;
4632 PyObject *res;
4633
4634 PyThread_release_lock(test_c_thread->start_event);
4635
4636 /* Allocate a Python thread state for this thread */
4637 state = PyGILState_Ensure();
4638
4639 res = PyObject_CallNoArgs(test_c_thread->callback);
4640 Py_CLEAR(test_c_thread->callback);
4641
4642 if (res == NULL) {
4643 PyErr_Print();
4644 }
4645 else {
4646 Py_DECREF(res);
4647 }
4648
4649 /* Destroy the Python thread state for this thread */
4650 PyGILState_Release(state);
4651
4652 PyThread_release_lock(test_c_thread->exit_event);
4653 }
4654
4655 static test_c_thread_t test_c_thread;
4656
4657 static PyObject *
4658 call_in_temporary_c_thread(PyObject *self, PyObject *args)
4659 {
4660 PyObject *res = NULL;
4661 PyObject *callback = NULL;
4662 long thread;
4663 int wait = 1;
4664 if (!PyArg_ParseTuple(args, "O|i", &callback, &wait))
4665 {
4666 return NULL;
4667 }
4668
4669 test_c_thread.start_event = PyThread_allocate_lock();
4670 test_c_thread.exit_event = PyThread_allocate_lock();
4671 test_c_thread.callback = NULL;
4672 if (!test_c_thread.start_event || !test_c_thread.exit_event) {
4673 PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
4674 goto exit;
4675 }
4676
4677 test_c_thread.callback = Py_NewRef(callback);
4678
4679 PyThread_acquire_lock(test_c_thread.start_event, 1);
4680 PyThread_acquire_lock(test_c_thread.exit_event, 1);
4681
4682 thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
4683 if (thread == -1) {
4684 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
4685 PyThread_release_lock(test_c_thread.start_event);
4686 PyThread_release_lock(test_c_thread.exit_event);
4687 goto exit;
4688 }
4689
4690 PyThread_acquire_lock(test_c_thread.start_event, 1);
4691 PyThread_release_lock(test_c_thread.start_event);
4692
4693 if (!wait) {
4694 Py_RETURN_NONE;
4695 }
4696
4697 Py_BEGIN_ALLOW_THREADS
4698 PyThread_acquire_lock(test_c_thread.exit_event, 1);
4699 PyThread_release_lock(test_c_thread.exit_event);
4700 Py_END_ALLOW_THREADS
4701
4702 res = Py_NewRef(Py_None);
4703
4704 exit:
4705 Py_CLEAR(test_c_thread.callback);
4706 if (test_c_thread.start_event) {
4707 PyThread_free_lock(test_c_thread.start_event);
4708 test_c_thread.start_event = NULL;
4709 }
4710 if (test_c_thread.exit_event) {
4711 PyThread_free_lock(test_c_thread.exit_event);
4712 test_c_thread.exit_event = NULL;
4713 }
4714 return res;
4715 }
4716
4717 static PyObject *
4718 join_temporary_c_thread(PyObject *self, PyObject *Py_UNUSED(ignored))
4719 {
4720 Py_BEGIN_ALLOW_THREADS
4721 PyThread_acquire_lock(test_c_thread.exit_event, 1);
4722 PyThread_release_lock(test_c_thread.exit_event);
4723 Py_END_ALLOW_THREADS
4724 Py_CLEAR(test_c_thread.callback);
4725 PyThread_free_lock(test_c_thread.start_event);
4726 test_c_thread.start_event = NULL;
4727 PyThread_free_lock(test_c_thread.exit_event);
4728 test_c_thread.exit_event = NULL;
4729 Py_RETURN_NONE;
4730 }
4731
4732 /* marshal */
4733
4734 #ifndef PYPY_VERSION
4735
4736 static PyObject*
4737 pymarshal_write_long_to_file(PyObject* self, PyObject *args)
4738 {
4739 long value;
4740 PyObject *filename;
4741 int version;
4742 FILE *fp;
4743
4744 if (!PyArg_ParseTuple(args, "lOi:pymarshal_write_long_to_file",
4745 &value, &filename, &version))
4746 return NULL;
4747
4748 fp = _Py_fopen_obj(filename, "wb");
4749 if (fp == NULL) {
4750 PyErr_SetFromErrno(PyExc_OSError);
4751 return NULL;
4752 }
4753
4754 PyMarshal_WriteLongToFile(value, fp, version);
4755 assert(!PyErr_Occurred());
4756
4757 fclose(fp);
4758 Py_RETURN_NONE;
4759 }
4760
4761 static PyObject*
4762 pymarshal_write_object_to_file(PyObject* self, PyObject *args)
4763 {
4764 PyObject *obj;
4765 PyObject *filename;
4766 int version;
4767 FILE *fp;
4768
4769 if (!PyArg_ParseTuple(args, "OOi:pymarshal_write_object_to_file",
4770 &obj, &filename, &version))
4771 return NULL;
4772
4773 fp = _Py_fopen_obj(filename, "wb");
4774 if (fp == NULL) {
4775 PyErr_SetFromErrno(PyExc_OSError);
4776 return NULL;
4777 }
4778
4779 PyMarshal_WriteObjectToFile(obj, fp, version);
4780 assert(!PyErr_Occurred());
4781
4782 fclose(fp);
4783 Py_RETURN_NONE;
4784 }
4785
4786 static PyObject*
4787 pymarshal_read_short_from_file(PyObject* self, PyObject *args)
4788 {
4789 int value;
4790 long pos;
4791 PyObject *filename;
4792 FILE *fp;
4793
4794 if (!PyArg_ParseTuple(args, "O:pymarshal_read_short_from_file", &filename))
4795 return NULL;
4796
4797 fp = _Py_fopen_obj(filename, "rb");
4798 if (fp == NULL) {
4799 PyErr_SetFromErrno(PyExc_OSError);
4800 return NULL;
4801 }
4802
4803 value = PyMarshal_ReadShortFromFile(fp);
4804 pos = ftell(fp);
4805
4806 fclose(fp);
4807 if (PyErr_Occurred())
4808 return NULL;
4809 return Py_BuildValue("il", value, pos);
4810 }
4811
4812 static PyObject*
4813 pymarshal_read_long_from_file(PyObject* self, PyObject *args)
4814 {
4815 long value, pos;
4816 PyObject *filename;
4817 FILE *fp;
4818
4819 if (!PyArg_ParseTuple(args, "O:pymarshal_read_long_from_file", &filename))
4820 return NULL;
4821
4822 fp = _Py_fopen_obj(filename, "rb");
4823 if (fp == NULL) {
4824 PyErr_SetFromErrno(PyExc_OSError);
4825 return NULL;
4826 }
4827
4828 value = PyMarshal_ReadLongFromFile(fp);
4829 pos = ftell(fp);
4830
4831 fclose(fp);
4832 if (PyErr_Occurred())
4833 return NULL;
4834 return Py_BuildValue("ll", value, pos);
4835 }
4836
4837 static PyObject*
4838 pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
4839 {
4840 PyObject *filename;
4841 if (!PyArg_ParseTuple(args, "O:pymarshal_read_last_object_from_file", &filename))
4842 return NULL;
4843
4844 FILE *fp = _Py_fopen_obj(filename, "rb");
4845 if (fp == NULL) {
4846 PyErr_SetFromErrno(PyExc_OSError);
4847 return NULL;
4848 }
4849
4850 PyObject *obj = PyMarshal_ReadLastObjectFromFile(fp);
4851 long pos = ftell(fp);
4852
4853 fclose(fp);
4854 if (obj == NULL) {
4855 return NULL;
4856 }
4857 return Py_BuildValue("Nl", obj, pos);
4858 }
4859
4860 static PyObject*
4861 pymarshal_read_object_from_file(PyObject* self, PyObject *args)
4862 {
4863 PyObject *filename;
4864 if (!PyArg_ParseTuple(args, "O:pymarshal_read_object_from_file", &filename))
4865 return NULL;
4866
4867 FILE *fp = _Py_fopen_obj(filename, "rb");
4868 if (fp == NULL) {
4869 PyErr_SetFromErrno(PyExc_OSError);
4870 return NULL;
4871 }
4872
4873 PyObject *obj = PyMarshal_ReadObjectFromFile(fp);
4874 long pos = ftell(fp);
4875
4876 fclose(fp);
4877 if (obj == NULL) {
4878 return NULL;
4879 }
4880 return Py_BuildValue("Nl", obj, pos);
4881 }
4882
4883 #endif // ifndef PYPY_VERSION
4884
4885 static PyObject*
4886 return_null_without_error(PyObject *self, PyObject *args)
4887 {
4888 /* invalid call: return NULL without setting an error,
4889 * _Py_CheckFunctionResult() must detect such bug at runtime. */
4890 PyErr_Clear();
4891 return NULL;
4892 }
4893
4894 static PyObject*
4895 return_result_with_error(PyObject *self, PyObject *args)
4896 {
4897 /* invalid call: return a result with an error set,
4898 * _Py_CheckFunctionResult() must detect such bug at runtime. */
4899 PyErr_SetNone(PyExc_ValueError);
4900 Py_RETURN_NONE;
4901 }
4902
4903 static PyObject*
4904 getitem_with_error(PyObject *self, PyObject *args)
4905 {
4906 PyObject *map, *key;
4907 if (!PyArg_ParseTuple(args, "OO", &map, &key)) {
4908 return NULL;
4909 }
4910
4911 PyErr_SetString(PyExc_ValueError, "bug");
4912 return PyObject_GetItem(map, key);
4913 }
4914
4915 static PyObject *
4916 test_pytime_fromseconds(PyObject *self, PyObject *args)
4917 {
4918 int seconds;
4919 if (!PyArg_ParseTuple(args, "i", &seconds)) {
4920 return NULL;
4921 }
4922 _PyTime_t ts = _PyTime_FromSeconds(seconds);
4923 return _PyTime_AsNanosecondsObject(ts);
4924 }
4925
4926 static PyObject *
4927 test_pytime_fromsecondsobject(PyObject *self, PyObject *args)
4928 {
4929 PyObject *obj;
4930 int round;
4931 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
4932 return NULL;
4933 }
4934 if (check_time_rounding(round) < 0) {
4935 return NULL;
4936 }
4937 _PyTime_t ts;
4938 if (_PyTime_FromSecondsObject(&ts, obj, round) == -1) {
4939 return NULL;
4940 }
4941 return _PyTime_AsNanosecondsObject(ts);
4942 }
4943
4944 static PyObject *
4945 test_pytime_assecondsdouble(PyObject *self, PyObject *args)
4946 {
4947 PyObject *obj;
4948 if (!PyArg_ParseTuple(args, "O", &obj)) {
4949 return NULL;
4950 }
4951 _PyTime_t ts;
4952 if (_PyTime_FromNanosecondsObject(&ts, obj) < 0) {
4953 return NULL;
4954 }
4955 double d = _PyTime_AsSecondsDouble(ts);
4956 return PyFloat_FromDouble(d);
4957 }
4958
4959 static PyObject *
4960 test_PyTime_AsTimeval(PyObject *self, PyObject *args)
4961 {
4962 PyObject *obj;
4963 int round;
4964 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
4965 return NULL;
4966 }
4967 if (check_time_rounding(round) < 0) {
4968 return NULL;
4969 }
4970 _PyTime_t t;
4971 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
4972 return NULL;
4973 }
4974 struct timeval tv;
4975 if (_PyTime_AsTimeval(t, &tv, round) < 0) {
4976 return NULL;
4977 }
4978
4979 PyObject *seconds = PyLong_FromLongLong(tv.tv_sec);
4980 if (seconds == NULL) {
4981 return NULL;
4982 }
4983 return Py_BuildValue("Nl", seconds, (long)tv.tv_usec);
4984 }
4985
4986 static PyObject *
4987 test_PyTime_AsTimeval_clamp(PyObject *self, PyObject *args)
4988 {
4989 PyObject *obj;
4990 int round;
4991 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
4992 return NULL;
4993 }
4994 if (check_time_rounding(round) < 0) {
4995 return NULL;
4996 }
4997 _PyTime_t t;
4998 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
4999 return NULL;
5000 }
5001 struct timeval tv;
5002 _PyTime_AsTimeval_clamp(t, &tv, round);
5003
5004 PyObject *seconds = PyLong_FromLongLong(tv.tv_sec);
5005 if (seconds == NULL) {
5006 return NULL;
5007 }
5008 return Py_BuildValue("Nl", seconds, (long)tv.tv_usec);
5009 }
5010
5011 #ifdef HAVE_CLOCK_GETTIME
5012 static PyObject *
5013 test_PyTime_AsTimespec(PyObject *self, PyObject *args)
5014 {
5015 PyObject *obj;
5016 if (!PyArg_ParseTuple(args, "O", &obj)) {
5017 return NULL;
5018 }
5019 _PyTime_t t;
5020 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
5021 return NULL;
5022 }
5023 struct timespec ts;
5024 if (_PyTime_AsTimespec(t, &ts) == -1) {
5025 return NULL;
5026 }
5027 return Py_BuildValue("Nl", _PyLong_FromTime_t(ts.tv_sec), ts.tv_nsec);
5028 }
5029
5030 static PyObject *
5031 test_PyTime_AsTimespec_clamp(PyObject *self, PyObject *args)
5032 {
5033 PyObject *obj;
5034 if (!PyArg_ParseTuple(args, "O", &obj)) {
5035 return NULL;
5036 }
5037 _PyTime_t t;
5038 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
5039 return NULL;
5040 }
5041 struct timespec ts;
5042 _PyTime_AsTimespec_clamp(t, &ts);
5043 return Py_BuildValue("Nl", _PyLong_FromTime_t(ts.tv_sec), ts.tv_nsec);
5044 }
5045 #endif
5046
5047 static PyObject *
5048 test_PyTime_AsMilliseconds(PyObject *self, PyObject *args)
5049 {
5050 PyObject *obj;
5051 int round;
5052 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
5053 return NULL;
5054 }
5055 _PyTime_t t;
5056 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
5057 return NULL;
5058 }
5059 if (check_time_rounding(round) < 0) {
5060 return NULL;
5061 }
5062 _PyTime_t ms = _PyTime_AsMilliseconds(t, round);
5063 _PyTime_t ns = _PyTime_FromNanoseconds(ms);
5064 return _PyTime_AsNanosecondsObject(ns);
5065 }
5066
5067 static PyObject *
5068 test_PyTime_AsMicroseconds(PyObject *self, PyObject *args)
5069 {
5070 PyObject *obj;
5071 int round;
5072 if (!PyArg_ParseTuple(args, "Oi", &obj, &round)) {
5073 return NULL;
5074 }
5075 _PyTime_t t;
5076 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
5077 return NULL;
5078 }
5079 if (check_time_rounding(round) < 0) {
5080 return NULL;
5081 }
5082 _PyTime_t us = _PyTime_AsMicroseconds(t, round);
5083 _PyTime_t ns = _PyTime_FromNanoseconds(us);
5084 return _PyTime_AsNanosecondsObject(ns);
5085 }
5086
5087 static PyObject*
5088 pymem_buffer_overflow(PyObject *self, PyObject *args)
5089 {
5090 char *buffer;
5091
5092 /* Deliberate buffer overflow to check that PyMem_Free() detects
5093 the overflow when debug hooks are installed. */
5094 buffer = PyMem_Malloc(16);
5095 if (buffer == NULL) {
5096 PyErr_NoMemory();
5097 return NULL;
5098 }
5099 buffer[16] = 'x';
5100 PyMem_Free(buffer);
5101
5102 Py_RETURN_NONE;
5103 }
5104
5105 static PyObject*
5106 pymem_api_misuse(PyObject *self, PyObject *args)
5107 {
5108 char *buffer;
5109
5110 /* Deliberate misusage of Python allocators:
5111 allococate with PyMem but release with PyMem_Raw. */
5112 buffer = PyMem_Malloc(16);
5113 PyMem_RawFree(buffer);
5114
5115 Py_RETURN_NONE;
5116 }
5117
5118 static PyObject*
5119 pymem_malloc_without_gil(PyObject *self, PyObject *args)
5120 {
5121 char *buffer;
5122
5123 /* Deliberate bug to test debug hooks on Python memory allocators:
5124 call PyMem_Malloc() without holding the GIL */
5125 Py_BEGIN_ALLOW_THREADS
5126 buffer = PyMem_Malloc(10);
5127 Py_END_ALLOW_THREADS
5128
5129 PyMem_Free(buffer);
5130
5131 Py_RETURN_NONE;
5132 }
5133
5134 #ifndef PYPY_VERSION
5135 static PyObject*
5136 test_pymem_getallocatorsname(PyObject *self, PyObject *args)
5137 {
5138 const char *name = _PyMem_GetCurrentAllocatorName();
5139 if (name == NULL) {
5140 PyErr_SetString(PyExc_RuntimeError, "cannot get allocators name");
5141 return NULL;
5142 }
5143 return PyUnicode_FromString(name);
5144 }
5145 #endif
5146
5147
5148 static PyObject*
5149 test_pyobject_is_freed(const char *test_name, PyObject *op)
5150 {
5151 #ifndef PYPY_VERSION
5152 if (!_PyObject_IsFreed(op)) {
5153 return raiseTestError(test_name, "object is not seen as freed");
5154 }
5155 #endif
5156 Py_RETURN_NONE;
5157 }
5158
5159
5160 static PyObject*
5161 check_pyobject_null_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
5162 {
5163 PyObject *op = NULL;
5164 return test_pyobject_is_freed("check_pyobject_null_is_freed", op);
5165 }
5166
5167
5168 static PyObject*
5169 check_pyobject_uninitialized_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
5170 {
5171 PyObject *op = (PyObject *)PyObject_Malloc(sizeof(PyObject));
5172 if (op == NULL) {
5173 return NULL;
5174 }
5175 /* Initialize reference count to avoid early crash in ceval or GC */
5176 Py_SET_REFCNT(op, 1);
5177 /* object fields like ob_type are uninitialized! */
5178 return test_pyobject_is_freed("check_pyobject_uninitialized_is_freed", op);
5179 }
5180
5181
5182 static PyObject*
5183 check_pyobject_forbidden_bytes_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
5184 {
5185 /* Allocate an incomplete PyObject structure: truncate 'ob_type' field */
5186 PyObject *op = (PyObject *)PyObject_Malloc(offsetof(PyObject, ob_type));
5187 if (op == NULL) {
5188 return NULL;
5189 }
5190 /* Initialize reference count to avoid early crash in ceval or GC */
5191 Py_SET_REFCNT(op, 1);
5192 /* ob_type field is after the memory block: part of "forbidden bytes"
5193 when using debug hooks on memory allocators! */
5194 return test_pyobject_is_freed("check_pyobject_forbidden_bytes_is_freed", op);
5195 }
5196
5197
5198 static PyObject*
5199 check_pyobject_freed_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
5200 {
5201 /* This test would fail if run with the address sanitizer */
5202 #ifdef _Py_ADDRESS_SANITIZER
5203 Py_RETURN_NONE;
5204 #else
5205 PyObject *op = PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
5206 if (op == NULL) {
5207 return NULL;
5208 }
5209 Py_TYPE(op)->tp_dealloc(op);
5210 /* Reset reference count to avoid early crash in ceval or GC */
5211 Py_SET_REFCNT(op, 1);
5212 /* object memory is freed! */
5213 return test_pyobject_is_freed("check_pyobject_freed_is_freed", op);
5214 #endif
5215 }
5216
5217
5218 #ifndef PYPY_VERSION
5219 static PyObject*
5220 pyobject_malloc_without_gil(PyObject *self, PyObject *args)
5221 {
5222 char *buffer;
5223
5224 /* Deliberate bug to test debug hooks on Python memory allocators:
5225 call PyObject_Malloc() without holding the GIL */
5226 Py_BEGIN_ALLOW_THREADS
5227 buffer = PyObject_Malloc(10);
5228 Py_END_ALLOW_THREADS
5229
5230 PyObject_Free(buffer);
5231 exit(-1); // PyPy does not implement memory management hooks
5232
5233 Py_RETURN_NONE;
5234 }
5235 #endif
5236
5237 static PyObject *
5238 tracemalloc_track(PyObject *self, PyObject *args)
5239 {
5240 unsigned int domain;
5241 PyObject *ptr_obj;
5242 void *ptr;
5243 Py_ssize_t size;
5244 int release_gil = 0;
5245 int res;
5246
5247 if (!PyArg_ParseTuple(args, "IOn|i", &domain, &ptr_obj, &size, &release_gil))
5248 return NULL;
5249 ptr = PyLong_AsVoidPtr(ptr_obj);
5250 if (PyErr_Occurred())
5251 return NULL;
5252
5253 if (release_gil) {
5254 Py_BEGIN_ALLOW_THREADS
5255 res = PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
5256 Py_END_ALLOW_THREADS
5257 }
5258 else {
5259 res = PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
5260 }
5261
5262 if (res < 0) {
5263 PyErr_SetString(PyExc_RuntimeError, "PyTraceMalloc_Track error");
5264 return NULL;
5265 }
5266
5267 Py_RETURN_NONE;
5268 }
5269
5270 static PyObject *
5271 tracemalloc_untrack(PyObject *self, PyObject *args)
5272 {
5273 unsigned int domain;
5274 PyObject *ptr_obj;
5275 void *ptr;
5276 int res;
5277
5278 if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
5279 return NULL;
5280 ptr = PyLong_AsVoidPtr(ptr_obj);
5281 if (PyErr_Occurred())
5282 return NULL;
5283
5284 res = PyTraceMalloc_Untrack(domain, (uintptr_t)ptr);
5285 if (res < 0) {
5286 PyErr_SetString(PyExc_RuntimeError, "PyTraceMalloc_Untrack error");
5287 return NULL;
5288 }
5289
5290 Py_RETURN_NONE;
5291 }
5292
5293 #ifndef PYPY_VERSION
5294 static PyObject *
5295 tracemalloc_get_traceback(PyObject *self, PyObject *args)
5296 {
5297 unsigned int domain;
5298 PyObject *ptr_obj;
5299 void *ptr;
5300
5301 if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
5302 return NULL;
5303 ptr = PyLong_AsVoidPtr(ptr_obj);
5304 if (PyErr_Occurred())
5305 return NULL;
5306
5307 return _PyTraceMalloc_GetTraceback(domain, (uintptr_t)ptr);
5308 }
5309
5310 static PyObject *
5311 dict_get_version(PyObject *self, PyObject *args)
5312 {
5313 PyDictObject *dict;
5314 uint64_t version;
5315
5316 if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
5317 return NULL;
5318
5319 version = dict->ma_version_tag;
5320
5321 static_assert(sizeof(unsigned long long) >= sizeof(version),
5322 "version is larger than unsigned long long");
5323 return PyLong_FromUnsignedLongLong((unsigned long long)version);
5324 }
5325
5326
5327 static PyObject *
5328 raise_SIGINT_then_send_None(PyObject *self, PyObject *args)
5329 {
5330 _Py_IDENTIFIER(send);
5331 PyGenObject *gen;
5332
5333 if (!PyArg_ParseTuple(args, "O!", &PyGen_Type, &gen))
5334 return NULL;
5335
5336 /* This is used in a test to check what happens if a signal arrives just
5337 as we're in the process of entering a yield from chain (see
5338 bpo-30039).
5339
5340 Needs to be done in C, because:
5341 - we don't have a Python wrapper for raise()
5342 - we need to make sure that the Python-level signal handler doesn't run
5343 *before* we enter the generator frame, which is impossible in Python
5344 because we check for signals before every bytecode operation.
5345 */
5346 raise(SIGINT);
5347 return _PyObject_CallMethodIdOneArg((PyObject *)gen, &PyId_send, Py_None);
5348 }
5349 #endif // ifndef PYPY_VERSION
5350
5351
5352 static int
5353 fastcall_args(PyObject *args, PyObject ***stack, Py_ssize_t *nargs)
5354 {
5355 if (args == Py_None) {
5356 *stack = NULL;
5357 *nargs = 0;
5358 }
5359 else if (PyTuple_Check(args)) {
5360 *stack = ((PyTupleObject *)args)->ob_item;
5361 *nargs = PyTuple_GET_SIZE(args);
5362 }
5363 else {
5364 PyErr_SetString(PyExc_TypeError, "args must be None or a tuple");
5365 return -1;
5366 }
5367 return 0;
5368 }
5369
5370
5371 static PyObject *
5372 test_pyobject_fastcall(PyObject *self, PyObject *args)
5373 {
5374 PyObject *func, *func_args;
5375 PyObject **stack;
5376 Py_ssize_t nargs;
5377
5378 if (!PyArg_ParseTuple(args, "OO", &func, &func_args)) {
5379 return NULL;
5380 }
5381
5382 if (fastcall_args(func_args, &stack, &nargs) < 0) {
5383 return NULL;
5384 }
5385 return _PyObject_FastCall(func, stack, nargs);
5386 }
5387
5388
5389 static PyObject *
5390 test_pyobject_fastcalldict(PyObject *self, PyObject *args)
5391 {
5392 PyObject *func, *func_args, *kwargs;
5393 PyObject **stack;
5394 Py_ssize_t nargs;
5395
5396 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwargs)) {
5397 return NULL;
5398 }
5399
5400 if (fastcall_args(func_args, &stack, &nargs) < 0) {
5401 return NULL;
5402 }
5403
5404 if (kwargs == Py_None) {
5405 kwargs = NULL;
5406 }
5407 else if (!PyDict_Check(kwargs)) {
5408 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a dict");
5409 return NULL;
5410 }
5411
5412 return PyObject_VectorcallDict(func, stack, nargs, kwargs);
5413 }
5414
5415
5416 static PyObject *
5417 test_pyobject_vectorcall(PyObject *self, PyObject *args)
5418 {
5419 PyObject *func, *func_args, *kwnames = NULL;
5420 PyObject **stack;
5421 Py_ssize_t nargs, nkw;
5422
5423 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwnames)) {
5424 return NULL;
5425 }
5426
5427 if (fastcall_args(func_args, &stack, &nargs) < 0) {
5428 return NULL;
5429 }
5430
5431 if (kwnames == Py_None) {
5432 kwnames = NULL;
5433 }
5434 else if (PyTuple_Check(kwnames)) {
5435 nkw = PyTuple_GET_SIZE(kwnames);
5436 if (nargs < nkw) {
5437 PyErr_SetString(PyExc_ValueError, "kwnames longer than args");
5438 return NULL;
5439 }
5440 nargs -= nkw;
5441 }
5442 else {
5443 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a tuple");
5444 return NULL;
5445 }
5446 return PyObject_Vectorcall(func, stack, nargs, kwnames);
5447 }
5448
5449
5450 static PyObject *
5451 test_pyvectorcall_call(PyObject *self, PyObject *args)
5452 {
5453 PyObject *func;
5454 PyObject *argstuple;
5455 PyObject *kwargs = NULL;
5456
5457 if (!PyArg_ParseTuple(args, "OO|O", &func, &argstuple, &kwargs)) {
5458 return NULL;
5459 }
5460
5461 if (!PyTuple_Check(argstuple)) {
5462 PyErr_SetString(PyExc_TypeError, "args must be a tuple");
5463 return NULL;
5464 }
5465 if (kwargs != NULL && !PyDict_Check(kwargs)) {
5466 PyErr_SetString(PyExc_TypeError, "kwargs must be a dict");
5467 return NULL;
5468 }
5469
5470 return PyVectorcall_Call(func, argstuple, kwargs);
5471 }
5472
5473
5474 static PyObject*
5475 stack_pointer(PyObject *self, PyObject *args)
5476 {
5477 int v = 5;
5478 return PyLong_FromVoidPtr(&v);
5479 }
5480
5481
5482 #ifdef W_STOPCODE
5483 static PyObject*
5484 py_w_stopcode(PyObject *self, PyObject *args)
5485 {
5486 int sig, status;
5487 if (!PyArg_ParseTuple(args, "i", &sig)) {
5488 return NULL;
5489 }
5490 status = W_STOPCODE(sig);
5491 return PyLong_FromLong(status);
5492 }
5493 #endif
5494
5495
5496 static PyObject *
5497 get_mapping_keys(PyObject* self, PyObject *obj)
5498 {
5499 return PyMapping_Keys(obj);
5500 }
5501
5502 static PyObject *
5503 get_mapping_values(PyObject* self, PyObject *obj)
5504 {
5505 return PyMapping_Values(obj);
5506 }
5507
5508 static PyObject *
5509 get_mapping_items(PyObject* self, PyObject *obj)
5510 {
5511 return PyMapping_Items(obj);
5512 }
5513
5514 static PyObject *
5515 test_mapping_has_key_string(PyObject *self, PyObject *Py_UNUSED(args))
5516 {
5517 PyObject *context = PyDict_New();
5518 PyObject *val = PyLong_FromLong(1);
5519
5520 // Since this uses `const char*` it is easier to test this in C:
5521 PyDict_SetItemString(context, "a", val);
5522 if (!PyMapping_HasKeyString(context, "a")) {
5523 PyErr_SetString(PyExc_RuntimeError,
5524 "Existing mapping key does not exist");
5525 return NULL;
5526 }
5527 if (PyMapping_HasKeyString(context, "b")) {
5528 PyErr_SetString(PyExc_RuntimeError,
5529 "Missing mapping key exists");
5530 return NULL;
5531 }
5532
5533 Py_DECREF(val);
5534 Py_DECREF(context);
5535 Py_RETURN_NONE;
5536 }
5537
5538 static PyObject *
5539 mapping_has_key(PyObject* self, PyObject *args)
5540 {
5541 PyObject *context, *key;
5542 if (!PyArg_ParseTuple(args, "OO", &context, &key)) {
5543 return NULL;
5544 }
5545 return PyLong_FromLong(PyMapping_HasKey(context, key));
5546 }
5547
5548 static PyObject *
5549 sequence_set_slice(PyObject* self, PyObject *args)
5550 {
5551 PyObject *sequence, *obj;
5552 Py_ssize_t i1, i2;
5553 if (!PyArg_ParseTuple(args, "OnnO", &sequence, &i1, &i2, &obj)) {
5554 return NULL;
5555 }
5556
5557 int res = PySequence_SetSlice(sequence, i1, i2, obj);
5558 if (res == -1) {
5559 return NULL;
5560 }
5561 Py_RETURN_NONE;
5562 }
5563
5564 static PyObject *
5565 sequence_del_slice(PyObject* self, PyObject *args)
5566 {
5567 PyObject *sequence;
5568 Py_ssize_t i1, i2;
5569 if (!PyArg_ParseTuple(args, "Onn", &sequence, &i1, &i2)) {
5570 return NULL;
5571 }
5572
5573 int res = PySequence_DelSlice(sequence, i1, i2);
5574 if (res == -1) {
5575 return NULL;
5576 }
5577 Py_RETURN_NONE;
5578 }
5579
5580 static PyObject *
5581 test_pythread_tss_key_state(PyObject *self, PyObject *args)
5582 {
5583 Py_tss_t tss_key = Py_tss_NEEDS_INIT;
5584 if (PyThread_tss_is_created(&tss_key)) {
5585 return raiseTestError("test_pythread_tss_key_state",
5586 "TSS key not in an uninitialized state at "
5587 "creation time");
5588 }
5589 if (PyThread_tss_create(&tss_key) != 0) {
5590 PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_create failed");
5591 return NULL;
5592 }
5593 if (!PyThread_tss_is_created(&tss_key)) {
5594 return raiseTestError("test_pythread_tss_key_state",
5595 "PyThread_tss_create succeeded, "
5596 "but with TSS key in an uninitialized state");
5597 }
5598 if (PyThread_tss_create(&tss_key) != 0) {
5599 return raiseTestError("test_pythread_tss_key_state",
5600 "PyThread_tss_create unsuccessful with "
5601 "an already initialized key");
5602 }
5603 #define CHECK_TSS_API(expr) \
5604 (void)(expr); \
5605 if (!PyThread_tss_is_created(&tss_key)) { \
5606 return raiseTestError("test_pythread_tss_key_state", \
5607 "TSS key initialization state was not " \
5608 "preserved after calling " #expr); }
5609 CHECK_TSS_API(PyThread_tss_set(&tss_key, NULL));
5610 CHECK_TSS_API(PyThread_tss_get(&tss_key));
5611 #undef CHECK_TSS_API
5612 PyThread_tss_delete(&tss_key);
5613 if (PyThread_tss_is_created(&tss_key)) {
5614 return raiseTestError("test_pythread_tss_key_state",
5615 "PyThread_tss_delete called, but did not "
5616 "set the key state to uninitialized");
5617 }
5618
5619 Py_tss_t *ptr_key = PyThread_tss_alloc();
5620 if (ptr_key == NULL) {
5621 PyErr_SetString(PyExc_RuntimeError, "PyThread_tss_alloc failed");
5622 return NULL;
5623 }
5624 if (PyThread_tss_is_created(ptr_key)) {
5625 return raiseTestError("test_pythread_tss_key_state",
5626 "TSS key not in an uninitialized state at "
5627 "allocation time");
5628 }
5629 PyThread_tss_free(ptr_key);
5630 ptr_key = NULL;
5631 Py_RETURN_NONE;
5632 }
5633
5634
5635 #ifndef PYPY_VERSION
5636 static PyObject*
5637 new_hamt(PyObject *self, PyObject *args)
5638 {
5639 return _PyContext_NewHamtForTests();
5640 }
5641 #endif
5642
5643 /* def bad_get(self, obj, cls):
5644 cls()
5645 return repr(self)
5646 */
5647 static PyObject*
5648 bad_get(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
5649 {
5650 PyObject *self, *obj, *cls;
5651 if (!_PyArg_UnpackStack(args, nargs, "bad_get", 3, 3, &self, &obj, &cls)) {
5652 return NULL;
5653 }
5654
5655 PyObject *res = PyObject_CallNoArgs(cls);
5656 if (res == NULL) {
5657 return NULL;
5658 }
5659 Py_DECREF(res);
5660
5661 return PyObject_Repr(self);
5662 }
5663
5664
5665 #ifdef Py_REF_DEBUG
5666 static PyObject *
5667 negative_refcount(PyObject *self, PyObject *Py_UNUSED(args))
5668 {
5669 PyObject *obj = PyUnicode_FromString("negative_refcount");
5670 if (obj == NULL) {
5671 return NULL;
5672 }
5673 assert(Py_REFCNT(obj) == 1);
5674
5675 Py_SET_REFCNT(obj, 0);
5676 /* Py_DECREF() must call _Py_NegativeRefcount() and abort Python */
5677 Py_DECREF(obj);
5678
5679 Py_RETURN_NONE;
5680 }
5681 #endif
5682
5683
5684 static PyObject*
5685 test_write_unraisable_exc(PyObject *self, PyObject *args)
5686 {
5687 PyObject *exc, *err_msg, *obj;
5688 if (!PyArg_ParseTuple(args, "OOO", &exc, &err_msg, &obj)) {
5689 return NULL;
5690 }
5691
5692 const char *err_msg_utf8;
5693 if (err_msg != Py_None) {
5694 err_msg_utf8 = PyUnicode_AsUTF8(err_msg);
5695 if (err_msg_utf8 == NULL) {
5696 return NULL;
5697 }
5698 }
5699 else {
5700 err_msg_utf8 = NULL;
5701 }
5702
5703 PyErr_SetObject((PyObject *)Py_TYPE(exc), exc);
5704 _PyErr_WriteUnraisableMsg(err_msg_utf8, obj);
5705 Py_RETURN_NONE;
5706 }
5707
5708
5709 static PyObject *
5710 sequence_getitem(PyObject *self, PyObject *args)
5711 {
5712 PyObject *seq;
5713 Py_ssize_t i;
5714 if (!PyArg_ParseTuple(args, "On", &seq, &i)) {
5715 return NULL;
5716 }
5717 return PySequence_GetItem(seq, i);
5718 }
5719
5720
5721 static PyObject *
5722 sequence_setitem(PyObject *self, PyObject *args)
5723 {
5724 Py_ssize_t i;
5725 PyObject *seq, *val;
5726 if (!PyArg_ParseTuple(args, "OnO", &seq, &i, &val)) {
5727 return NULL;
5728 }
5729 if (PySequence_SetItem(seq, i, val)) {
5730 return NULL;
5731 }
5732 Py_RETURN_NONE;
5733 }
5734
5735
5736 /* Functions for testing C calling conventions (METH_*) are named meth_*,
5737 * e.g. "meth_varargs" for METH_VARARGS.
5738 *
5739 * They all return a tuple of their C-level arguments, with None instead
5740 * of NULL and Python tuples instead of C arrays.
5741 */
5742
5743
5744 static PyObject*
5745 _null_to_none(PyObject* obj)
5746 {
5747 if (obj == NULL) {
5748 Py_RETURN_NONE;
5749 }
5750 Py_INCREF(obj);
5751 return obj;
5752 }
5753
5754 static PyObject*
5755 meth_varargs(PyObject* self, PyObject* args)
5756 {
5757 return Py_BuildValue("NO", _null_to_none(self), args);
5758 }
5759
5760 static PyObject*
5761 meth_varargs_keywords(PyObject* self, PyObject* args, PyObject* kwargs)
5762 {
5763 return Py_BuildValue("NON", _null_to_none(self), args, _null_to_none(kwargs));
5764 }
5765
5766 static PyObject*
5767 meth_o(PyObject* self, PyObject* obj)
5768 {
5769 return Py_BuildValue("NO", _null_to_none(self), obj);
5770 }
5771
5772 static PyObject*
5773 meth_noargs(PyObject* self, PyObject* ignored)
5774 {
5775 return _null_to_none(self);
5776 }
5777
5778 static PyObject*
5779 _fastcall_to_tuple(PyObject* const* args, Py_ssize_t nargs)
5780 {
5781 PyObject *tuple = PyTuple_New(nargs);
5782 if (tuple == NULL) {
5783 return NULL;
5784 }
5785 for (Py_ssize_t i=0; i < nargs; i++) {
5786 Py_INCREF(args[i]);
5787 PyTuple_SET_ITEM(tuple, i, args[i]);
5788 }
5789 return tuple;
5790 }
5791
5792 static PyObject*
5793 meth_fastcall(PyObject* self, PyObject* const* args, Py_ssize_t nargs)
5794 {
5795 return Py_BuildValue(
5796 "NN", _null_to_none(self), _fastcall_to_tuple(args, nargs)
5797 );
5798 }
5799
5800 static PyObject*
5801 meth_fastcall_keywords(PyObject* self, PyObject* const* args,
5802 Py_ssize_t nargs, PyObject* kwargs)
5803 {
5804 PyObject *pyargs = _fastcall_to_tuple(args, nargs);
5805 if (pyargs == NULL) {
5806 return NULL;
5807 }
5808 assert(args != NULL || nargs == 0);
5809 PyObject* const* args_offset = args == NULL ? NULL : args + nargs;
5810 PyObject *pykwargs = PyObject_Vectorcall((PyObject*)&PyDict_Type,
5811 args_offset, 0, kwargs);
5812 return Py_BuildValue("NNN", _null_to_none(self), pyargs, pykwargs);
5813 }
5814
5815
5816 static PyObject*
5817 pynumber_tobase(PyObject *module, PyObject *args)
5818 {
5819 PyObject *obj;
5820 int base;
5821 if (!PyArg_ParseTuple(args, "Oi:pynumber_tobase",
5822 &obj, &base)) {
5823 return NULL;
5824 }
5825 return PyNumber_ToBase(obj, base);
5826 }
5827
5828
5829 static PyObject*
5830 test_set_type_size(PyObject *self, PyObject *Py_UNUSED(ignored))
5831 {
5832 PyObject *obj = PyList_New(0);
5833 if (obj == NULL) {
5834 return NULL;
5835 }
5836
5837 // Ensure that following tests don't modify the object,
5838 // to ensure that Py_DECREF() will not crash.
5839 assert(Py_TYPE(obj) == &PyList_Type);
5840 assert(Py_SIZE(obj) == 0);
5841
5842 // bpo-39573: Test Py_SET_TYPE() and Py_SET_SIZE() functions.
5843 Py_SET_TYPE(obj, &PyList_Type);
5844 Py_SET_SIZE(obj, 0);
5845
5846 Py_DECREF(obj);
5847 Py_RETURN_NONE;
5848 }
5849
5850 #ifdef PYPY_VERSION
5851 #define TEST_REFCOUNT() Py_RETURN_NONE;
5852 #else
5853 #define TEST_REFCOUNT() \
5854 do { \
5855 PyObject *obj = PyList_New(0); \
5856 if (obj == NULL) { \
5857 return NULL; \
5858 } \
5859 assert(Py_REFCNT(obj) == 1); \
5860 \
5861 /* test Py_NewRef() */ \
5862 PyObject *ref = Py_NewRef(obj); \
5863 assert(ref == obj); \
5864 assert(Py_REFCNT(obj) == 2); \
5865 Py_DECREF(ref); \
5866 \
5867 /* test Py_XNewRef() */ \
5868 PyObject *xref = Py_XNewRef(obj); \
5869 assert(xref == obj); \
5870 assert(Py_REFCNT(obj) == 2); \
5871 Py_DECREF(xref); \
5872 \
5873 assert(Py_XNewRef(NULL) == NULL); \
5874 \
5875 Py_DECREF(obj); \
5876 Py_RETURN_NONE; \
5877 } while (0)
5878 #endif
5879
5880 // Test Py_NewRef() and Py_XNewRef() macros
5881 static PyObject*
5882 test_refcount_macros(PyObject *self, PyObject *Py_UNUSED(ignored))
5883 {
5884 TEST_REFCOUNT();
5885 }
5886
5887 #ifndef PYPY_VERSION
5888 // PyPy does not support the stable ABI
5889 #undef Py_NewRef
5890 #undef Py_XNewRef
5891 #endif
5892
5893 // Test Py_NewRef() and Py_XNewRef() functions, after undefining macros.
5894 static PyObject*
5895 test_refcount_funcs(PyObject *self, PyObject *Py_UNUSED(ignored))
5896 {
5897 TEST_REFCOUNT();
5898 }
5899
5900
5901 // Test Py_Is() function
5902 #define TEST_PY_IS() \
5903 do { \
5904 PyObject *o_none = Py_None; \
5905 PyObject *o_true = Py_True; \
5906 PyObject *o_false = Py_False; \
5907 PyObject *obj = PyList_New(0); \
5908 if (obj == NULL) { \
5909 return NULL; \
5910 } \
5911 \
5912 /* test Py_Is() */ \
5913 assert(Py_Is(obj, obj)); \
5914 assert(!Py_Is(obj, o_none)); \
5915 \
5916 /* test Py_None */ \
5917 assert(Py_Is(o_none, o_none)); \
5918 assert(!Py_Is(obj, o_none)); \
5919 \
5920 /* test Py_True */ \
5921 assert(Py_Is(o_true, o_true)); \
5922 assert(!Py_Is(o_false, o_true)); \
5923 assert(!Py_Is(obj, o_true)); \
5924 \
5925 /* test Py_False */ \
5926 assert(Py_Is(o_false, o_false)); \
5927 assert(!Py_Is(o_true, o_false)); \
5928 assert(!Py_Is(obj, o_false)); \
5929 \
5930 Py_DECREF(obj); \
5931 Py_RETURN_NONE; \
5932 } while (0)
5933
5934 // Test Py_Is() macro
5935 static PyObject*
5936 test_py_is_macros(PyObject *self, PyObject *Py_UNUSED(ignored))
5937 {
5938 TEST_PY_IS();
5939 }
5940
5941 #ifndef PYPY_VERSION
5942 // PyPy does not support the stable ABI
5943 #undef Py_Is
5944 #endif
5945
5946 // Test Py_Is() function, after undefining its macro.
5947 static PyObject*
5948 test_py_is_funcs(PyObject *self, PyObject *Py_UNUSED(ignored))
5949 {
5950 TEST_PY_IS();
5951 }
5952
5953
5954 static PyObject *
5955 test_fatal_error(PyObject *self, PyObject *args)
5956 {
5957 char *message;
5958 int release_gil = 0;
5959 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
5960 return NULL;
5961 if (release_gil) {
5962 Py_BEGIN_ALLOW_THREADS
5963 Py_FatalError(message);
5964 Py_END_ALLOW_THREADS
5965 }
5966 else {
5967 Py_FatalError(message);
5968 }
5969 // Py_FatalError() does not return, but exits the process.
5970 Py_RETURN_NONE;
5971 }
5972
5973 // type->tp_version_tag
5974 static PyObject *
5975 type_get_version(PyObject *self, PyObject *type)
5976 {
5977 if (!PyType_Check(type)) {
5978 PyErr_SetString(PyExc_TypeError, "argument must be a type");
5979 return NULL;
5980 }
5981 PyObject *res = PyLong_FromUnsignedLong(
5982 ((PyTypeObject *)type)->tp_version_tag);
5983 if (res == NULL) {
5984 assert(PyErr_Occurred());
5985 return NULL;
5986 }
5987 return res;
5988 }
5989
5990 static PyObject *
5991 type_modified(PyObject *self, PyObject *type)
5992 {
5993 if (!PyType_Check(type)) {
5994 PyErr_SetString(PyExc_TypeError, "argument must be a type");
5995 return NULL;
5996 }
5997 PyType_Modified((PyTypeObject *)type);
5998 Py_RETURN_NONE;
5999 }
6000
6001 // Circumvents standard version assignment machinery - use with caution and only on
6002 // short-lived heap types
6003 static PyObject *
6004 type_assign_specific_version_unsafe(PyObject *self, PyObject *args)
6005 {
6006 PyTypeObject *type;
6007 unsigned int version;
6008 if (!PyArg_ParseTuple(args, "Oi:type_assign_specific_version_unsafe", &type, &version)) {
6009 return NULL;
6010 }
6011 assert(!PyType_HasFeature(type, Py_TPFLAGS_IMMUTABLETYPE));
6012 type->tp_version_tag = version;
6013 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
6014 Py_RETURN_NONE;
6015 }
6016
6017 // Test PyThreadState C API
6018 static PyObject *
6019 test_tstate_capi(PyObject *self, PyObject *Py_UNUSED(args))
6020 {
6021 // PyThreadState_Get()
6022 PyThreadState *tstate = PyThreadState_Get();
6023 assert(tstate != NULL);
6024
6025 // PyThreadState_GET()
6026 PyThreadState *tstate2 = PyThreadState_Get();
6027 assert(tstate2 == tstate);
6028
6029 // private _PyThreadState_UncheckedGet()
6030 PyThreadState *tstate3 = _PyThreadState_UncheckedGet();
6031 assert(tstate3 == tstate);
6032
6033 // PyThreadState_EnterTracing(), PyThreadState_LeaveTracing()
6034 PyThreadState_EnterTracing(tstate);
6035 PyThreadState_LeaveTracing(tstate);
6036
6037 // PyThreadState_GetDict(): no tstate argument
6038 PyObject *dict = PyThreadState_GetDict();
6039 // PyThreadState_GetDict() API can return NULL if PyDict_New() fails,
6040 // but it should not occur in practice.
6041 assert(dict != NULL);
6042 assert(PyDict_Check(dict));
6043 // dict is a borrowed reference
6044
6045 // private _PyThreadState_GetDict()
6046 PyObject *dict2 = _PyThreadState_GetDict(tstate);
6047 assert(dict2 == dict);
6048 // dict2 is a borrowed reference
6049
6050 // PyThreadState_GetInterpreter()
6051 PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
6052 assert(interp != NULL);
6053
6054 // PyThreadState_GetFrame()
6055 PyFrameObject*frame = PyThreadState_GetFrame(tstate);
6056 assert(frame != NULL);
6057 assert(PyFrame_Check(frame));
6058 Py_DECREF(frame);
6059
6060 // PyThreadState_GetID()
6061 uint64_t id = PyThreadState_GetID(tstate);
6062 assert(id >= 1);
6063
6064 Py_RETURN_NONE;
6065 }
6066
6067
6068 // Test PyFloat_Pack2(), PyFloat_Pack4() and PyFloat_Pack8()
6069 static PyObject *
6070 test_float_pack(PyObject *self, PyObject *args)
6071 {
6072 int size;
6073 double d;
6074 int le;
6075 if (!PyArg_ParseTuple(args, "idi", &size, &d, &le)) {
6076 return NULL;
6077 }
6078 switch (size)
6079 {
6080 case 2:
6081 {
6082 char data[2];
6083 if (PyFloat_Pack2(d, data, le) < 0) {
6084 return NULL;
6085 }
6086 return PyBytes_FromStringAndSize(data, Py_ARRAY_LENGTH(data));
6087 }
6088 case 4:
6089 {
6090 char data[4];
6091 if (PyFloat_Pack4(d, data, le) < 0) {
6092 return NULL;
6093 }
6094 return PyBytes_FromStringAndSize(data, Py_ARRAY_LENGTH(data));
6095 }
6096 case 8:
6097 {
6098 char data[8];
6099 if (PyFloat_Pack8(d, data, le) < 0) {
6100 return NULL;
6101 }
6102 return PyBytes_FromStringAndSize(data, Py_ARRAY_LENGTH(data));
6103 }
6104 default: break;
6105 }
6106
6107 PyErr_SetString(PyExc_ValueError, "size must 2, 4 or 8");
6108 return NULL;
6109 }
6110
6111
6112 // Test PyFloat_Unpack2(), PyFloat_Unpack4() and PyFloat_Unpack8()
6113 static PyObject *
6114 test_float_unpack(PyObject *self, PyObject *args)
6115 {
6116 assert(!PyErr_Occurred());
6117 const char *data;
6118 Py_ssize_t size;
6119 int le;
6120 if (!PyArg_ParseTuple(args, "y#i", &data, &size, &le)) {
6121 return NULL;
6122 }
6123 double d;
6124 switch (size)
6125 {
6126 case 2:
6127 d = PyFloat_Unpack2(data, le);
6128 break;
6129 case 4:
6130 d = PyFloat_Unpack4(data, le);
6131 break;
6132 case 8:
6133 d = PyFloat_Unpack8(data, le);
6134 break;
6135 default:
6136 PyErr_SetString(PyExc_ValueError, "data length must 2, 4 or 8 bytes");
6137 return NULL;
6138 }
6139
6140 if (d == -1.0 && PyErr_Occurred()) {
6141 return NULL;
6142 }
6143 return PyFloat_FromDouble(d);
6144 }
6145
6146 static PyObject *
6147 frame_getlocals(PyObject *self, PyObject *frame)
6148 {
6149 if (!PyFrame_Check(frame)) {
6150 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
6151 return NULL;
6152 }
6153 return PyFrame_GetLocals((PyFrameObject *)frame);
6154 }
6155
6156 static PyObject *
6157 frame_getglobals(PyObject *self, PyObject *frame)
6158 {
6159 if (!PyFrame_Check(frame)) {
6160 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
6161 return NULL;
6162 }
6163 return PyFrame_GetGlobals((PyFrameObject *)frame);
6164 }
6165
6166 static PyObject *
6167 frame_getgenerator(PyObject *self, PyObject *frame)
6168 {
6169 if (!PyFrame_Check(frame)) {
6170 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
6171 return NULL;
6172 }
6173 return PyFrame_GetGenerator((PyFrameObject *)frame);
6174 }
6175
6176 static PyObject *
6177 frame_getbuiltins(PyObject *self, PyObject *frame)
6178 {
6179 if (!PyFrame_Check(frame)) {
6180 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
6181 return NULL;
6182 }
6183 return PyFrame_GetBuiltins((PyFrameObject *)frame);
6184 }
6185
6186 static PyObject *
6187 frame_getlasti(PyObject *self, PyObject *frame)
6188 {
6189 if (!PyFrame_Check(frame)) {
6190 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
6191 return NULL;
6192 }
6193 int lasti = PyFrame_GetLasti((PyFrameObject *)frame);
6194 if (lasti < 0) {
6195 assert(lasti == -1);
6196 Py_RETURN_NONE;
6197 }
6198 return PyLong_FromLong(lasti);
6199 }
6200
6201 static PyObject *
6202 frame_new(PyObject *self, PyObject *args)
6203 {
6204 PyObject *code, *globals, *locals;
6205 if (!PyArg_ParseTuple(args, "OOO", &code, &globals, &locals)) {
6206 return NULL;
6207 }
6208 if (!PyCode_Check(code)) {
6209 PyErr_SetString(PyExc_TypeError, "argument must be a code object");
6210 return NULL;
6211 }
6212 PyThreadState *tstate = PyThreadState_Get();
6213
6214 return (PyObject *)PyFrame_New(tstate, (PyCodeObject *)code, globals, locals);
6215 }
6216
6217 static PyObject *
6218 eval_get_func_name(PyObject *self, PyObject *func)
6219 {
6220 return PyUnicode_FromString(PyEval_GetFuncName(func));
6221 }
6222
6223 static PyObject *
6224 eval_get_func_desc(PyObject *self, PyObject *func)
6225 {
6226 return PyUnicode_FromString(PyEval_GetFuncDesc(func));
6227 }
6228
6229 #ifndef PYPY_VERSION
6230 static PyObject *
6231 eval_eval_code_ex(PyObject *mod, PyObject *pos_args)
6232 {
6233 PyObject *result = NULL;
6234 PyObject *code;
6235 PyObject *globals;
6236 PyObject *locals = NULL;
6237 PyObject *args = NULL;
6238 PyObject *kwargs = NULL;
6239 PyObject *defaults = NULL;
6240 PyObject *kw_defaults = NULL;
6241 PyObject *closure = NULL;
6242
6243 PyObject **c_kwargs = NULL;
6244
6245 if (!PyArg_UnpackTuple(pos_args,
6246 "eval_code_ex",
6247 2,
6248 8,
6249 &code,
6250 &globals,
6251 &locals,
6252 &args,
6253 &kwargs,
6254 &defaults,
6255 &kw_defaults,
6256 &closure))
6257 {
6258 goto exit;
6259 }
6260
6261 if (!PyCode_Check(code)) {
6262 PyErr_SetString(PyExc_TypeError,
6263 "code must be a Python code object");
6264 goto exit;
6265 }
6266
6267 if (!PyDict_Check(globals)) {
6268 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
6269 goto exit;
6270 }
6271
6272 if (locals && !PyMapping_Check(locals)) {
6273 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
6274 goto exit;
6275 }
6276 if (locals == Py_None) {
6277 locals = NULL;
6278 }
6279
6280 PyObject **c_args = NULL;
6281 Py_ssize_t c_args_len = 0;
6282
6283 if (args)
6284 {
6285 if (!PyTuple_Check(args)) {
6286 PyErr_SetString(PyExc_TypeError, "args must be a tuple");
6287 goto exit;
6288 } else {
6289 c_args = &PyTuple_GET_ITEM(args, 0);
6290 c_args_len = PyTuple_Size(args);
6291 }
6292 }
6293
6294 Py_ssize_t c_kwargs_len = 0;
6295
6296 if (kwargs)
6297 {
6298 if (!PyDict_Check(kwargs)) {
6299 PyErr_SetString(PyExc_TypeError, "keywords must be a dict");
6300 goto exit;
6301 } else {
6302 c_kwargs_len = PyDict_Size(kwargs);
6303 if (c_kwargs_len > 0) {
6304 c_kwargs = PyMem_NEW(PyObject*, 2 * c_kwargs_len);
6305 if (!c_kwargs) {
6306 PyErr_NoMemory();
6307 goto exit;
6308 }
6309
6310 Py_ssize_t i = 0;
6311 Py_ssize_t pos = 0;
6312
6313 while (PyDict_Next(kwargs,
6314 &pos,
6315 &c_kwargs[i],
6316 &c_kwargs[i + 1]))
6317 {
6318 i += 2;
6319 }
6320 c_kwargs_len = i / 2;
6321 /* XXX This is broken if the caller deletes dict items! */
6322 }
6323 }
6324 }
6325
6326
6327 PyObject **c_defaults = NULL;
6328 Py_ssize_t c_defaults_len = 0;
6329
6330 if (defaults && PyTuple_Check(defaults)) {
6331 c_defaults = &PyTuple_GET_ITEM(defaults, 0);
6332 c_defaults_len = PyTuple_Size(defaults);
6333 }
6334
6335 if (kw_defaults && !PyDict_Check(kw_defaults)) {
6336 PyErr_SetString(PyExc_TypeError, "kw_defaults must be a dict");
6337 goto exit;
6338 }
6339
6340 if (closure && !PyTuple_Check(closure)) {
6341 PyErr_SetString(PyExc_TypeError, "closure must be a tuple of cells");
6342 goto exit;
6343 }
6344
6345
6346 result = PyEval_EvalCodeEx(
6347 code,
6348 globals,
6349 locals,
6350 c_args,
6351 (int)c_args_len,
6352 c_kwargs,
6353 (int)c_kwargs_len,
6354 c_defaults,
6355 (int)c_defaults_len,
6356 kw_defaults,
6357 closure
6358 );
6359
6360 exit:
6361 if (c_kwargs) {
6362 PyMem_DEL(c_kwargs);
6363 }
6364
6365 return result;
6366 }
6367 #endif
6368
6369 static PyObject *
6370 get_feature_macros(PyObject *self, PyObject *Py_UNUSED(args))
6371 {
6372 PyObject *result = PyDict_New();
6373 if (!result) {
6374 return NULL;
6375 }
6376 int res;
6377 #include "_testcapi_feature_macros.inc"
6378 return result;
6379 }
6380
6381 static PyObject *
6382 test_code_api(PyObject *self, PyObject *Py_UNUSED(args))
6383 {
6384 PyCodeObject *co = PyCode_NewEmpty("_testcapi", "dummy", 1);
6385 if (co == NULL) {
6386 return NULL;
6387 }
6388 /* co_code */
6389 {
6390 PyObject *co_code = PyCode_GetCode(co);
6391 if (co_code == NULL) {
6392 goto fail;
6393 }
6394 assert(PyBytes_CheckExact(co_code));
6395 if (PyObject_Length(co_code) == 0) {
6396 PyErr_SetString(PyExc_ValueError, "empty co_code");
6397 Py_DECREF(co_code);
6398 goto fail;
6399 }
6400 Py_DECREF(co_code);
6401 }
6402 /* co_varnames */
6403 {
6404 PyObject *co_varnames = PyCode_GetVarnames(co);
6405 if (co_varnames == NULL) {
6406 goto fail;
6407 }
6408 if (!PyTuple_CheckExact(co_varnames)) {
6409 PyErr_SetString(PyExc_TypeError, "co_varnames not tuple");
6410 Py_DECREF(co_varnames);
6411 goto fail;
6412 }
6413 if (PyTuple_GET_SIZE(co_varnames) != 0) {
6414 PyErr_SetString(PyExc_ValueError, "non-empty co_varnames");
6415 Py_DECREF(co_varnames);
6416 goto fail;
6417 }
6418 Py_DECREF(co_varnames);
6419 }
6420 /* co_cellvars */
6421 {
6422 PyObject *co_cellvars = PyCode_GetCellvars(co);
6423 if (co_cellvars == NULL) {
6424 goto fail;
6425 }
6426 if (!PyTuple_CheckExact(co_cellvars)) {
6427 PyErr_SetString(PyExc_TypeError, "co_cellvars not tuple");
6428 Py_DECREF(co_cellvars);
6429 goto fail;
6430 }
6431 if (PyTuple_GET_SIZE(co_cellvars) != 0) {
6432 PyErr_SetString(PyExc_ValueError, "non-empty co_cellvars");
6433 Py_DECREF(co_cellvars);
6434 goto fail;
6435 }
6436 Py_DECREF(co_cellvars);
6437 }
6438 /* co_freevars */
6439 {
6440 PyObject *co_freevars = PyCode_GetFreevars(co);
6441 if (co_freevars == NULL) {
6442 goto fail;
6443 }
6444 if (!PyTuple_CheckExact(co_freevars)) {
6445 PyErr_SetString(PyExc_TypeError, "co_freevars not tuple");
6446 Py_DECREF(co_freevars);
6447 goto fail;
6448 }
6449 if (PyTuple_GET_SIZE(co_freevars) != 0) {
6450 PyErr_SetString(PyExc_ValueError, "non-empty co_freevars");
6451 Py_DECREF(co_freevars);
6452 goto fail;
6453 }
6454 Py_DECREF(co_freevars);
6455 }
6456 Py_DECREF(co);
6457 Py_RETURN_NONE;
6458 fail:
6459 Py_DECREF(co);
6460 return NULL;
6461 }
6462
6463 static int
6464 record_func(PyObject *obj, PyFrameObject *f, int what, PyObject *arg)
6465 {
6466 assert(PyList_Check(obj));
6467 PyObject *what_obj = NULL;
6468 PyObject *line_obj = NULL;
6469 PyObject *tuple = NULL;
6470 int res = -1;
6471 what_obj = PyLong_FromLong(what);
6472 if (what_obj == NULL) {
6473 goto error;
6474 }
6475 int line = PyFrame_GetLineNumber(f);
6476 line_obj = PyLong_FromLong(line);
6477 if (line_obj == NULL) {
6478 goto error;
6479 }
6480 tuple = PyTuple_Pack(3, what_obj, line_obj, arg);
6481 if (tuple == NULL) {
6482 goto error;
6483 }
6484 PyTuple_SET_ITEM(tuple, 0, what_obj);
6485 if (PyList_Append(obj, tuple)) {
6486 goto error;
6487 }
6488 res = 0;
6489 error:
6490 Py_XDECREF(what_obj);
6491 Py_XDECREF(line_obj);
6492 Py_XDECREF(tuple);
6493 return res;
6494 }
6495
6496 #ifndef PYPY_VERSION
6497 static PyObject *
6498 settrace_to_record(PyObject *self, PyObject *list)
6499 {
6500
6501 if (!PyList_Check(list)) {
6502 PyErr_SetString(PyExc_TypeError, "argument must be a list");
6503 return NULL;
6504 }
6505 PyEval_SetTrace(record_func, list);
6506 Py_RETURN_NONE;
6507 }
6508 #endif
6509
6510 static int
6511 error_func(PyObject *obj, PyFrameObject *f, int what, PyObject *arg)
6512 {
6513 assert(PyList_Check(obj));
6514 /* Only raise if list is empty, otherwise append None
6515 * This ensures that we only raise once */
6516 if (PyList_GET_SIZE(obj)) {
6517 return 0;
6518 }
6519 if (PyList_Append(obj, Py_None)) {
6520 return -1;
6521 }
6522 PyErr_SetString(PyExc_Exception, "an exception");
6523 return -1;
6524 }
6525
6526 #ifndef PYPY_VERSION
6527 static PyObject *
6528 settrace_to_error(PyObject *self, PyObject *list)
6529 {
6530 if (!PyList_Check(list)) {
6531 PyErr_SetString(PyExc_TypeError, "argument must be a list");
6532 return NULL;
6533 }
6534 PyEval_SetTrace(error_func, list);
6535 Py_RETURN_NONE;
6536 }
6537 #endif
6538
6539 static PyObject *negative_dictoffset(PyObject *, PyObject *);
6540
6541 static PyObject *
6542 function_get_code(PyObject *self, PyObject *func)
6543 {
6544 PyObject *code = PyFunction_GetCode(func);
6545 if (code != NULL) {
6546 Py_INCREF(code);
6547 return code;
6548 } else {
6549 return NULL;
6550 }
6551 }
6552
6553 static PyObject *
6554 function_get_globals(PyObject *self, PyObject *func)
6555 {
6556 PyObject *globals = PyFunction_GetGlobals(func);
6557 if (globals != NULL) {
6558 Py_INCREF(globals);
6559 return globals;
6560 } else {
6561 return NULL;
6562 }
6563 }
6564
6565 static PyObject *
6566 function_get_module(PyObject *self, PyObject *func)
6567 {
6568 PyObject *module = PyFunction_GetModule(func);
6569 if (module != NULL) {
6570 Py_INCREF(module);
6571 return module;
6572 } else {
6573 return NULL;
6574 }
6575 }
6576
6577 static PyObject *test_buildvalue_issue38913(PyObject *, PyObject *);
6578 static PyObject *getargs_s_hash_int(PyObject *, PyObject *, PyObject*);
6579 static PyObject *getargs_s_hash_int2(PyObject *, PyObject *, PyObject*);
6580 static PyObject *gh_99240_clear_args(PyObject *, PyObject *);
6581
6582 static PyObject *
6583 sys_getobject(PyObject *Py_UNUSED(module), PyObject *arg)
6584 {
6585 const char *name;
6586 Py_ssize_t size;
6587 if (!PyArg_Parse(arg, "z#", &name, &size)) {
6588 return NULL;
6589 }
6590 PyObject *result = PySys_GetObject(name);
6591 if (result == NULL) {
6592 result = PyExc_AttributeError;
6593 }
6594 return Py_NewRef(result);
6595 }
6596
6597 static PyObject *
6598 sys_setobject(PyObject *Py_UNUSED(module), PyObject *args)
6599 {
6600 const char *name;
6601 Py_ssize_t size;
6602 PyObject *value;
6603 if (!PyArg_ParseTuple(args, "z#O", &name, &size, &value)) {
6604 return NULL;
6605 }
6606 NULLABLE(value);
6607 RETURN_INT(PySys_SetObject(name, value));
6608 }
6609
6610
6611 static PyMethodDef TestMethods[] = {
6612 {"exc_set_object", exc_set_object, METH_VARARGS},
6613 {"raise_exception", raise_exception, METH_VARARGS},
6614 {"raise_memoryerror", raise_memoryerror, METH_NOARGS},
6615 {"set_errno", set_errno, METH_VARARGS},
6616 {"test_config", test_config, METH_NOARGS},
6617 {"test_sizeof_c_types", test_sizeof_c_types, METH_NOARGS},
6618 {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
6619 {"datetime_check_date", datetime_check_date, METH_VARARGS},
6620 {"datetime_check_time", datetime_check_time, METH_VARARGS},
6621 {"datetime_check_datetime", datetime_check_datetime, METH_VARARGS},
6622 {"datetime_check_delta", datetime_check_delta, METH_VARARGS},
6623 {"datetime_check_tzinfo", datetime_check_tzinfo, METH_VARARGS},
6624 {"make_timezones_capi", make_timezones_capi, METH_NOARGS},
6625 {"get_timezones_offset_zero", get_timezones_offset_zero, METH_NOARGS},
6626 {"get_timezone_utc_capi", get_timezone_utc_capi, METH_VARARGS},
6627 {"get_date_fromdate", get_date_fromdate, METH_VARARGS},
6628 {"get_datetime_fromdateandtime", get_datetime_fromdateandtime, METH_VARARGS},
6629 {"get_datetime_fromdateandtimeandfold", get_datetime_fromdateandtimeandfold, METH_VARARGS},
6630 {"get_time_fromtime", get_time_fromtime, METH_VARARGS},
6631 {"get_time_fromtimeandfold", get_time_fromtimeandfold, METH_VARARGS},
6632 {"get_delta_fromdsu", get_delta_fromdsu, METH_VARARGS},
6633 {"get_date_fromtimestamp", get_date_fromtimestamp, METH_VARARGS},
6634 {"get_datetime_fromtimestamp", get_datetime_fromtimestamp, METH_VARARGS},
6635 {"PyDateTime_GET", test_PyDateTime_GET, METH_O},
6636 {"PyDateTime_DATE_GET", test_PyDateTime_DATE_GET, METH_O},
6637 {"PyDateTime_TIME_GET", test_PyDateTime_TIME_GET, METH_O},
6638 {"PyDateTime_DELTA_GET", test_PyDateTime_DELTA_GET, METH_O},
6639 {"test_gc_control", test_gc_control, METH_NOARGS},
6640 {"test_list_api", test_list_api, METH_NOARGS},
6641 {"test_dict_iteration", test_dict_iteration, METH_NOARGS},
6642 #ifndef PYPY_VERSION
6643 {"dict_getitem_knownhash", dict_getitem_knownhash, METH_VARARGS},
6644 #endif // ifndef PYPY_VERSION
6645 {"test_lazy_hash_inheritance", test_lazy_hash_inheritance,METH_NOARGS},
6646 {"test_long_api", test_long_api, METH_NOARGS},
6647 {"test_xincref_doesnt_leak",test_xincref_doesnt_leak, METH_NOARGS},
6648 {"test_incref_doesnt_leak", test_incref_doesnt_leak, METH_NOARGS},
6649 {"test_xdecref_doesnt_leak",test_xdecref_doesnt_leak, METH_NOARGS},
6650 {"test_decref_doesnt_leak", test_decref_doesnt_leak, METH_NOARGS},
6651 #ifndef PYPY_VERSION
6652 {"test_structseq_newtype_doesnt_leak",
6653 test_structseq_newtype_doesnt_leak, METH_NOARGS},
6654 #endif
6655 {"test_structseq_newtype_null_descr_doc",
6656 test_structseq_newtype_null_descr_doc, METH_NOARGS},
6657 {"test_incref_decref_API", test_incref_decref_API, METH_NOARGS},
6658 {"test_long_and_overflow", test_long_and_overflow, METH_NOARGS},
6659 {"test_long_as_double", test_long_as_double, METH_NOARGS},
6660 {"test_long_as_size_t", test_long_as_size_t, METH_NOARGS},
6661 {"test_long_as_unsigned_long_long_mask",
6662 test_long_as_unsigned_long_long_mask, METH_NOARGS},
6663 {"test_long_numbits", test_long_numbits, METH_NOARGS},
6664 {"test_k_code", test_k_code, METH_NOARGS},
6665 {"test_empty_argparse", test_empty_argparse, METH_NOARGS},
6666 {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS},
6667 {"pyobject_repr_from_null", pyobject_repr_from_null, METH_NOARGS},
6668 {"pyobject_str_from_null", pyobject_str_from_null, METH_NOARGS},
6669 {"pyobject_bytes_from_null", pyobject_bytes_from_null, METH_NOARGS},
6670 {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
6671 {"test_with_docstring", test_with_docstring, METH_NOARGS,
6672 PyDoc_STR("This is a pretty normal docstring.")},
6673 {"test_string_to_double", test_string_to_double, METH_NOARGS},
6674 {"test_unicode_compare_with_ascii", test_unicode_compare_with_ascii,
6675 METH_NOARGS},
6676 {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
6677 {"test_from_contiguous", (PyCFunction)test_from_contiguous, METH_NOARGS},
6678 #if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
6679 #ifndef PYPY_VERSION
6680 {"test_pep3118_obsolete_write_locks", (PyCFunction)test_pep3118_obsolete_write_locks, METH_NOARGS},
6681 #endif // ifndef PYPY_VERSION
6682 #endif
6683 {"getbuffer_with_null_view", getbuffer_with_null_view, METH_O},
6684 #ifndef PYPY_VERSION
6685 {"PyBuffer_SizeFromFormat", test_PyBuffer_SizeFromFormat, METH_VARARGS},
6686 #endif
6687 {"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
6688 {"negative_dictoffset", negative_dictoffset, METH_NOARGS},
6689 #ifndef PYPY_VERSION
6690 {"test_buildvalue_issue38913", test_buildvalue_issue38913, METH_NOARGS},
6691 #endif
6692 {"get_args", get_args, METH_VARARGS},
6693 {"test_get_statictype_slots", test_get_statictype_slots, METH_NOARGS},
6694 {"test_get_type_name", test_get_type_name, METH_NOARGS},
6695 {"test_get_type_qualname", test_get_type_qualname, METH_NOARGS},
6696 {"test_type_from_ephemeral_spec", test_type_from_ephemeral_spec, METH_NOARGS},
6697 {"get_kwargs", _PyCFunction_CAST(get_kwargs),
6698 METH_VARARGS|METH_KEYWORDS},
6699 {"getargs_tuple", getargs_tuple, METH_VARARGS},
6700 {"getargs_keywords", _PyCFunction_CAST(getargs_keywords),
6701 METH_VARARGS|METH_KEYWORDS},
6702 {"getargs_keyword_only", _PyCFunction_CAST(getargs_keyword_only),
6703 METH_VARARGS|METH_KEYWORDS},
6704 {"getargs_positional_only_and_keywords",
6705 _PyCFunction_CAST(getargs_positional_only_and_keywords),
6706 METH_VARARGS|METH_KEYWORDS},
6707 {"getargs_b", getargs_b, METH_VARARGS},
6708 {"getargs_B", getargs_B, METH_VARARGS},
6709 {"getargs_h", getargs_h, METH_VARARGS},
6710 {"getargs_H", getargs_H, METH_VARARGS},
6711 {"getargs_I", getargs_I, METH_VARARGS},
6712 {"getargs_k", getargs_k, METH_VARARGS},
6713 {"getargs_i", getargs_i, METH_VARARGS},
6714 {"getargs_l", getargs_l, METH_VARARGS},
6715 {"getargs_n", getargs_n, METH_VARARGS},
6716 {"getargs_p", getargs_p, METH_VARARGS},
6717 {"getargs_L", getargs_L, METH_VARARGS},
6718 {"getargs_K", getargs_K, METH_VARARGS},
6719 {"test_longlong_api", test_longlong_api, METH_NOARGS},
6720 {"test_long_long_and_overflow",test_long_long_and_overflow, METH_NOARGS},
6721 {"test_L_code", test_L_code, METH_NOARGS},
6722 {"getargs_f", getargs_f, METH_VARARGS},
6723 {"getargs_d", getargs_d, METH_VARARGS},
6724 {"getargs_D", getargs_D, METH_VARARGS},
6725 {"getargs_S", getargs_S, METH_VARARGS},
6726 {"getargs_Y", getargs_Y, METH_VARARGS},
6727 {"getargs_U", getargs_U, METH_VARARGS},
6728 {"getargs_c", getargs_c, METH_VARARGS},
6729 {"getargs_C", getargs_C, METH_VARARGS},
6730 {"getargs_s", getargs_s, METH_VARARGS},
6731 {"getargs_s_star", getargs_s_star, METH_VARARGS},
6732 {"getargs_s_hash", getargs_s_hash, METH_VARARGS},
6733 {"getargs_s_hash_int", _PyCFunction_CAST(getargs_s_hash_int),
6734 METH_VARARGS|METH_KEYWORDS},
6735 {"getargs_s_hash_int2", _PyCFunction_CAST(getargs_s_hash_int2),
6736 METH_VARARGS|METH_KEYWORDS},
6737 {"gh_99240_clear_args", gh_99240_clear_args, METH_VARARGS},
6738 {"getargs_z", getargs_z, METH_VARARGS},
6739 {"getargs_z_star", getargs_z_star, METH_VARARGS},
6740 {"getargs_z_hash", getargs_z_hash, METH_VARARGS},
6741 {"getargs_y", getargs_y, METH_VARARGS},
6742 {"getargs_y_star", getargs_y_star, METH_VARARGS},
6743 {"getargs_y_hash", getargs_y_hash, METH_VARARGS},
6744 {"getargs_u", getargs_u, METH_VARARGS},
6745 {"getargs_u_hash", getargs_u_hash, METH_VARARGS},
6746 {"getargs_Z", getargs_Z, METH_VARARGS},
6747 {"getargs_Z_hash", getargs_Z_hash, METH_VARARGS},
6748 {"getargs_w_star", getargs_w_star, METH_VARARGS},
6749 {"getargs_es", getargs_es, METH_VARARGS},
6750 {"getargs_et", getargs_et, METH_VARARGS},
6751 {"getargs_es_hash", getargs_es_hash, METH_VARARGS},
6752 {"getargs_et_hash", getargs_et_hash, METH_VARARGS},
6753 {"codec_incrementalencoder",
6754 (PyCFunction)codec_incrementalencoder, METH_VARARGS},
6755 {"codec_incrementaldecoder",
6756 (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
6757 {"test_s_code", test_s_code, METH_NOARGS},
6758 #if USE_UNICODE_WCHAR_CACHE
6759 {"test_u_code", test_u_code, METH_NOARGS},
6760 {"test_Z_code", test_Z_code, METH_NOARGS},
6761 #endif /* USE_UNICODE_WCHAR_CACHE */
6762 {"test_widechar", test_widechar, METH_NOARGS},
6763 {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS},
6764 {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS},
6765 {"unicode_asucs4", unicode_asucs4, METH_VARARGS},
6766 {"unicode_asutf8", unicode_asutf8, METH_VARARGS},
6767 {"unicode_asutf8andsize", unicode_asutf8andsize, METH_VARARGS},
6768 {"unicode_decodeutf8", unicode_decodeutf8, METH_VARARGS},
6769 #ifndef PYPY_VERSION
6770 {"unicode_decodeutf8stateful",unicode_decodeutf8stateful, METH_VARARGS}, {"unicode_findchar", unicode_findchar, METH_VARARGS},
6771 {"unicode_copycharacters", unicode_copycharacters, METH_VARARGS},
6772 #endif
6773 #if USE_UNICODE_WCHAR_CACHE
6774 {"unicode_legacy_string", unicode_legacy_string, METH_VARARGS},
6775 #endif /* USE_UNICODE_WCHAR_CACHE */
6776 {"_test_thread_state", test_thread_state, METH_VARARGS},
6777 {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
6778 #ifdef HAVE_GETTIMEOFDAY
6779 {"profile_int", profile_int, METH_NOARGS},
6780 #endif
6781 {"traceback_print", traceback_print, METH_VARARGS},
6782 {"exception_print", exception_print, METH_VARARGS},
6783 {"set_exception", test_set_exception, METH_O},
6784 {"set_exc_info", test_set_exc_info, METH_VARARGS},
6785 {"argparsing", argparsing, METH_VARARGS},
6786 {"code_newempty", code_newempty, METH_VARARGS},
6787 #ifndef PYPY_VERSION
6788 {"eval_code_ex", eval_eval_code_ex, METH_VARARGS},
6789 #endif
6790 {"make_exception_with_doc", _PyCFunction_CAST(make_exception_with_doc),
6791 METH_VARARGS | METH_KEYWORDS},
6792 {"make_memoryview_from_NULL_pointer", make_memoryview_from_NULL_pointer,
6793 METH_NOARGS},
6794 {"crash_no_current_thread", crash_no_current_thread, METH_NOARGS},
6795 #ifndef PYPY_VERSION
6796 {"run_in_subinterp", run_in_subinterp, METH_VARARGS},
6797 #endif // ifndef PYPY_VERSION
6798 {"pytime_object_to_time_t", test_pytime_object_to_time_t, METH_VARARGS},
6799 {"pytime_object_to_timeval", test_pytime_object_to_timeval, METH_VARARGS},
6800 {"pytime_object_to_timespec", test_pytime_object_to_timespec, METH_VARARGS},
6801 #ifndef PYPY_VERSION
6802 {"with_tp_del", with_tp_del, METH_VARARGS},
6803 #endif
6804 {"create_cfunction", create_cfunction, METH_NOARGS},
6805 {"test_pymem_alloc0", test_pymem_alloc0, METH_NOARGS},
6806 #ifndef PYPY_VERSION
6807 {"test_pymem_setrawallocators",test_pymem_setrawallocators, METH_NOARGS},
6808 {"test_pymem_setallocators",test_pymem_setallocators, METH_NOARGS},
6809 {"test_pyobject_setallocators",test_pyobject_setallocators, METH_NOARGS},
6810 {"set_nomemory", (PyCFunction)set_nomemory, METH_VARARGS,
6811 PyDoc_STR("set_nomemory(start:int, stop:int = 0)")},
6812 {"remove_mem_hooks", remove_mem_hooks, METH_NOARGS,
6813 PyDoc_STR("Remove memory hooks.")},
6814 #endif // ifndef PYPY_VERSION
6815 {"no_docstring",
6816 (PyCFunction)test_with_docstring, METH_NOARGS},
6817 {"docstring_empty",
6818 (PyCFunction)test_with_docstring, METH_NOARGS,
6819 docstring_empty},
6820 {"docstring_no_signature",
6821 (PyCFunction)test_with_docstring, METH_NOARGS,
6822 docstring_no_signature},
6823 {"docstring_with_invalid_signature",
6824 (PyCFunction)test_with_docstring, METH_NOARGS,
6825 docstring_with_invalid_signature},
6826 {"docstring_with_invalid_signature2",
6827 (PyCFunction)test_with_docstring, METH_NOARGS,
6828 docstring_with_invalid_signature2},
6829 {"docstring_with_signature",
6830 (PyCFunction)test_with_docstring, METH_NOARGS,
6831 docstring_with_signature},
6832 {"docstring_with_signature_but_no_doc",
6833 (PyCFunction)test_with_docstring, METH_NOARGS,
6834 docstring_with_signature_but_no_doc},
6835 {"docstring_with_signature_and_extra_newlines",
6836 (PyCFunction)test_with_docstring, METH_NOARGS,
6837 docstring_with_signature_and_extra_newlines},
6838 {"docstring_with_signature_with_defaults",
6839 (PyCFunction)test_with_docstring, METH_NOARGS,
6840 docstring_with_signature_with_defaults},
6841 {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_VARARGS,
6842 PyDoc_STR("set_error_class(error_class) -> None")},
6843 {"join_temporary_c_thread", join_temporary_c_thread, METH_NOARGS},
6844 #ifndef PYPY_VERSION
6845 {"pymarshal_write_long_to_file",
6846 pymarshal_write_long_to_file, METH_VARARGS},
6847 {"pymarshal_write_object_to_file",
6848 pymarshal_write_object_to_file, METH_VARARGS},
6849 {"pymarshal_read_short_from_file",
6850 pymarshal_read_short_from_file, METH_VARARGS},
6851 {"pymarshal_read_long_from_file",
6852 pymarshal_read_long_from_file, METH_VARARGS},
6853 {"pymarshal_read_last_object_from_file",
6854 pymarshal_read_last_object_from_file, METH_VARARGS},
6855 {"pymarshal_read_object_from_file",
6856 pymarshal_read_object_from_file, METH_VARARGS},
6857 #endif // ifndef PYPY_VERSION
6858 {"return_null_without_error", return_null_without_error, METH_NOARGS},
6859 {"return_result_with_error", return_result_with_error, METH_NOARGS},
6860 {"getitem_with_error", getitem_with_error, METH_VARARGS},
6861 {"Py_CompileString", pycompilestring, METH_O},
6862 {"PyTime_FromSeconds", test_pytime_fromseconds, METH_VARARGS},
6863 {"PyTime_FromSecondsObject", test_pytime_fromsecondsobject, METH_VARARGS},
6864 {"PyTime_AsSecondsDouble", test_pytime_assecondsdouble, METH_VARARGS},
6865 {"PyTime_AsTimeval", test_PyTime_AsTimeval, METH_VARARGS},
6866 {"PyTime_AsTimeval_clamp", test_PyTime_AsTimeval_clamp, METH_VARARGS},
6867 #ifdef HAVE_CLOCK_GETTIME
6868 {"PyTime_AsTimespec", test_PyTime_AsTimespec, METH_VARARGS},
6869 {"PyTime_AsTimespec_clamp", test_PyTime_AsTimespec_clamp, METH_VARARGS},
6870 #endif
6871 {"PyTime_AsMilliseconds", test_PyTime_AsMilliseconds, METH_VARARGS},
6872 {"PyTime_AsMicroseconds", test_PyTime_AsMicroseconds, METH_VARARGS},
6873 {"pymem_buffer_overflow", pymem_buffer_overflow, METH_NOARGS},
6874 {"pymem_api_misuse", pymem_api_misuse, METH_NOARGS},
6875 #ifndef PYPY_VERSION
6876 {"pymem_malloc_without_gil", pymem_malloc_without_gil, METH_NOARGS},
6877 {"pymem_getallocatorsname", test_pymem_getallocatorsname, METH_NOARGS},
6878 #endif
6879 {"check_pyobject_null_is_freed", check_pyobject_null_is_freed, METH_NOARGS},
6880 {"check_pyobject_uninitialized_is_freed", check_pyobject_uninitialized_is_freed, METH_NOARGS},
6881 {"check_pyobject_forbidden_bytes_is_freed", check_pyobject_forbidden_bytes_is_freed, METH_NOARGS},
6882 {"check_pyobject_freed_is_freed", check_pyobject_freed_is_freed, METH_NOARGS},
6883 #ifndef PYPY_VERSION
6884 {"pyobject_malloc_without_gil", pyobject_malloc_without_gil, METH_NOARGS},
6885 #endif
6886 {"tracemalloc_track", tracemalloc_track, METH_VARARGS},
6887 {"tracemalloc_untrack", tracemalloc_untrack, METH_VARARGS},
6888 #ifndef PYPY_VERSION
6889 {"tracemalloc_get_traceback", tracemalloc_get_traceback, METH_VARARGS},
6890 {"dict_get_version", dict_get_version, METH_VARARGS},
6891 {"raise_SIGINT_then_send_None", raise_SIGINT_then_send_None, METH_VARARGS},
6892 #endif
6893 {"pyobject_fastcall", test_pyobject_fastcall, METH_VARARGS},
6894 {"pyobject_fastcalldict", test_pyobject_fastcalldict, METH_VARARGS},
6895 {"pyobject_vectorcall", test_pyobject_vectorcall, METH_VARARGS},
6896 {"pyvectorcall_call", test_pyvectorcall_call, METH_VARARGS},
6897 {"stack_pointer", stack_pointer, METH_NOARGS},
6898 #ifdef W_STOPCODE
6899 {"W_STOPCODE", py_w_stopcode, METH_VARARGS},
6900 #endif
6901 {"get_mapping_keys", get_mapping_keys, METH_O},
6902 {"get_mapping_values", get_mapping_values, METH_O},
6903 {"get_mapping_items", get_mapping_items, METH_O},
6904 {"test_mapping_has_key_string", test_mapping_has_key_string, METH_NOARGS},
6905 {"mapping_has_key", mapping_has_key, METH_VARARGS},
6906 {"sequence_set_slice", sequence_set_slice, METH_VARARGS},
6907 {"sequence_del_slice", sequence_del_slice, METH_VARARGS},
6908 {"test_pythread_tss_key_state", test_pythread_tss_key_state, METH_VARARGS},
6909 #ifndef PYPY_VERSION
6910 {"hamt", new_hamt, METH_NOARGS},
6911 #endif // ifndef PYPY_VERSION
6912 {"bad_get", _PyCFunction_CAST(bad_get), METH_FASTCALL},
6913 #ifdef Py_REF_DEBUG
6914 {"negative_refcount", negative_refcount, METH_NOARGS},
6915 #endif
6916 {"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
6917 {"sequence_getitem", sequence_getitem, METH_VARARGS},
6918 {"sequence_setitem", sequence_setitem, METH_VARARGS},
6919 {"meth_varargs", meth_varargs, METH_VARARGS},
6920 {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
6921 {"meth_o", meth_o, METH_O},
6922 {"meth_noargs", meth_noargs, METH_NOARGS},
6923 {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL},
6924 {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS},
6925 {"pynumber_tobase", pynumber_tobase, METH_VARARGS},
6926 {"without_gc", without_gc, METH_O},
6927 {"test_set_type_size", test_set_type_size, METH_NOARGS},
6928 {"test_refcount_macros", test_refcount_macros, METH_NOARGS},
6929 {"test_refcount_funcs", test_refcount_funcs, METH_NOARGS},
6930 {"test_py_is_macros", test_py_is_macros, METH_NOARGS},
6931 {"test_py_is_funcs", test_py_is_funcs, METH_NOARGS},
6932 {"fatal_error", test_fatal_error, METH_VARARGS,
6933 PyDoc_STR("fatal_error(message, release_gil=False): call Py_FatalError(message)")},
6934 {"type_get_version", type_get_version, METH_O, PyDoc_STR("type->tp_version_tag")},
6935 {"type_modified", type_modified, METH_O, PyDoc_STR("PyType_Modified")},
6936 {"type_assign_specific_version_unsafe", type_assign_specific_version_unsafe, METH_VARARGS,
6937 PyDoc_STR("forcefully assign type->tp_version_tag")},
6938 {"test_tstate_capi", test_tstate_capi, METH_NOARGS, NULL},
6939 {"float_pack", test_float_pack, METH_VARARGS, NULL},
6940 {"float_unpack", test_float_unpack, METH_VARARGS, NULL},
6941 {"frame_getlocals", frame_getlocals, METH_O, NULL},
6942 {"frame_getglobals", frame_getglobals, METH_O, NULL},
6943 {"frame_getgenerator", frame_getgenerator, METH_O, NULL},
6944 {"frame_getbuiltins", frame_getbuiltins, METH_O, NULL},
6945 {"frame_getlasti", frame_getlasti, METH_O, NULL},
6946 {"frame_new", frame_new, METH_VARARGS, NULL},
6947 {"eval_get_func_name", eval_get_func_name, METH_O, NULL},
6948 {"eval_get_func_desc", eval_get_func_desc, METH_O, NULL},
6949 {"get_feature_macros", get_feature_macros, METH_NOARGS, NULL},
6950 {"test_code_api", test_code_api, METH_NOARGS, NULL},
6951 #ifndef PYPY_VERSION
6952 {"settrace_to_error", settrace_to_error, METH_O, NULL},
6953 {"settrace_to_record", settrace_to_record, METH_O, NULL},
6954 #endif
6955 {"function_get_code", function_get_code, METH_O, NULL},
6956 {"function_get_globals", function_get_globals, METH_O, NULL},
6957 {"function_get_module", function_get_module, METH_O, NULL},
6958 {"sys_getobject", sys_getobject, METH_O},
6959 {"sys_setobject", sys_setobject, METH_VARARGS},
6960 {NULL, NULL} /* sentinel */
6961 };
6962
6963 typedef struct {
6964 char bool_member;
6965 char byte_member;
6966 unsigned char ubyte_member;
6967 short short_member;
6968 unsigned short ushort_member;
6969 int int_member;
6970 unsigned int uint_member;
6971 long long_member;
6972 unsigned long ulong_member;
6973 Py_ssize_t pyssizet_member;
6974 float float_member;
6975 double double_member;
6976 char inplace_member[6];
6977 long long longlong_member;
6978 unsigned long long ulonglong_member;
6979 } all_structmembers;
6980
6981 typedef struct {
6982 PyObject_HEAD
6983 all_structmembers structmembers;
6984 } test_structmembers;
6985
6986 static struct PyMemberDef test_members[] = {
6987 {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
6988 {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
6989 {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
6990 {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
6991 {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
6992 {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
6993 {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
6994 {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
6995 {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
6996 {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
6997 {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
6998 {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
6999 {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
7000 {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
7001 {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
7002 {NULL}
7003 };
7004
7005
7006 static PyObject *
7007 test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
7008 {
7009 static char *keywords[] = {
7010 "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
7011 "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
7012 "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
7013 "T_LONGLONG", "T_ULONGLONG",
7014 NULL};
7015 static const char fmt[] = "|bbBhHiIlknfds#LK";
7016 test_structmembers *ob;
7017 const char *s = NULL;
7018 Py_ssize_t string_len = 0;
7019 ob = PyObject_New(test_structmembers, type);
7020 if (ob == NULL)
7021 return NULL;
7022 memset(&ob->structmembers, 0, sizeof(all_structmembers));
7023 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
7024 &ob->structmembers.bool_member,
7025 &ob->structmembers.byte_member,
7026 &ob->structmembers.ubyte_member,
7027 &ob->structmembers.short_member,
7028 &ob->structmembers.ushort_member,
7029 &ob->structmembers.int_member,
7030 &ob->structmembers.uint_member,
7031 &ob->structmembers.long_member,
7032 &ob->structmembers.ulong_member,
7033 &ob->structmembers.pyssizet_member,
7034 &ob->structmembers.float_member,
7035 &ob->structmembers.double_member,
7036 &s, &string_len
7037 , &ob->structmembers.longlong_member,
7038 &ob->structmembers.ulonglong_member
7039 )) {
7040 Py_DECREF(ob);
7041 return NULL;
7042 }
7043 if (s != NULL) {
7044 if (string_len > 5) {
7045 Py_DECREF(ob);
7046 PyErr_SetString(PyExc_ValueError, "string too long");
7047 return NULL;
7048 }
7049 strcpy(ob->structmembers.inplace_member, s);
7050 }
7051 else {
7052 strcpy(ob->structmembers.inplace_member, "");
7053 }
7054 return (PyObject *)ob;
7055 }
7056
7057 static void
7058 test_structmembers_free(PyObject *ob)
7059 {
7060 PyObject_Free(ob);
7061 }
7062
7063 static PyTypeObject test_structmembersType = {
7064 PyVarObject_HEAD_INIT(NULL, 0)
7065 "test_structmembersType",
7066 sizeof(test_structmembers), /* tp_basicsize */
7067 0, /* tp_itemsize */
7068 test_structmembers_free, /* destructor tp_dealloc */
7069 0, /* tp_vectorcall_offset */
7070 0, /* tp_getattr */
7071 0, /* tp_setattr */
7072 0, /* tp_as_async */
7073 0, /* tp_repr */
7074 0, /* tp_as_number */
7075 0, /* tp_as_sequence */
7076 0, /* tp_as_mapping */
7077 0, /* tp_hash */
7078 0, /* tp_call */
7079 0, /* tp_str */
7080 PyObject_GenericGetAttr, /* tp_getattro */
7081 PyObject_GenericSetAttr, /* tp_setattro */
7082 0, /* tp_as_buffer */
7083 0, /* tp_flags */
7084 "Type containing all structmember types",
7085 0, /* traverseproc tp_traverse */
7086 0, /* tp_clear */
7087 0, /* tp_richcompare */
7088 0, /* tp_weaklistoffset */
7089 0, /* tp_iter */
7090 0, /* tp_iternext */
7091 0, /* tp_methods */
7092 test_members, /* tp_members */
7093 0,
7094 0,
7095 0,
7096 0,
7097 0,
7098 0,
7099 0,
7100 0,
7101 test_structmembers_new, /* tp_new */
7102 };
7103
7104
7105 typedef struct {
7106 PyObject_HEAD
7107 } matmulObject;
7108
7109 static PyObject *
7110 matmulType_matmul(PyObject *self, PyObject *other)
7111 {
7112 return Py_BuildValue("(sOO)", "matmul", self, other);
7113 }
7114
7115 static PyObject *
7116 matmulType_imatmul(PyObject *self, PyObject *other)
7117 {
7118 return Py_BuildValue("(sOO)", "imatmul", self, other);
7119 }
7120
7121 static void
7122 matmulType_dealloc(PyObject *self)
7123 {
7124 Py_TYPE(self)->tp_free(self);
7125 }
7126
7127 static PyNumberMethods matmulType_as_number = {
7128 0, /* nb_add */
7129 0, /* nb_subtract */
7130 0, /* nb_multiply */
7131 0, /* nb_remainde r*/
7132 0, /* nb_divmod */
7133 0, /* nb_power */
7134 0, /* nb_negative */
7135 0, /* tp_positive */
7136 0, /* tp_absolute */
7137 0, /* tp_bool */
7138 0, /* nb_invert */
7139 0, /* nb_lshift */
7140 0, /* nb_rshift */
7141 0, /* nb_and */
7142 0, /* nb_xor */
7143 0, /* nb_or */
7144 0, /* nb_int */
7145 0, /* nb_reserved */
7146 0, /* nb_float */
7147 0, /* nb_inplace_add */
7148 0, /* nb_inplace_subtract */
7149 0, /* nb_inplace_multiply */
7150 0, /* nb_inplace_remainder */
7151 0, /* nb_inplace_power */
7152 0, /* nb_inplace_lshift */
7153 0, /* nb_inplace_rshift */
7154 0, /* nb_inplace_and */
7155 0, /* nb_inplace_xor */
7156 0, /* nb_inplace_or */
7157 0, /* nb_floor_divide */
7158 0, /* nb_true_divide */
7159 0, /* nb_inplace_floor_divide */
7160 0, /* nb_inplace_true_divide */
7161 0, /* nb_index */
7162 matmulType_matmul, /* nb_matrix_multiply */
7163 matmulType_imatmul /* nb_matrix_inplace_multiply */
7164 };
7165
7166 static PyTypeObject matmulType = {
7167 PyVarObject_HEAD_INIT(NULL, 0)
7168 "matmulType",
7169 sizeof(matmulObject), /* tp_basicsize */
7170 0, /* tp_itemsize */
7171 matmulType_dealloc, /* destructor tp_dealloc */
7172 0, /* tp_vectorcall_offset */
7173 0, /* tp_getattr */
7174 0, /* tp_setattr */
7175 0, /* tp_as_async */
7176 0, /* tp_repr */
7177 &matmulType_as_number, /* tp_as_number */
7178 0, /* tp_as_sequence */
7179 0, /* tp_as_mapping */
7180 0, /* tp_hash */
7181 0, /* tp_call */
7182 0, /* tp_str */
7183 PyObject_GenericGetAttr, /* tp_getattro */
7184 PyObject_GenericSetAttr, /* tp_setattro */
7185 0, /* tp_as_buffer */
7186 0, /* tp_flags */
7187 "C level type with matrix operations defined",
7188 0, /* traverseproc tp_traverse */
7189 0, /* tp_clear */
7190 0, /* tp_richcompare */
7191 0, /* tp_weaklistoffset */
7192 0, /* tp_iter */
7193 0, /* tp_iternext */
7194 0, /* tp_methods */
7195 0, /* tp_members */
7196 0,
7197 0,
7198 0,
7199 0,
7200 0,
7201 0,
7202 0,
7203 0,
7204 PyType_GenericNew, /* tp_new */
7205 PyObject_Del, /* tp_free */
7206 };
7207
7208 typedef struct {
7209 PyObject_HEAD
7210 } ipowObject;
7211
7212 static PyObject *
7213 ipowType_ipow(PyObject *self, PyObject *other, PyObject *mod)
7214 {
7215 return Py_BuildValue("OO", other, mod);
7216 }
7217
7218 static PyNumberMethods ipowType_as_number = {
7219 .nb_inplace_power = ipowType_ipow
7220 };
7221
7222 static PyTypeObject ipowType = {
7223 PyVarObject_HEAD_INIT(NULL, 0)
7224 .tp_name = "ipowType",
7225 .tp_basicsize = sizeof(ipowObject),
7226 .tp_as_number = &ipowType_as_number,
7227 .tp_new = PyType_GenericNew
7228 };
7229
7230 typedef struct {
7231 PyObject_HEAD
7232 PyObject *ao_iterator;
7233 } awaitObject;
7234
7235
7236 static PyObject *
7237 awaitObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
7238 {
7239 PyObject *v;
7240 awaitObject *ao;
7241
7242 if (!PyArg_UnpackTuple(args, "awaitObject", 1, 1, &v))
7243 return NULL;
7244
7245 ao = (awaitObject *)type->tp_alloc(type, 0);
7246 if (ao == NULL) {
7247 return NULL;
7248 }
7249
7250 Py_INCREF(v);
7251 ao->ao_iterator = v;
7252
7253 return (PyObject *)ao;
7254 }
7255
7256
7257 static void
7258 awaitObject_dealloc(awaitObject *ao)
7259 {
7260 Py_CLEAR(ao->ao_iterator);
7261 Py_TYPE(ao)->tp_free(ao);
7262 }
7263
7264
7265 static PyObject *
7266 awaitObject_await(awaitObject *ao)
7267 {
7268 Py_INCREF(ao->ao_iterator);
7269 return ao->ao_iterator;
7270 }
7271
7272 static PyAsyncMethods awaitType_as_async = {
7273 (unaryfunc)awaitObject_await, /* am_await */
7274 0, /* am_aiter */
7275 0, /* am_anext */
7276 0, /* am_send */
7277 };
7278
7279
7280 static PyTypeObject awaitType = {
7281 PyVarObject_HEAD_INIT(NULL, 0)
7282 "awaitType",
7283 sizeof(awaitObject), /* tp_basicsize */
7284 0, /* tp_itemsize */
7285 (destructor)awaitObject_dealloc, /* destructor tp_dealloc */
7286 0, /* tp_vectorcall_offset */
7287 0, /* tp_getattr */
7288 0, /* tp_setattr */
7289 &awaitType_as_async, /* tp_as_async */
7290 0, /* tp_repr */
7291 0, /* tp_as_number */
7292 0, /* tp_as_sequence */
7293 0, /* tp_as_mapping */
7294 0, /* tp_hash */
7295 0, /* tp_call */
7296 0, /* tp_str */
7297 PyObject_GenericGetAttr, /* tp_getattro */
7298 PyObject_GenericSetAttr, /* tp_setattro */
7299 0, /* tp_as_buffer */
7300 0, /* tp_flags */
7301 "C level type with tp_as_async",
7302 0, /* traverseproc tp_traverse */
7303 0, /* tp_clear */
7304 0, /* tp_richcompare */
7305 0, /* tp_weaklistoffset */
7306 0, /* tp_iter */
7307 0, /* tp_iternext */
7308 0, /* tp_methods */
7309 0, /* tp_members */
7310 0,
7311 0,
7312 0,
7313 0,
7314 0,
7315 0,
7316 0,
7317 0,
7318 awaitObject_new, /* tp_new */
7319 PyObject_Del, /* tp_free */
7320 };
7321
7322
7323 static int recurse_infinitely_error_init(PyObject *, PyObject *, PyObject *);
7324
7325 static PyTypeObject PyRecursingInfinitelyError_Type = {
7326 PyVarObject_HEAD_INIT(NULL, 0)
7327 "RecursingInfinitelyError", /* tp_name */
7328 sizeof(PyBaseExceptionObject), /* tp_basicsize */
7329 0, /* tp_itemsize */
7330 0, /* tp_dealloc */
7331 0, /* tp_vectorcall_offset */
7332 0, /* tp_getattr */
7333 0, /* tp_setattr */
7334 0, /* tp_as_async */
7335 0, /* tp_repr */
7336 0, /* tp_as_number */
7337 0, /* tp_as_sequence */
7338 0, /* tp_as_mapping */
7339 0, /* tp_hash */
7340 0, /* tp_call */
7341 0, /* tp_str */
7342 0, /* tp_getattro */
7343 0, /* tp_setattro */
7344 0, /* tp_as_buffer */
7345 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
7346 PyDoc_STR("Instantiating this exception starts infinite recursion."), /* tp_doc */
7347 0, /* tp_traverse */
7348 0, /* tp_clear */
7349 0, /* tp_richcompare */
7350 0, /* tp_weaklistoffset */
7351 0, /* tp_iter */
7352 0, /* tp_iternext */
7353 0, /* tp_methods */
7354 0, /* tp_members */
7355 0, /* tp_getset */
7356 0, /* tp_base */
7357 0, /* tp_dict */
7358 0, /* tp_descr_get */
7359 0, /* tp_descr_set */
7360 0, /* tp_dictoffset */
7361 (initproc)recurse_infinitely_error_init, /* tp_init */
7362 0, /* tp_alloc */
7363 0, /* tp_new */
7364 };
7365
7366 static int
7367 recurse_infinitely_error_init(PyObject *self, PyObject *args, PyObject *kwds)
7368 {
7369 PyObject *type = (PyObject *)&PyRecursingInfinitelyError_Type;
7370
7371 /* Instantiating this exception starts infinite recursion. */
7372 Py_INCREF(type);
7373 PyErr_SetObject(type, NULL);
7374 return -1;
7375 }
7376
7377
7378 /* Test bpo-35983: create a subclass of "list" which checks that instances
7379 * are not deallocated twice */
7380
7381 typedef struct {
7382 PyListObject list;
7383 int deallocated;
7384 } MyListObject;
7385
7386 static PyObject *
7387 MyList_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
7388 {
7389 PyObject* op = PyList_Type.tp_new(type, args, kwds);
7390 ((MyListObject*)op)->deallocated = 0;
7391 return op;
7392 }
7393
7394 void
7395 MyList_dealloc(MyListObject* op)
7396 {
7397 if (op->deallocated) {
7398 /* We cannot raise exceptions here but we still want the testsuite
7399 * to fail when we hit this */
7400 Py_FatalError("MyList instance deallocated twice");
7401 }
7402 op->deallocated = 1;
7403 PyList_Type.tp_dealloc((PyObject *)op);
7404 }
7405
7406 static PyTypeObject MyList_Type = {
7407 PyVarObject_HEAD_INIT(NULL, 0)
7408 "MyList",
7409 sizeof(MyListObject),
7410 0,
7411 (destructor)MyList_dealloc, /* tp_dealloc */
7412 0, /* tp_vectorcall_offset */
7413 0, /* tp_getattr */
7414 0, /* tp_setattr */
7415 0, /* tp_as_async */
7416 0, /* tp_repr */
7417 0, /* tp_as_number */
7418 0, /* tp_as_sequence */
7419 0, /* tp_as_mapping */
7420 0, /* tp_hash */
7421 0, /* tp_call */
7422 0, /* tp_str */
7423 0, /* tp_getattro */
7424 0, /* tp_setattro */
7425 0, /* tp_as_buffer */
7426 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
7427 0, /* tp_doc */
7428 0, /* tp_traverse */
7429 0, /* tp_clear */
7430 0, /* tp_richcompare */
7431 0, /* tp_weaklistoffset */
7432 0, /* tp_iter */
7433 0, /* tp_iternext */
7434 0, /* tp_methods */
7435 0, /* tp_members */
7436 0, /* tp_getset */
7437 0, /* &PyList_Type */ /* tp_base */
7438 0, /* tp_dict */
7439 0, /* tp_descr_get */
7440 0, /* tp_descr_set */
7441 0, /* tp_dictoffset */
7442 0, /* tp_init */
7443 0, /* tp_alloc */
7444 MyList_new, /* tp_new */
7445 };
7446
7447
7448 /* Test PEP 560 */
7449
7450 typedef struct {
7451 PyObject_HEAD
7452 PyObject *item;
7453 } PyGenericAliasObject;
7454
7455 static void
7456 generic_alias_dealloc(PyGenericAliasObject *self)
7457 {
7458 Py_CLEAR(self->item);
7459 Py_TYPE(self)->tp_free((PyObject *)self);
7460 }
7461
7462 static PyObject *
7463 generic_alias_mro_entries(PyGenericAliasObject *self, PyObject *bases)
7464 {
7465 return PyTuple_Pack(1, self->item);
7466 }
7467
7468 static PyMethodDef generic_alias_methods[] = {
7469 {"__mro_entries__", _PyCFunction_CAST(generic_alias_mro_entries), METH_O, NULL},
7470 {NULL} /* sentinel */
7471 };
7472
7473 static PyTypeObject GenericAlias_Type = {
7474 PyVarObject_HEAD_INIT(NULL, 0)
7475 "GenericAlias",
7476 sizeof(PyGenericAliasObject),
7477 0,
7478 .tp_dealloc = (destructor)generic_alias_dealloc,
7479 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7480 .tp_methods = generic_alias_methods,
7481 };
7482
7483 static PyObject *
7484 generic_alias_new(PyObject *item)
7485 {
7486 PyGenericAliasObject *o = PyObject_New(PyGenericAliasObject, &GenericAlias_Type);
7487 if (o == NULL) {
7488 return NULL;
7489 }
7490 Py_INCREF(item);
7491 o->item = item;
7492 return (PyObject*) o;
7493 }
7494
7495 typedef struct {
7496 PyObject_HEAD
7497 } PyGenericObject;
7498
7499 static PyObject *
7500 generic_class_getitem(PyObject *type, PyObject *item)
7501 {
7502 return generic_alias_new(item);
7503 }
7504
7505 static PyMethodDef generic_methods[] = {
7506 {"__class_getitem__", generic_class_getitem, METH_O|METH_CLASS, NULL},
7507 {NULL} /* sentinel */
7508 };
7509
7510 static PyTypeObject Generic_Type = {
7511 PyVarObject_HEAD_INIT(NULL, 0)
7512 "Generic",
7513 sizeof(PyGenericObject),
7514 0,
7515 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7516 .tp_methods = generic_methods,
7517 };
7518
7519
7520 /* Test PEP 590 */
7521
7522 typedef struct {
7523 PyObject_HEAD
7524 vectorcallfunc vectorcall;
7525 } MethodDescriptorObject;
7526
7527 static PyObject *
7528 MethodDescriptor_vectorcall(PyObject *callable, PyObject *const *args,
7529 size_t nargsf, PyObject *kwnames)
7530 {
7531 /* True if using the vectorcall function in MethodDescriptorObject
7532 * but False for MethodDescriptor2Object */
7533 MethodDescriptorObject *md = (MethodDescriptorObject *)callable;
7534 return PyBool_FromLong(md->vectorcall != NULL);
7535 }
7536
7537 static PyObject *
7538 MethodDescriptor_new(PyTypeObject* type, PyObject* args, PyObject *kw)
7539 {
7540 MethodDescriptorObject *op = (MethodDescriptorObject *)type->tp_alloc(type, 0);
7541 op->vectorcall = MethodDescriptor_vectorcall;
7542 return (PyObject *)op;
7543 }
7544
7545 static PyObject *
7546 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
7547 {
7548 if (obj == Py_None || obj == NULL) {
7549 Py_INCREF(func);
7550 return func;
7551 }
7552 return PyMethod_New(func, obj);
7553 }
7554
7555 static PyObject *
7556 nop_descr_get(PyObject *func, PyObject *obj, PyObject *type)
7557 {
7558 Py_INCREF(func);
7559 return func;
7560 }
7561
7562 static PyObject *
7563 call_return_args(PyObject *self, PyObject *args, PyObject *kwargs)
7564 {
7565 Py_INCREF(args);
7566 return args;
7567 }
7568
7569 static PyTypeObject MethodDescriptorBase_Type = {
7570 PyVarObject_HEAD_INIT(NULL, 0)
7571 "MethodDescriptorBase",
7572 sizeof(MethodDescriptorObject),
7573 .tp_new = MethodDescriptor_new,
7574 .tp_call = PyVectorcall_Call,
7575 .tp_vectorcall_offset = offsetof(MethodDescriptorObject, vectorcall),
7576 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
7577 Py_TPFLAGS_METHOD_DESCRIPTOR | Py_TPFLAGS_HAVE_VECTORCALL,
7578 .tp_descr_get = func_descr_get,
7579 };
7580
7581 static PyTypeObject MethodDescriptorDerived_Type = {
7582 PyVarObject_HEAD_INIT(NULL, 0)
7583 "MethodDescriptorDerived",
7584 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7585 };
7586
7587 static PyTypeObject MethodDescriptorNopGet_Type = {
7588 PyVarObject_HEAD_INIT(NULL, 0)
7589 "MethodDescriptorNopGet",
7590 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7591 .tp_call = call_return_args,
7592 .tp_descr_get = nop_descr_get,
7593 };
7594
7595 typedef struct {
7596 MethodDescriptorObject base;
7597 vectorcallfunc vectorcall;
7598 } MethodDescriptor2Object;
7599
7600 static PyObject *
7601 MethodDescriptor2_new(PyTypeObject* type, PyObject* args, PyObject *kw)
7602 {
7603 MethodDescriptor2Object *op = PyObject_New(MethodDescriptor2Object, type);
7604 op->base.vectorcall = NULL;
7605 op->vectorcall = MethodDescriptor_vectorcall;
7606 return (PyObject *)op;
7607 }
7608
7609 static PyTypeObject MethodDescriptor2_Type = {
7610 PyVarObject_HEAD_INIT(NULL, 0)
7611 "MethodDescriptor2",
7612 sizeof(MethodDescriptor2Object),
7613 .tp_new = MethodDescriptor2_new,
7614 .tp_call = PyVectorcall_Call,
7615 .tp_vectorcall_offset = offsetof(MethodDescriptor2Object, vectorcall),
7616 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL,
7617 };
7618
7619 PyDoc_STRVAR(heapdocctype__doc__,
7620 "HeapDocCType(arg1, arg2)\n"
7621 "--\n"
7622 "\n"
7623 "somedoc");
7624
7625 typedef struct {
7626 PyObject_HEAD
7627 } HeapDocCTypeObject;
7628
7629 static PyType_Slot HeapDocCType_slots[] = {
7630 {Py_tp_doc, (char*)heapdocctype__doc__},
7631 {0},
7632 };
7633
7634 static PyType_Spec HeapDocCType_spec = {
7635 "_testcapi.HeapDocCType",
7636 sizeof(HeapDocCTypeObject),
7637 0,
7638 Py_TPFLAGS_DEFAULT,
7639 HeapDocCType_slots
7640 };
7641
7642 typedef struct {
7643 PyObject_HEAD
7644 } HeapTypeNameObject;
7645
7646 static PyType_Slot HeapTypeNameType_slots[] = {
7647 {0},
7648 };
7649
7650 static PyType_Spec HeapTypeNameType_Spec = {
7651 .name = "_testcapi.HeapTypeNameType",
7652 .basicsize = sizeof(HeapTypeNameObject),
7653 .flags = Py_TPFLAGS_DEFAULT,
7654 .slots = HeapTypeNameType_slots,
7655 };
7656
7657 typedef struct {
7658 PyObject_HEAD
7659 } NullTpDocTypeObject;
7660
7661 static PyType_Slot NullTpDocType_slots[] = {
7662 {Py_tp_doc, NULL},
7663 {0, 0},
7664 };
7665
7666 static PyType_Spec NullTpDocType_spec = {
7667 "_testcapi.NullTpDocType",
7668 sizeof(NullTpDocTypeObject),
7669 0,
7670 Py_TPFLAGS_DEFAULT,
7671 NullTpDocType_slots
7672 };
7673
7674
7675 PyDoc_STRVAR(heapgctype__doc__,
7676 "A heap type with GC, and with overridden dealloc.\n\n"
7677 "The 'value' attribute is set to 10 in __init__.");
7678
7679 typedef struct {
7680 PyObject_HEAD
7681 int value;
7682 } HeapCTypeObject;
7683
7684 static struct PyMemberDef heapctype_members[] = {
7685 {"value", T_INT, offsetof(HeapCTypeObject, value)},
7686 {NULL} /* Sentinel */
7687 };
7688
7689 static int
7690 heapctype_init(PyObject *self, PyObject *args, PyObject *kwargs)
7691 {
7692 ((HeapCTypeObject *)self)->value = 10;
7693 return 0;
7694 }
7695
7696 static int
7697 heapgcctype_traverse(HeapCTypeObject *self, visitproc visit, void *arg)
7698 {
7699 Py_VISIT(Py_TYPE(self));
7700 return 0;
7701 }
7702
7703 static void
7704 heapgcctype_dealloc(HeapCTypeObject *self)
7705 {
7706 PyTypeObject *tp = Py_TYPE(self);
7707 PyObject_GC_UnTrack(self);
7708 PyObject_GC_Del(self);
7709 Py_DECREF(tp);
7710 }
7711
7712 static PyType_Slot HeapGcCType_slots[] = {
7713 {Py_tp_init, heapctype_init},
7714 {Py_tp_members, heapctype_members},
7715 {Py_tp_dealloc, heapgcctype_dealloc},
7716 {Py_tp_traverse, heapgcctype_traverse},
7717 {Py_tp_doc, (char*)heapgctype__doc__},
7718 {0, 0},
7719 };
7720
7721 static PyType_Spec HeapGcCType_spec = {
7722 "_testcapi.HeapGcCType",
7723 sizeof(HeapCTypeObject),
7724 0,
7725 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
7726 HeapGcCType_slots
7727 };
7728
7729 PyDoc_STRVAR(heapctype__doc__,
7730 "A heap type without GC, but with overridden dealloc.\n\n"
7731 "The 'value' attribute is set to 10 in __init__.");
7732
7733 static void
7734 heapctype_dealloc(HeapCTypeObject *self)
7735 {
7736 PyTypeObject *tp = Py_TYPE(self);
7737 PyObject_Free(self);
7738 Py_DECREF(tp);
7739 }
7740
7741 static PyType_Slot HeapCType_slots[] = {
7742 {Py_tp_init, heapctype_init},
7743 {Py_tp_members, heapctype_members},
7744 {Py_tp_dealloc, heapctype_dealloc},
7745 {Py_tp_doc, (char*)heapctype__doc__},
7746 {0, 0},
7747 };
7748
7749 static PyType_Spec HeapCType_spec = {
7750 "_testcapi.HeapCType",
7751 sizeof(HeapCTypeObject),
7752 0,
7753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7754 HeapCType_slots
7755 };
7756
7757 PyDoc_STRVAR(heapctypesubclass__doc__,
7758 "Subclass of HeapCType, without GC.\n\n"
7759 "__init__ sets the 'value' attribute to 10 and 'value2' to 20.");
7760
7761 typedef struct {
7762 HeapCTypeObject base;
7763 int value2;
7764 } HeapCTypeSubclassObject;
7765
7766 static int
7767 heapctypesubclass_init(PyObject *self, PyObject *args, PyObject *kwargs)
7768 {
7769 /* Call __init__ of the superclass */
7770 if (heapctype_init(self, args, kwargs) < 0) {
7771 return -1;
7772 }
7773 /* Initialize additional element */
7774 ((HeapCTypeSubclassObject *)self)->value2 = 20;
7775 return 0;
7776 }
7777
7778 static struct PyMemberDef heapctypesubclass_members[] = {
7779 {"value2", T_INT, offsetof(HeapCTypeSubclassObject, value2)},
7780 {NULL} /* Sentinel */
7781 };
7782
7783 static PyType_Slot HeapCTypeSubclass_slots[] = {
7784 {Py_tp_init, heapctypesubclass_init},
7785 {Py_tp_members, heapctypesubclass_members},
7786 {Py_tp_doc, (char*)heapctypesubclass__doc__},
7787 {0, 0},
7788 };
7789
7790 static PyType_Spec HeapCTypeSubclass_spec = {
7791 "_testcapi.HeapCTypeSubclass",
7792 sizeof(HeapCTypeSubclassObject),
7793 0,
7794 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7795 HeapCTypeSubclass_slots
7796 };
7797
7798 PyDoc_STRVAR(heapctypewithbuffer__doc__,
7799 "Heap type with buffer support.\n\n"
7800 "The buffer is set to [b'1', b'2', b'3', b'4']");
7801
7802 typedef struct {
7803 HeapCTypeObject base;
7804 char buffer[4];
7805 } HeapCTypeWithBufferObject;
7806
7807 static int
7808 heapctypewithbuffer_getbuffer(HeapCTypeWithBufferObject *self, Py_buffer *view, int flags)
7809 {
7810 self->buffer[0] = '1';
7811 self->buffer[1] = '2';
7812 self->buffer[2] = '3';
7813 self->buffer[3] = '4';
7814 return PyBuffer_FillInfo(
7815 view, (PyObject*)self, (void *)self->buffer, 4, 1, flags);
7816 }
7817
7818 static void
7819 heapctypewithbuffer_releasebuffer(HeapCTypeWithBufferObject *self, Py_buffer *view)
7820 {
7821 assert(view->obj == (void*) self);
7822 }
7823
7824 static PyType_Slot HeapCTypeWithBuffer_slots[] = {
7825 {Py_bf_getbuffer, heapctypewithbuffer_getbuffer},
7826 {Py_bf_releasebuffer, heapctypewithbuffer_releasebuffer},
7827 {Py_tp_doc, (char*)heapctypewithbuffer__doc__},
7828 {0, 0},
7829 };
7830
7831 static PyType_Spec HeapCTypeWithBuffer_spec = {
7832 "_testcapi.HeapCTypeWithBuffer",
7833 sizeof(HeapCTypeWithBufferObject),
7834 0,
7835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7836 HeapCTypeWithBuffer_slots
7837 };
7838
7839 #ifndef PYPY_VERSION
7840 PyDoc_STRVAR(heapctypesubclasswithfinalizer__doc__,
7841 "Subclass of HeapCType with a finalizer that reassigns __class__.\n\n"
7842 "__class__ is set to plain HeapCTypeSubclass during finalization.\n"
7843 "__init__ sets the 'value' attribute to 10 and 'value2' to 20.");
7844
7845 static int
7846 heapctypesubclasswithfinalizer_init(PyObject *self, PyObject *args, PyObject *kwargs)
7847 {
7848 PyTypeObject *base = (PyTypeObject *)PyType_GetSlot(Py_TYPE(self), Py_tp_base);
7849 initproc base_init = PyType_GetSlot(base, Py_tp_init);
7850 base_init(self, args, kwargs);
7851 return 0;
7852 }
7853
7854 static void
7855 heapctypesubclasswithfinalizer_finalize(PyObject *self)
7856 {
7857 PyObject *error_type, *error_value, *error_traceback, *m;
7858 PyObject *oldtype = NULL, *newtype = NULL, *refcnt = NULL;
7859
7860 /* Save the current exception, if any. */
7861 PyErr_Fetch(&error_type, &error_value, &error_traceback);
7862
7863 m = PyState_FindModule(&_testcapimodule);
7864 if (m == NULL) {
7865 goto cleanup_finalize;
7866 }
7867 oldtype = PyObject_GetAttrString(m, "HeapCTypeSubclassWithFinalizer");
7868 newtype = PyObject_GetAttrString(m, "HeapCTypeSubclass");
7869 if (oldtype == NULL || newtype == NULL) {
7870 goto cleanup_finalize;
7871 }
7872
7873 if (PyObject_SetAttrString(self, "__class__", newtype) < 0) {
7874 goto cleanup_finalize;
7875 }
7876 refcnt = PyLong_FromSsize_t(Py_REFCNT(oldtype));
7877 if (refcnt == NULL) {
7878 goto cleanup_finalize;
7879 }
7880 if (PyObject_SetAttrString(oldtype, "refcnt_in_del", refcnt) < 0) {
7881 goto cleanup_finalize;
7882 }
7883 Py_DECREF(refcnt);
7884 refcnt = PyLong_FromSsize_t(Py_REFCNT(newtype));
7885 if (refcnt == NULL) {
7886 goto cleanup_finalize;
7887 }
7888 if (PyObject_SetAttrString(newtype, "refcnt_in_del", refcnt) < 0) {
7889 goto cleanup_finalize;
7890 }
7891
7892 cleanup_finalize:
7893 Py_XDECREF(oldtype);
7894 Py_XDECREF(newtype);
7895 Py_XDECREF(refcnt);
7896
7897 /* Restore the saved exception. */
7898 PyErr_Restore(error_type, error_value, error_traceback);
7899 }
7900
7901 static PyType_Slot HeapCTypeSubclassWithFinalizer_slots[] = {
7902 {Py_tp_init, heapctypesubclasswithfinalizer_init},
7903 {Py_tp_members, heapctypesubclass_members},
7904 {Py_tp_finalize, heapctypesubclasswithfinalizer_finalize},
7905 {Py_tp_doc, (char*)heapctypesubclasswithfinalizer__doc__},
7906 {0, 0},
7907 };
7908
7909 static PyType_Spec HeapCTypeSubclassWithFinalizer_spec = {
7910 "_testcapi.HeapCTypeSubclassWithFinalizer",
7911 sizeof(HeapCTypeSubclassObject),
7912 0,
7913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
7914 HeapCTypeSubclassWithFinalizer_slots
7915 };
7916
7917 #endif
7918
7919 typedef struct {
7920 PyObject_HEAD
7921 PyObject *dict;
7922 } HeapCTypeWithDictObject;
7923
7924 static void
7925 heapctypewithdict_dealloc(HeapCTypeWithDictObject* self)
7926 {
7927
7928 PyTypeObject *tp = Py_TYPE(self);
7929 Py_XDECREF(self->dict);
7930 PyObject_Free(self);
7931 Py_DECREF(tp);
7932 }
7933
7934 static PyGetSetDef heapctypewithdict_getsetlist[] = {
7935 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
7936 {NULL} /* Sentinel */
7937 };
7938
7939 static struct PyMemberDef heapctypewithdict_members[] = {
7940 {"dictobj", T_OBJECT, offsetof(HeapCTypeWithDictObject, dict)},
7941 {"__dictoffset__", T_PYSSIZET, offsetof(HeapCTypeWithDictObject, dict), READONLY},
7942 {NULL} /* Sentinel */
7943 };
7944
7945 static PyType_Slot HeapCTypeWithDict_slots[] = {
7946 {Py_tp_members, heapctypewithdict_members},
7947 {Py_tp_getset, heapctypewithdict_getsetlist},
7948 {Py_tp_dealloc, heapctypewithdict_dealloc},
7949 {0, 0},
7950 };
7951
7952 static PyType_Spec HeapCTypeWithDict_spec = {
7953 "_testcapi.HeapCTypeWithDict",
7954 sizeof(HeapCTypeWithDictObject),
7955 0,
7956 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7957 HeapCTypeWithDict_slots
7958 };
7959
7960 static PyType_Spec HeapCTypeWithDict2_spec = {
7961 "_testcapi.HeapCTypeWithDict2",
7962 sizeof(HeapCTypeWithDictObject),
7963 0,
7964 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7965 HeapCTypeWithDict_slots
7966 };
7967
7968 static struct PyMemberDef heapctypewithnegativedict_members[] = {
7969 {"dictobj", T_OBJECT, offsetof(HeapCTypeWithDictObject, dict)},
7970 {"__dictoffset__", T_PYSSIZET, -(Py_ssize_t)sizeof(void*), READONLY},
7971 {NULL} /* Sentinel */
7972 };
7973
7974 static PyType_Slot HeapCTypeWithNegativeDict_slots[] = {
7975 {Py_tp_members, heapctypewithnegativedict_members},
7976 {Py_tp_getset, heapctypewithdict_getsetlist},
7977 {Py_tp_dealloc, heapctypewithdict_dealloc},
7978 {0, 0},
7979 };
7980
7981 static PyType_Spec HeapCTypeWithNegativeDict_spec = {
7982 "_testcapi.HeapCTypeWithNegativeDict",
7983 sizeof(HeapCTypeWithDictObject),
7984 0,
7985 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7986 HeapCTypeWithNegativeDict_slots
7987 };
7988
7989 typedef struct {
7990 PyObject_HEAD
7991 PyObject *weakreflist;
7992 } HeapCTypeWithWeakrefObject;
7993
7994 static struct PyMemberDef heapctypewithweakref_members[] = {
7995 {"weakreflist", T_OBJECT, offsetof(HeapCTypeWithWeakrefObject, weakreflist)},
7996 {"__weaklistoffset__", T_PYSSIZET,
7997 offsetof(HeapCTypeWithWeakrefObject, weakreflist), READONLY},
7998 {NULL} /* Sentinel */
7999 };
8000
8001 static void
8002 heapctypewithweakref_dealloc(HeapCTypeWithWeakrefObject* self)
8003 {
8004
8005 PyTypeObject *tp = Py_TYPE(self);
8006 if (self->weakreflist != NULL)
8007 PyObject_ClearWeakRefs((PyObject *) self);
8008 Py_XDECREF(self->weakreflist);
8009 PyObject_Free(self);
8010 Py_DECREF(tp);
8011 }
8012
8013 static PyType_Slot HeapCTypeWithWeakref_slots[] = {
8014 {Py_tp_members, heapctypewithweakref_members},
8015 {Py_tp_dealloc, heapctypewithweakref_dealloc},
8016 {0, 0},
8017 };
8018
8019 static PyType_Spec HeapCTypeWithWeakref_spec = {
8020 "_testcapi.HeapCTypeWithWeakref",
8021 sizeof(HeapCTypeWithWeakrefObject),
8022 0,
8023 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
8024 HeapCTypeWithWeakref_slots
8025 };
8026
8027 static PyType_Spec HeapCTypeWithWeakref2_spec = {
8028 "_testcapi.HeapCTypeWithWeakref2",
8029 sizeof(HeapCTypeWithWeakrefObject),
8030 0,
8031 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
8032 HeapCTypeWithWeakref_slots
8033 };
8034
8035 PyDoc_STRVAR(heapctypesetattr__doc__,
8036 "A heap type without GC, but with overridden __setattr__.\n\n"
8037 "The 'value' attribute is set to 10 in __init__ and updated via attribute setting.");
8038
8039 typedef struct {
8040 PyObject_HEAD
8041 long value;
8042 } HeapCTypeSetattrObject;
8043
8044 static struct PyMemberDef heapctypesetattr_members[] = {
8045 {"pvalue", T_LONG, offsetof(HeapCTypeSetattrObject, value)},
8046 {NULL} /* Sentinel */
8047 };
8048
8049 static int
8050 heapctypesetattr_init(PyObject *self, PyObject *args, PyObject *kwargs)
8051 {
8052 ((HeapCTypeSetattrObject *)self)->value = 10;
8053 return 0;
8054 }
8055
8056 static void
8057 heapctypesetattr_dealloc(HeapCTypeSetattrObject *self)
8058 {
8059 PyTypeObject *tp = Py_TYPE(self);
8060 PyObject_Free(self);
8061 Py_DECREF(tp);
8062 }
8063
8064 static int
8065 heapctypesetattr_setattro(HeapCTypeSetattrObject *self, PyObject *attr, PyObject *value)
8066 {
8067 PyObject *svalue = PyUnicode_FromString("value");
8068 if (svalue == NULL)
8069 return -1;
8070 int eq = PyObject_RichCompareBool(svalue, attr, Py_EQ);
8071 Py_DECREF(svalue);
8072 if (eq < 0)
8073 return -1;
8074 if (!eq) {
8075 return PyObject_GenericSetAttr((PyObject*) self, attr, value);
8076 }
8077 if (value == NULL) {
8078 self->value = 0;
8079 return 0;
8080 }
8081 PyObject *ivalue = PyNumber_Long(value);
8082 if (ivalue == NULL)
8083 return -1;
8084 long v = PyLong_AsLong(ivalue);
8085 Py_DECREF(ivalue);
8086 if (v == -1 && PyErr_Occurred())
8087 return -1;
8088 self->value = v;
8089 return 0;
8090 }
8091
8092 static PyType_Slot HeapCTypeSetattr_slots[] = {
8093 {Py_tp_init, heapctypesetattr_init},
8094 {Py_tp_members, heapctypesetattr_members},
8095 {Py_tp_setattro, heapctypesetattr_setattro},
8096 {Py_tp_dealloc, heapctypesetattr_dealloc},
8097 {Py_tp_doc, (char*)heapctypesetattr__doc__},
8098 {0, 0},
8099 };
8100
8101 static PyType_Spec HeapCTypeSetattr_spec = {
8102 "_testcapi.HeapCTypeSetattr",
8103 sizeof(HeapCTypeSetattrObject),
8104 0,
8105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
8106 HeapCTypeSetattr_slots
8107 };
8108
8109 static PyMethodDef meth_instance_methods[] = {
8110 {"meth_varargs", meth_varargs, METH_VARARGS},
8111 {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
8112 {"meth_o", meth_o, METH_O},
8113 {"meth_noargs", meth_noargs, METH_NOARGS},
8114 {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL},
8115 {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS},
8116 {NULL, NULL} /* sentinel */
8117 };
8118
8119
8120 static PyTypeObject MethInstance_Type = {
8121 PyVarObject_HEAD_INIT(NULL, 0)
8122 "MethInstance",
8123 sizeof(PyObject),
8124 .tp_new = PyType_GenericNew,
8125 .tp_flags = Py_TPFLAGS_DEFAULT,
8126 .tp_methods = meth_instance_methods,
8127 .tp_doc = (char*)PyDoc_STR(
8128 "Class with normal (instance) methods to test calling conventions"),
8129 };
8130
8131 static PyMethodDef meth_class_methods[] = {
8132 {"meth_varargs", meth_varargs, METH_VARARGS|METH_CLASS},
8133 {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS|METH_CLASS},
8134 {"meth_o", meth_o, METH_O|METH_CLASS},
8135 {"meth_noargs", meth_noargs, METH_NOARGS|METH_CLASS},
8136 {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL|METH_CLASS},
8137 {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS|METH_CLASS},
8138 {NULL, NULL} /* sentinel */
8139 };
8140
8141
8142 static PyTypeObject MethClass_Type = {
8143 PyVarObject_HEAD_INIT(NULL, 0)
8144 "MethClass",
8145 sizeof(PyObject),
8146 .tp_new = PyType_GenericNew,
8147 .tp_flags = Py_TPFLAGS_DEFAULT,
8148 .tp_methods = meth_class_methods,
8149 .tp_doc = PyDoc_STR(
8150 "Class with class methods to test calling conventions"),
8151 };
8152
8153 static PyMethodDef meth_static_methods[] = {
8154 {"meth_varargs", meth_varargs, METH_VARARGS|METH_STATIC},
8155 {"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS|METH_STATIC},
8156 {"meth_o", meth_o, METH_O|METH_STATIC},
8157 {"meth_noargs", meth_noargs, METH_NOARGS|METH_STATIC},
8158 {"meth_fastcall", _PyCFunction_CAST(meth_fastcall), METH_FASTCALL|METH_STATIC},
8159 {"meth_fastcall_keywords", _PyCFunction_CAST(meth_fastcall_keywords), METH_FASTCALL|METH_KEYWORDS|METH_STATIC},
8160 {NULL, NULL} /* sentinel */
8161 };
8162
8163
8164 static PyTypeObject MethStatic_Type = {
8165 PyVarObject_HEAD_INIT(NULL, 0)
8166 "MethStatic",
8167 sizeof(PyObject),
8168 .tp_new = PyType_GenericNew,
8169 .tp_flags = Py_TPFLAGS_DEFAULT,
8170 .tp_methods = meth_static_methods,
8171 .tp_doc = PyDoc_STR(
8172 "Class with static methods to test calling conventions"),
8173 };
8174
8175 /* ContainerNoGC -- a simple container without GC methods */
8176
8177 typedef struct {
8178 PyObject_HEAD
8179 PyObject *value;
8180 } ContainerNoGCobject;
8181
8182 static PyObject *
8183 ContainerNoGC_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
8184 {
8185 PyObject *value;
8186 char *names[] = {"value", NULL};
8187 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", names, &value)) {
8188 return NULL;
8189 }
8190 PyObject *self = type->tp_alloc(type, 0);
8191 if (self == NULL) {
8192 return NULL;
8193 }
8194 Py_INCREF(value);
8195 ((ContainerNoGCobject *)self)->value = value;
8196 return self;
8197 }
8198
8199 static void
8200 ContainerNoGC_dealloc(ContainerNoGCobject *self)
8201 {
8202 Py_DECREF(self->value);
8203 Py_TYPE(self)->tp_free((PyObject *)self);
8204 }
8205
8206 static PyMemberDef ContainerNoGC_members[] = {
8207 {"value", T_OBJECT, offsetof(ContainerNoGCobject, value), READONLY,
8208 PyDoc_STR("a container value for test purposes")},
8209 {0}
8210 };
8211
8212 static PyTypeObject ContainerNoGC_type = {
8213 PyVarObject_HEAD_INIT(NULL, 0)
8214 "_testcapi.ContainerNoGC",
8215 sizeof(ContainerNoGCobject),
8216 .tp_dealloc = (destructor)ContainerNoGC_dealloc,
8217 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
8218 .tp_members = ContainerNoGC_members,
8219 .tp_new = ContainerNoGC_new,
8220 };
8221
8222
8223 static struct PyModuleDef _testcapimodule = {
8224 PyModuleDef_HEAD_INIT,
8225 "_testcapi",
8226 NULL,
8227 -1,
8228 TestMethods,
8229 NULL,
8230 NULL,
8231 NULL,
8232 NULL
8233 };
8234
8235 /* Per PEP 489, this module will not be converted to multi-phase initialization
8236 */
8237
8238 PyMODINIT_FUNC
8239 PyInit__testcapi(void)
8240 {
8241 PyObject *m;
8242
8243 m = PyModule_Create(&_testcapimodule);
8244 if (m == NULL)
8245 return NULL;
8246
8247 Py_SET_TYPE(&_HashInheritanceTester_Type, &PyType_Type);
8248
8249 Py_SET_TYPE(&test_structmembersType, &PyType_Type);
8250 Py_INCREF(&test_structmembersType);
8251 /* don't use a name starting with "test", since we don't want
8252 test_capi to automatically call this */
8253 PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
8254 if (PyType_Ready(&matmulType) < 0)
8255 return NULL;
8256 Py_INCREF(&matmulType);
8257 PyModule_AddObject(m, "matmulType", (PyObject *)&matmulType);
8258 if (PyType_Ready(&ipowType) < 0) {
8259 return NULL;
8260 }
8261 Py_INCREF(&ipowType);
8262 PyModule_AddObject(m, "ipowType", (PyObject *)&ipowType);
8263
8264 if (PyType_Ready(&awaitType) < 0)
8265 return NULL;
8266 Py_INCREF(&awaitType);
8267 PyModule_AddObject(m, "awaitType", (PyObject *)&awaitType);
8268
8269 MyList_Type.tp_base = &PyList_Type;
8270 if (PyType_Ready(&MyList_Type) < 0)
8271 return NULL;
8272 Py_INCREF(&MyList_Type);
8273 PyModule_AddObject(m, "MyList", (PyObject *)&MyList_Type);
8274
8275 if (PyType_Ready(&MethodDescriptorBase_Type) < 0)
8276 return NULL;
8277 Py_INCREF(&MethodDescriptorBase_Type);
8278 PyModule_AddObject(m, "MethodDescriptorBase", (PyObject *)&MethodDescriptorBase_Type);
8279
8280 MethodDescriptorDerived_Type.tp_base = &MethodDescriptorBase_Type;
8281 if (PyType_Ready(&MethodDescriptorDerived_Type) < 0)
8282 return NULL;
8283 Py_INCREF(&MethodDescriptorDerived_Type);
8284 PyModule_AddObject(m, "MethodDescriptorDerived", (PyObject *)&MethodDescriptorDerived_Type);
8285
8286 MethodDescriptorNopGet_Type.tp_base = &MethodDescriptorBase_Type;
8287 if (PyType_Ready(&MethodDescriptorNopGet_Type) < 0)
8288 return NULL;
8289 Py_INCREF(&MethodDescriptorNopGet_Type);
8290 PyModule_AddObject(m, "MethodDescriptorNopGet", (PyObject *)&MethodDescriptorNopGet_Type);
8291
8292 MethodDescriptor2_Type.tp_base = &MethodDescriptorBase_Type;
8293 if (PyType_Ready(&MethodDescriptor2_Type) < 0)
8294 return NULL;
8295 Py_INCREF(&MethodDescriptor2_Type);
8296 PyModule_AddObject(m, "MethodDescriptor2", (PyObject *)&MethodDescriptor2_Type);
8297
8298 if (PyType_Ready(&GenericAlias_Type) < 0)
8299 return NULL;
8300 Py_INCREF(&GenericAlias_Type);
8301 PyModule_AddObject(m, "GenericAlias", (PyObject *)&GenericAlias_Type);
8302
8303 if (PyType_Ready(&Generic_Type) < 0)
8304 return NULL;
8305 Py_INCREF(&Generic_Type);
8306 PyModule_AddObject(m, "Generic", (PyObject *)&Generic_Type);
8307
8308 if (PyType_Ready(&MethInstance_Type) < 0)
8309 return NULL;
8310 Py_INCREF(&MethInstance_Type);
8311 PyModule_AddObject(m, "MethInstance", (PyObject *)&MethInstance_Type);
8312
8313 if (PyType_Ready(&MethClass_Type) < 0)
8314 return NULL;
8315 Py_INCREF(&MethClass_Type);
8316 PyModule_AddObject(m, "MethClass", (PyObject *)&MethClass_Type);
8317
8318 if (PyType_Ready(&MethStatic_Type) < 0)
8319 return NULL;
8320 Py_INCREF(&MethStatic_Type);
8321 PyModule_AddObject(m, "MethStatic", (PyObject *)&MethStatic_Type);
8322
8323 PyRecursingInfinitelyError_Type.tp_base = (PyTypeObject *)PyExc_Exception;
8324 if (PyType_Ready(&PyRecursingInfinitelyError_Type) < 0) {
8325 return NULL;
8326 }
8327 Py_INCREF(&PyRecursingInfinitelyError_Type);
8328 PyModule_AddObject(m, "RecursingInfinitelyError",
8329 (PyObject *)&PyRecursingInfinitelyError_Type);
8330
8331 PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
8332 PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
8333 PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
8334 PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
8335 PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
8336 PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
8337 PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
8338 PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
8339 PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
8340 PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
8341 PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
8342 PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
8343 PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
8344 PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
8345 PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
8346 PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
8347 PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(LLONG_MAX));
8348 PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(LLONG_MIN));
8349 PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(ULLONG_MAX));
8350 PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
8351 PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
8352 PyModule_AddObject(m, "SIZEOF_TIME_T", PyLong_FromSsize_t(sizeof(time_t)));
8353 PyModule_AddObject(m, "SIZEOF_PID_T", PyLong_FromSsize_t(sizeof(pid_t)));
8354 PyModule_AddObject(m, "Py_Version", PyLong_FromUnsignedLong(Py_Version));
8355 Py_INCREF(&PyInstanceMethod_Type);
8356 PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
8357
8358 PyModule_AddIntConstant(m, "the_number_three", 3);
8359 PyObject *v;
8360 #ifdef WITH_PYMALLOC
8361 v = Py_True;
8362 #else
8363 v = Py_False;
8364 #endif
8365 PyModule_AddObject(m, "WITH_PYMALLOC", Py_NewRef(v));
8366
8367 #ifdef USE_STACKCHECK
8368 v = Py_True;
8369 #else
8370 v = Py_False;
8371 #endif
8372 PyModule_AddObject(m, "USE_STACKCHECK", Py_NewRef(v));
8373
8374 TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
8375 Py_INCREF(TestError);
8376 PyModule_AddObject(m, "error", TestError);
8377
8378 PyObject *HeapDocCType = PyType_FromSpec(&HeapDocCType_spec);
8379 if (HeapDocCType == NULL) {
8380 return NULL;
8381 }
8382 PyModule_AddObject(m, "HeapDocCType", HeapDocCType);
8383
8384 /* bpo-41832: Add a new type to test PyType_FromSpec()
8385 now can accept a NULL tp_doc slot. */
8386 PyObject *NullTpDocType = PyType_FromSpec(&NullTpDocType_spec);
8387 if (NullTpDocType == NULL) {
8388 return NULL;
8389 }
8390 PyModule_AddObject(m, "NullTpDocType", NullTpDocType);
8391
8392 PyObject *HeapGcCType = PyType_FromSpec(&HeapGcCType_spec);
8393 if (HeapGcCType == NULL) {
8394 return NULL;
8395 }
8396 PyModule_AddObject(m, "HeapGcCType", HeapGcCType);
8397
8398 PyObject *HeapCType = PyType_FromSpec(&HeapCType_spec);
8399 if (HeapCType == NULL) {
8400 return NULL;
8401 }
8402 PyObject *subclass_bases = PyTuple_Pack(1, HeapCType);
8403 if (subclass_bases == NULL) {
8404 return NULL;
8405 }
8406 PyObject *HeapCTypeSubclass = PyType_FromSpecWithBases(&HeapCTypeSubclass_spec, subclass_bases);
8407 if (HeapCTypeSubclass == NULL) {
8408 return NULL;
8409 }
8410 Py_DECREF(subclass_bases);
8411 PyModule_AddObject(m, "HeapCTypeSubclass", HeapCTypeSubclass);
8412
8413 PyObject *HeapCTypeWithDict = PyType_FromSpec(&HeapCTypeWithDict_spec);
8414 if (HeapCTypeWithDict == NULL) {
8415 return NULL;
8416 }
8417 PyModule_AddObject(m, "HeapCTypeWithDict", HeapCTypeWithDict);
8418
8419 PyObject *HeapCTypeWithDict2 = PyType_FromSpec(&HeapCTypeWithDict2_spec);
8420 if (HeapCTypeWithDict2 == NULL) {
8421 return NULL;
8422 }
8423 PyModule_AddObject(m, "HeapCTypeWithDict2", HeapCTypeWithDict2);
8424
8425 PyObject *HeapCTypeWithNegativeDict = PyType_FromSpec(&HeapCTypeWithNegativeDict_spec);
8426 if (HeapCTypeWithNegativeDict == NULL) {
8427 return NULL;
8428 }
8429 PyModule_AddObject(m, "HeapCTypeWithNegativeDict", HeapCTypeWithNegativeDict);
8430
8431 PyObject *HeapCTypeWithWeakref = PyType_FromSpec(&HeapCTypeWithWeakref_spec);
8432 if (HeapCTypeWithWeakref == NULL) {
8433 return NULL;
8434 }
8435 PyModule_AddObject(m, "HeapCTypeWithWeakref", HeapCTypeWithWeakref);
8436
8437 PyObject *HeapCTypeWithBuffer = PyType_FromSpec(&HeapCTypeWithBuffer_spec);
8438 if (HeapCTypeWithBuffer == NULL) {
8439 return NULL;
8440 }
8441 PyModule_AddObject(m, "HeapCTypeWithBuffer", HeapCTypeWithBuffer);
8442
8443 PyObject *HeapCTypeWithWeakref2 = PyType_FromSpec(&HeapCTypeWithWeakref2_spec);
8444 if (HeapCTypeWithWeakref2 == NULL) {
8445 return NULL;
8446 }
8447 PyModule_AddObject(m, "HeapCTypeWithWeakref2", HeapCTypeWithWeakref2);
8448
8449 PyObject *HeapCTypeSetattr = PyType_FromSpec(&HeapCTypeSetattr_spec);
8450 if (HeapCTypeSetattr == NULL) {
8451 return NULL;
8452 }
8453 PyModule_AddObject(m, "HeapCTypeSetattr", HeapCTypeSetattr);
8454
8455 PyObject *subclass_with_finalizer_bases = PyTuple_Pack(1, HeapCTypeSubclass);
8456 if (subclass_with_finalizer_bases == NULL) {
8457 return NULL;
8458 }
8459 #ifndef PYPY_VERSION
8460 PyObject *HeapCTypeSubclassWithFinalizer = PyType_FromSpecWithBases(
8461 &HeapCTypeSubclassWithFinalizer_spec, subclass_with_finalizer_bases);
8462 if (HeapCTypeSubclassWithFinalizer == NULL) {
8463 return NULL;
8464 }
8465 Py_DECREF(subclass_with_finalizer_bases);
8466 PyModule_AddObject(m, "HeapCTypeSubclassWithFinalizer", HeapCTypeSubclassWithFinalizer);
8467 #endif
8468
8469 if (PyType_Ready(&ContainerNoGC_type) < 0) {
8470 return NULL;
8471 }
8472 Py_INCREF(&ContainerNoGC_type);
8473 if (PyModule_AddObject(m, "ContainerNoGC",
8474 (PyObject *) &ContainerNoGC_type) < 0)
8475 return NULL;
8476
8477 #ifndef PYPY_VERSION
8478 PyState_AddModule(m, &_testcapimodule);
8479 #endif
8480 return m;
8481 }
8482
8483 static PyObject *
8484 negative_dictoffset(PyObject *self, PyObject *Py_UNUSED(ignored))
8485 {
8486 return PyType_FromSpec(&HeapCTypeWithNegativeDict_spec);
8487 }
8488
8489 /* Test the C API exposed when PY_SSIZE_T_CLEAN is not defined */
8490
8491 #undef Py_BuildValue
8492 #ifdef PYPY_VERSION
8493 #define Py_BuildValue PyPy_BuildValue
8494 #endif
8495 PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...);
8496
8497 static PyObject *
8498 test_buildvalue_issue38913(PyObject *self, PyObject *Py_UNUSED(ignored))
8499 {
8500 PyObject *res;
8501 const char str[] = "string";
8502 const Py_UNICODE unicode[] = L"unicode";
8503 assert(!PyErr_Occurred());
8504
8505 res = Py_BuildValue("(s#O)", str, 1, Py_None);
8506 assert(res == NULL);
8507 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
8508 return NULL;
8509 }
8510 PyErr_Clear();
8511
8512 res = Py_BuildValue("(z#O)", str, 1, Py_None);
8513 assert(res == NULL);
8514 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
8515 return NULL;
8516 }
8517 PyErr_Clear();
8518
8519 res = Py_BuildValue("(y#O)", str, 1, Py_None);
8520 assert(res == NULL);
8521 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
8522 return NULL;
8523 }
8524 PyErr_Clear();
8525
8526 res = Py_BuildValue("(u#O)", unicode, 1, Py_None);
8527 assert(res == NULL);
8528 if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
8529 return NULL;
8530 }
8531 PyErr_Clear();
8532
8533
8534 Py_RETURN_NONE;
8535 }
8536
8537 #undef PyArg_ParseTupleAndKeywords
8538 #ifdef PYPY_VERSION
8539 #define PyArg_ParseTupleAndKeywords PyPyArg_ParseTupleAndKeywords
8540 #endif
8541 PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
8542 const char *, char **, ...);
8543
8544 static PyObject *
8545 getargs_s_hash_int(PyObject *self, PyObject *args, PyObject *kwargs)
8546 {
8547 static char *keywords[] = {"", "", "x", NULL};
8548 Py_buffer buf = {NULL};
8549 const char *s;
8550 int len;
8551 int i = 0;
8552 if (!PyPyArg_ParseTupleAndKeywords(args, kwargs, "w*|s#i", keywords, &buf, &s, &len, &i))
8553 return NULL;
8554 PyBuffer_Release(&buf);
8555 Py_RETURN_NONE;
8556 }
8557
8558 static PyObject *
8559 getargs_s_hash_int2(PyObject *self, PyObject *args, PyObject *kwargs)
8560 {
8561 static char *keywords[] = {"", "", "x", NULL};
8562 Py_buffer buf = {NULL};
8563 const char *s;
8564 int len;
8565 int i = 0;
8566 if (!PyPyArg_ParseTupleAndKeywords(args, kwargs, "w*|(s#)i", keywords, &buf, &s, &len, &i))
8567 return NULL;
8568 PyBuffer_Release(&buf);
8569 Py_RETURN_NONE;
8570 }
8571
8572 static PyObject *
8573 gh_99240_clear_args(PyObject *self, PyObject *args)
8574 {
8575 char *a = NULL;
8576 char *b = NULL;
8577
8578 if (!PyArg_ParseTuple(args, "eses", "idna", &a, "idna", &b)) {
8579 if (a || b) {
8580 PyErr_Clear();
8581 PyErr_SetString(PyExc_AssertionError, "Arguments are not cleared.");
8582 }
8583 return NULL;
8584 }
8585 PyMem_Free(a);
8586 PyMem_Free(b);
8587 Py_RETURN_NONE;
8588 }