ยปCore Development>Code coverage>Modules/_testcapimodule.c

Python code coverage for Modules/_testcapimodule.c

#countcontent
1n/a/*
2n/a * C Extension module to test Python interpreter C APIs.
3n/a *
4n/a * The 'test_*' functions exported by this module are run as part of the
5n/a * standard Python regression test, via Lib/test/test_capi.py.
6n/a */
7n/a
8n/a#define PY_SSIZE_T_CLEAN
9n/a
10n/a#include "Python.h"
11n/a#include <float.h>
12n/a#include "structmember.h"
13n/a#include "datetime.h"
14n/a#include "marshal.h"
15n/a#include <signal.h>
16n/a
17n/a#ifdef MS_WINDOWS
18n/a# include <winsock2.h> /* struct timeval */
19n/a#endif
20n/a
21n/a#ifdef WITH_THREAD
22n/a#include "pythread.h"
23n/a#endif /* WITH_THREAD */
24n/astatic PyObject *TestError; /* set to exception object in init */
25n/a
26n/a/* Raise TestError with test_name + ": " + msg, and return NULL. */
27n/a
28n/astatic PyObject *
29n/araiseTestError(const char* test_name, const char* msg)
30n/a{
31n/a PyErr_Format(TestError, "%s: %s", test_name, msg);
32n/a return NULL;
33n/a}
34n/a
35n/a/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
36n/a
37n/a The ones derived from autoconf on the UNIX-like OSes can be relied
38n/a upon (in the absence of sloppy cross-compiling), but the Windows
39n/a platforms have these hardcoded. Better safe than sorry.
40n/a*/
41n/astatic PyObject*
42n/asizeof_error(const char* fatname, const char* typname,
43n/a int expected, int got)
44n/a{
45n/a PyErr_Format(TestError,
46n/a "%s #define == %d but sizeof(%s) == %d",
47n/a fatname, expected, typname, got);
48n/a return (PyObject*)NULL;
49n/a}
50n/a
51n/astatic PyObject*
52n/atest_config(PyObject *self)
53n/a{
54n/a#define CHECK_SIZEOF(FATNAME, TYPE) \
55n/a if (FATNAME != sizeof(TYPE)) \
56n/a return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
57n/a
58n/a CHECK_SIZEOF(SIZEOF_SHORT, short);
59n/a CHECK_SIZEOF(SIZEOF_INT, int);
60n/a CHECK_SIZEOF(SIZEOF_LONG, long);
61n/a CHECK_SIZEOF(SIZEOF_VOID_P, void*);
62n/a CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
63n/a CHECK_SIZEOF(SIZEOF_LONG_LONG, long long);
64n/a
65n/a#undef CHECK_SIZEOF
66n/a
67n/a Py_RETURN_NONE;
68n/a}
69n/a
70n/astatic PyObject*
71n/atest_sizeof_c_types(PyObject *self)
72n/a{
73n/a#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
74n/a#pragma GCC diagnostic push
75n/a#pragma GCC diagnostic ignored "-Wtype-limits"
76n/a#endif
77n/a#define CHECK_SIZEOF(TYPE, EXPECTED) \
78n/a if (EXPECTED != sizeof(TYPE)) { \
79n/a PyErr_Format(TestError, \
80n/a "sizeof(%s) = %u instead of %u", \
81n/a #TYPE, sizeof(TYPE), EXPECTED); \
82n/a return (PyObject*)NULL; \
83n/a }
84n/a#define IS_SIGNED(TYPE) (((TYPE)-1) < (TYPE)0)
85n/a#define CHECK_SIGNNESS(TYPE, SIGNED) \
86n/a if (IS_SIGNED(TYPE) != SIGNED) { \
87n/a PyErr_Format(TestError, \
88n/a "%s signness is, instead of %i", \
89n/a #TYPE, IS_SIGNED(TYPE), SIGNED); \
90n/a return (PyObject*)NULL; \
91n/a }
92n/a
93n/a /* integer types */
94n/a CHECK_SIZEOF(Py_UCS1, 1);
95n/a CHECK_SIZEOF(Py_UCS2, 2);
96n/a CHECK_SIZEOF(Py_UCS4, 4);
97n/a CHECK_SIGNNESS(Py_UCS1, 0);
98n/a CHECK_SIGNNESS(Py_UCS2, 0);
99n/a CHECK_SIGNNESS(Py_UCS4, 0);
100n/a CHECK_SIZEOF(int32_t, 4);
101n/a CHECK_SIGNNESS(int32_t, 1);
102n/a CHECK_SIZEOF(uint32_t, 4);
103n/a CHECK_SIGNNESS(uint32_t, 0);
104n/a CHECK_SIZEOF(int64_t, 8);
105n/a CHECK_SIGNNESS(int64_t, 1);
106n/a CHECK_SIZEOF(uint64_t, 8);
107n/a CHECK_SIGNNESS(uint64_t, 0);
108n/a
109n/a /* pointer/size types */
110n/a CHECK_SIZEOF(size_t, sizeof(void *));
111n/a CHECK_SIGNNESS(size_t, 0);
112n/a CHECK_SIZEOF(Py_ssize_t, sizeof(void *));
113n/a CHECK_SIGNNESS(Py_ssize_t, 1);
114n/a
115n/a CHECK_SIZEOF(uintptr_t, sizeof(void *));
116n/a CHECK_SIGNNESS(uintptr_t, 0);
117n/a CHECK_SIZEOF(intptr_t, sizeof(void *));
118n/a CHECK_SIGNNESS(intptr_t, 1);
119n/a
120n/a Py_RETURN_NONE;
121n/a
122n/a#undef IS_SIGNED
123n/a#undef CHECK_SIGNESS
124n/a#undef CHECK_SIZEOF
125n/a#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
126n/a#pragma GCC diagnostic pop
127n/a#endif
128n/a}
129n/a
130n/a
131n/astatic PyObject*
132n/atest_list_api(PyObject *self)
133n/a{
134n/a PyObject* list;
135n/a int i;
136n/a
137n/a /* SF bug 132008: PyList_Reverse segfaults */
138n/a#define NLIST 30
139n/a list = PyList_New(NLIST);
140n/a if (list == (PyObject*)NULL)
141n/a return (PyObject*)NULL;
142n/a /* list = range(NLIST) */
143n/a for (i = 0; i < NLIST; ++i) {
144n/a PyObject* anint = PyLong_FromLong(i);
145n/a if (anint == (PyObject*)NULL) {
146n/a Py_DECREF(list);
147n/a return (PyObject*)NULL;
148n/a }
149n/a PyList_SET_ITEM(list, i, anint);
150n/a }
151n/a /* list.reverse(), via PyList_Reverse() */
152n/a i = PyList_Reverse(list); /* should not blow up! */
153n/a if (i != 0) {
154n/a Py_DECREF(list);
155n/a return (PyObject*)NULL;
156n/a }
157n/a /* Check that list == range(29, -1, -1) now */
158n/a for (i = 0; i < NLIST; ++i) {
159n/a PyObject* anint = PyList_GET_ITEM(list, i);
160n/a if (PyLong_AS_LONG(anint) != NLIST-1-i) {
161n/a PyErr_SetString(TestError,
162n/a "test_list_api: reverse screwed up");
163n/a Py_DECREF(list);
164n/a return (PyObject*)NULL;
165n/a }
166n/a }
167n/a Py_DECREF(list);
168n/a#undef NLIST
169n/a
170n/a Py_RETURN_NONE;
171n/a}
172n/a
173n/astatic int
174n/atest_dict_inner(int count)
175n/a{
176n/a Py_ssize_t pos = 0, iterations = 0;
177n/a int i;
178n/a PyObject *dict = PyDict_New();
179n/a PyObject *v, *k;
180n/a
181n/a if (dict == NULL)
182n/a return -1;
183n/a
184n/a for (i = 0; i < count; i++) {
185n/a v = PyLong_FromLong(i);
186n/a if (v == NULL) {
187n/a return -1;
188n/a }
189n/a if (PyDict_SetItem(dict, v, v) < 0) {
190n/a Py_DECREF(v);
191n/a return -1;
192n/a }
193n/a Py_DECREF(v);
194n/a }
195n/a
196n/a while (PyDict_Next(dict, &pos, &k, &v)) {
197n/a PyObject *o;
198n/a iterations++;
199n/a
200n/a i = PyLong_AS_LONG(v) + 1;
201n/a o = PyLong_FromLong(i);
202n/a if (o == NULL)
203n/a return -1;
204n/a if (PyDict_SetItem(dict, k, o) < 0) {
205n/a Py_DECREF(o);
206n/a return -1;
207n/a }
208n/a Py_DECREF(o);
209n/a }
210n/a
211n/a Py_DECREF(dict);
212n/a
213n/a if (iterations != count) {
214n/a PyErr_SetString(
215n/a TestError,
216n/a "test_dict_iteration: dict iteration went wrong ");
217n/a return -1;
218n/a } else {
219n/a return 0;
220n/a }
221n/a}
222n/a
223n/astatic PyObject*
224n/atest_dict_iteration(PyObject* self)
225n/a{
226n/a int i;
227n/a
228n/a for (i = 0; i < 200; i++) {
229n/a if (test_dict_inner(i) < 0) {
230n/a return NULL;
231n/a }
232n/a }
233n/a
234n/a Py_RETURN_NONE;
235n/a}
236n/a
237n/astatic PyObject*
238n/adict_getitem_knownhash(PyObject *self, PyObject *args)
239n/a{
240n/a PyObject *mp, *key, *result;
241n/a Py_ssize_t hash;
242n/a
243n/a if (!PyArg_ParseTuple(args, "OOn:dict_getitem_knownhash",
244n/a &mp, &key, &hash)) {
245n/a return NULL;
246n/a }
247n/a
248n/a result = _PyDict_GetItem_KnownHash(mp, key, (Py_hash_t)hash);
249n/a if (result == NULL && !PyErr_Occurred()) {
250n/a _PyErr_SetKeyError(key);
251n/a return NULL;
252n/a }
253n/a
254n/a Py_XINCREF(result);
255n/a return result;
256n/a}
257n/a
258n/astatic PyObject*
259n/adict_hassplittable(PyObject *self, PyObject *arg)
260n/a{
261n/a if (!PyDict_Check(arg)) {
262n/a PyErr_Format(PyExc_TypeError,
263n/a "dict_hassplittable() argument must be dict, not '%s'",
264n/a arg->ob_type->tp_name);
265n/a return NULL;
266n/a }
267n/a
268n/a return PyBool_FromLong(_PyDict_HasSplitTable((PyDictObject*)arg));
269n/a}
270n/a
271n/a/* Issue #4701: Check that PyObject_Hash implicitly calls
272n/a * PyType_Ready if it hasn't already been called
273n/a */
274n/astatic PyTypeObject _HashInheritanceTester_Type = {
275n/a PyVarObject_HEAD_INIT(NULL, 0)
276n/a "hashinheritancetester", /* Name of this type */
277n/a sizeof(PyObject), /* Basic object size */
278n/a 0, /* Item size for varobject */
279n/a (destructor)PyObject_Del, /* tp_dealloc */
280n/a 0, /* tp_print */
281n/a 0, /* tp_getattr */
282n/a 0, /* tp_setattr */
283n/a 0, /* tp_reserved */
284n/a 0, /* tp_repr */
285n/a 0, /* tp_as_number */
286n/a 0, /* tp_as_sequence */
287n/a 0, /* tp_as_mapping */
288n/a 0, /* tp_hash */
289n/a 0, /* tp_call */
290n/a 0, /* tp_str */
291n/a PyObject_GenericGetAttr, /* tp_getattro */
292n/a 0, /* tp_setattro */
293n/a 0, /* tp_as_buffer */
294n/a Py_TPFLAGS_DEFAULT, /* tp_flags */
295n/a 0, /* tp_doc */
296n/a 0, /* tp_traverse */
297n/a 0, /* tp_clear */
298n/a 0, /* tp_richcompare */
299n/a 0, /* tp_weaklistoffset */
300n/a 0, /* tp_iter */
301n/a 0, /* tp_iternext */
302n/a 0, /* tp_methods */
303n/a 0, /* tp_members */
304n/a 0, /* tp_getset */
305n/a 0, /* tp_base */
306n/a 0, /* tp_dict */
307n/a 0, /* tp_descr_get */
308n/a 0, /* tp_descr_set */
309n/a 0, /* tp_dictoffset */
310n/a 0, /* tp_init */
311n/a 0, /* tp_alloc */
312n/a PyType_GenericNew, /* tp_new */
313n/a};
314n/a
315n/astatic PyObject*
316n/atest_lazy_hash_inheritance(PyObject* self)
317n/a{
318n/a PyTypeObject *type;
319n/a PyObject *obj;
320n/a Py_hash_t hash;
321n/a
322n/a type = &_HashInheritanceTester_Type;
323n/a
324n/a if (type->tp_dict != NULL)
325n/a /* The type has already been initialized. This probably means
326n/a -R is being used. */
327n/a Py_RETURN_NONE;
328n/a
329n/a
330n/a obj = PyObject_New(PyObject, type);
331n/a if (obj == NULL) {
332n/a PyErr_Clear();
333n/a PyErr_SetString(
334n/a TestError,
335n/a "test_lazy_hash_inheritance: failed to create object");
336n/a return NULL;
337n/a }
338n/a
339n/a if (type->tp_dict != NULL) {
340n/a PyErr_SetString(
341n/a TestError,
342n/a "test_lazy_hash_inheritance: type initialised too soon");
343n/a Py_DECREF(obj);
344n/a return NULL;
345n/a }
346n/a
347n/a hash = PyObject_Hash(obj);
348n/a if ((hash == -1) && PyErr_Occurred()) {
349n/a PyErr_Clear();
350n/a PyErr_SetString(
351n/a TestError,
352n/a "test_lazy_hash_inheritance: could not hash object");
353n/a Py_DECREF(obj);
354n/a return NULL;
355n/a }
356n/a
357n/a if (type->tp_dict == NULL) {
358n/a PyErr_SetString(
359n/a TestError,
360n/a "test_lazy_hash_inheritance: type not initialised by hash()");
361n/a Py_DECREF(obj);
362n/a return NULL;
363n/a }
364n/a
365n/a if (type->tp_hash != PyType_Type.tp_hash) {
366n/a PyErr_SetString(
367n/a TestError,
368n/a "test_lazy_hash_inheritance: unexpected hash function");
369n/a Py_DECREF(obj);
370n/a return NULL;
371n/a }
372n/a
373n/a Py_DECREF(obj);
374n/a
375n/a Py_RETURN_NONE;
376n/a}
377n/a
378n/a
379n/a/* Tests of PyLong_{As, From}{Unsigned,}Long(), and
380n/a PyLong_{As, From}{Unsigned,}LongLong().
381n/a
382n/a Note that the meat of the test is contained in testcapi_long.h.
383n/a This is revolting, but delicate code duplication is worse: "almost
384n/a exactly the same" code is needed to test long long, but the ubiquitous
385n/a dependence on type names makes it impossible to use a parameterized
386n/a function. A giant macro would be even worse than this. A C++ template
387n/a would be perfect.
388n/a
389n/a The "report an error" functions are deliberately not part of the #include
390n/a file: if the test fails, you can set a breakpoint in the appropriate
391n/a error function directly, and crawl back from there in the debugger.
392n/a*/
393n/a
394n/a#define UNBIND(X) Py_DECREF(X); (X) = NULL
395n/a
396n/astatic PyObject *
397n/araise_test_long_error(const char* msg)
398n/a{
399n/a return raiseTestError("test_long_api", msg);
400n/a}
401n/a
402n/a#define TESTNAME test_long_api_inner
403n/a#define TYPENAME long
404n/a#define F_S_TO_PY PyLong_FromLong
405n/a#define F_PY_TO_S PyLong_AsLong
406n/a#define F_U_TO_PY PyLong_FromUnsignedLong
407n/a#define F_PY_TO_U PyLong_AsUnsignedLong
408n/a
409n/a#include "testcapi_long.h"
410n/a
411n/astatic PyObject *
412n/atest_long_api(PyObject* self)
413n/a{
414n/a return TESTNAME(raise_test_long_error);
415n/a}
416n/a
417n/a#undef TESTNAME
418n/a#undef TYPENAME
419n/a#undef F_S_TO_PY
420n/a#undef F_PY_TO_S
421n/a#undef F_U_TO_PY
422n/a#undef F_PY_TO_U
423n/a
424n/astatic PyObject *
425n/araise_test_longlong_error(const char* msg)
426n/a{
427n/a return raiseTestError("test_longlong_api", msg);
428n/a}
429n/a
430n/a#define TESTNAME test_longlong_api_inner
431n/a#define TYPENAME long long
432n/a#define F_S_TO_PY PyLong_FromLongLong
433n/a#define F_PY_TO_S PyLong_AsLongLong
434n/a#define F_U_TO_PY PyLong_FromUnsignedLongLong
435n/a#define F_PY_TO_U PyLong_AsUnsignedLongLong
436n/a
437n/a#include "testcapi_long.h"
438n/a
439n/astatic PyObject *
440n/atest_longlong_api(PyObject* self, PyObject *args)
441n/a{
442n/a return TESTNAME(raise_test_longlong_error);
443n/a}
444n/a
445n/a#undef TESTNAME
446n/a#undef TYPENAME
447n/a#undef F_S_TO_PY
448n/a#undef F_PY_TO_S
449n/a#undef F_U_TO_PY
450n/a#undef F_PY_TO_U
451n/a
452n/a/* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG
453n/a is tested by test_long_api_inner. This test will concentrate on proper
454n/a handling of overflow.
455n/a*/
456n/a
457n/astatic PyObject *
458n/atest_long_and_overflow(PyObject *self)
459n/a{
460n/a PyObject *num, *one, *temp;
461n/a long value;
462n/a int overflow;
463n/a
464n/a /* Test that overflow is set properly for a large value. */
465n/a /* num is a number larger than LONG_MAX even on 64-bit platforms */
466n/a num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
467n/a if (num == NULL)
468n/a return NULL;
469n/a overflow = 1234;
470n/a value = PyLong_AsLongAndOverflow(num, &overflow);
471n/a Py_DECREF(num);
472n/a if (value == -1 && PyErr_Occurred())
473n/a return NULL;
474n/a if (value != -1)
475n/a return raiseTestError("test_long_and_overflow",
476n/a "return value was not set to -1");
477n/a if (overflow != 1)
478n/a return raiseTestError("test_long_and_overflow",
479n/a "overflow was not set to 1");
480n/a
481n/a /* Same again, with num = LONG_MAX + 1 */
482n/a num = PyLong_FromLong(LONG_MAX);
483n/a if (num == NULL)
484n/a return NULL;
485n/a one = PyLong_FromLong(1L);
486n/a if (one == NULL) {
487n/a Py_DECREF(num);
488n/a return NULL;
489n/a }
490n/a temp = PyNumber_Add(num, one);
491n/a Py_DECREF(one);
492n/a Py_DECREF(num);
493n/a num = temp;
494n/a if (num == NULL)
495n/a return NULL;
496n/a overflow = 0;
497n/a value = PyLong_AsLongAndOverflow(num, &overflow);
498n/a Py_DECREF(num);
499n/a if (value == -1 && PyErr_Occurred())
500n/a return NULL;
501n/a if (value != -1)
502n/a return raiseTestError("test_long_and_overflow",
503n/a "return value was not set to -1");
504n/a if (overflow != 1)
505n/a return raiseTestError("test_long_and_overflow",
506n/a "overflow was not set to 1");
507n/a
508n/a /* Test that overflow is set properly for a large negative value. */
509n/a /* num is a number smaller than LONG_MIN even on 64-bit platforms */
510n/a num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
511n/a if (num == NULL)
512n/a return NULL;
513n/a overflow = 1234;
514n/a value = PyLong_AsLongAndOverflow(num, &overflow);
515n/a Py_DECREF(num);
516n/a if (value == -1 && PyErr_Occurred())
517n/a return NULL;
518n/a if (value != -1)
519n/a return raiseTestError("test_long_and_overflow",
520n/a "return value was not set to -1");
521n/a if (overflow != -1)
522n/a return raiseTestError("test_long_and_overflow",
523n/a "overflow was not set to -1");
524n/a
525n/a /* Same again, with num = LONG_MIN - 1 */
526n/a num = PyLong_FromLong(LONG_MIN);
527n/a if (num == NULL)
528n/a return NULL;
529n/a one = PyLong_FromLong(1L);
530n/a if (one == NULL) {
531n/a Py_DECREF(num);
532n/a return NULL;
533n/a }
534n/a temp = PyNumber_Subtract(num, one);
535n/a Py_DECREF(one);
536n/a Py_DECREF(num);
537n/a num = temp;
538n/a if (num == NULL)
539n/a return NULL;
540n/a overflow = 0;
541n/a value = PyLong_AsLongAndOverflow(num, &overflow);
542n/a Py_DECREF(num);
543n/a if (value == -1 && PyErr_Occurred())
544n/a return NULL;
545n/a if (value != -1)
546n/a return raiseTestError("test_long_and_overflow",
547n/a "return value was not set to -1");
548n/a if (overflow != -1)
549n/a return raiseTestError("test_long_and_overflow",
550n/a "overflow was not set to -1");
551n/a
552n/a /* Test that overflow is cleared properly for small values. */
553n/a num = PyLong_FromString("FF", NULL, 16);
554n/a if (num == NULL)
555n/a return NULL;
556n/a overflow = 1234;
557n/a value = PyLong_AsLongAndOverflow(num, &overflow);
558n/a Py_DECREF(num);
559n/a if (value == -1 && PyErr_Occurred())
560n/a return NULL;
561n/a if (value != 0xFF)
562n/a return raiseTestError("test_long_and_overflow",
563n/a "expected return value 0xFF");
564n/a if (overflow != 0)
565n/a return raiseTestError("test_long_and_overflow",
566n/a "overflow was not cleared");
567n/a
568n/a num = PyLong_FromString("-FF", NULL, 16);
569n/a if (num == NULL)
570n/a return NULL;
571n/a overflow = 0;
572n/a value = PyLong_AsLongAndOverflow(num, &overflow);
573n/a Py_DECREF(num);
574n/a if (value == -1 && PyErr_Occurred())
575n/a return NULL;
576n/a if (value != -0xFF)
577n/a return raiseTestError("test_long_and_overflow",
578n/a "expected return value 0xFF");
579n/a if (overflow != 0)
580n/a return raiseTestError("test_long_and_overflow",
581n/a "overflow was set incorrectly");
582n/a
583n/a num = PyLong_FromLong(LONG_MAX);
584n/a if (num == NULL)
585n/a return NULL;
586n/a overflow = 1234;
587n/a value = PyLong_AsLongAndOverflow(num, &overflow);
588n/a Py_DECREF(num);
589n/a if (value == -1 && PyErr_Occurred())
590n/a return NULL;
591n/a if (value != LONG_MAX)
592n/a return raiseTestError("test_long_and_overflow",
593n/a "expected return value LONG_MAX");
594n/a if (overflow != 0)
595n/a return raiseTestError("test_long_and_overflow",
596n/a "overflow was not cleared");
597n/a
598n/a num = PyLong_FromLong(LONG_MIN);
599n/a if (num == NULL)
600n/a return NULL;
601n/a overflow = 0;
602n/a value = PyLong_AsLongAndOverflow(num, &overflow);
603n/a Py_DECREF(num);
604n/a if (value == -1 && PyErr_Occurred())
605n/a return NULL;
606n/a if (value != LONG_MIN)
607n/a return raiseTestError("test_long_and_overflow",
608n/a "expected return value LONG_MIN");
609n/a if (overflow != 0)
610n/a return raiseTestError("test_long_and_overflow",
611n/a "overflow was not cleared");
612n/a
613n/a Py_RETURN_NONE;
614n/a}
615n/a
616n/a/* Test the PyLong_AsLongLongAndOverflow API. General conversion to
617n/a long long is tested by test_long_api_inner. This test will
618n/a concentrate on proper handling of overflow.
619n/a*/
620n/a
621n/astatic PyObject *
622n/atest_long_long_and_overflow(PyObject *self)
623n/a{
624n/a PyObject *num, *one, *temp;
625n/a long long value;
626n/a int overflow;
627n/a
628n/a /* Test that overflow is set properly for a large value. */
629n/a /* num is a number larger than PY_LLONG_MAX on a typical machine. */
630n/a num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
631n/a if (num == NULL)
632n/a return NULL;
633n/a overflow = 1234;
634n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
635n/a Py_DECREF(num);
636n/a if (value == -1 && PyErr_Occurred())
637n/a return NULL;
638n/a if (value != -1)
639n/a return raiseTestError("test_long_long_and_overflow",
640n/a "return value was not set to -1");
641n/a if (overflow != 1)
642n/a return raiseTestError("test_long_long_and_overflow",
643n/a "overflow was not set to 1");
644n/a
645n/a /* Same again, with num = PY_LLONG_MAX + 1 */
646n/a num = PyLong_FromLongLong(PY_LLONG_MAX);
647n/a if (num == NULL)
648n/a return NULL;
649n/a one = PyLong_FromLong(1L);
650n/a if (one == NULL) {
651n/a Py_DECREF(num);
652n/a return NULL;
653n/a }
654n/a temp = PyNumber_Add(num, one);
655n/a Py_DECREF(one);
656n/a Py_DECREF(num);
657n/a num = temp;
658n/a if (num == NULL)
659n/a return NULL;
660n/a overflow = 0;
661n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
662n/a Py_DECREF(num);
663n/a if (value == -1 && PyErr_Occurred())
664n/a return NULL;
665n/a if (value != -1)
666n/a return raiseTestError("test_long_long_and_overflow",
667n/a "return value was not set to -1");
668n/a if (overflow != 1)
669n/a return raiseTestError("test_long_long_and_overflow",
670n/a "overflow was not set to 1");
671n/a
672n/a /* Test that overflow is set properly for a large negative value. */
673n/a /* num is a number smaller than PY_LLONG_MIN on a typical platform */
674n/a num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
675n/a if (num == NULL)
676n/a return NULL;
677n/a overflow = 1234;
678n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
679n/a Py_DECREF(num);
680n/a if (value == -1 && PyErr_Occurred())
681n/a return NULL;
682n/a if (value != -1)
683n/a return raiseTestError("test_long_long_and_overflow",
684n/a "return value was not set to -1");
685n/a if (overflow != -1)
686n/a return raiseTestError("test_long_long_and_overflow",
687n/a "overflow was not set to -1");
688n/a
689n/a /* Same again, with num = PY_LLONG_MIN - 1 */
690n/a num = PyLong_FromLongLong(PY_LLONG_MIN);
691n/a if (num == NULL)
692n/a return NULL;
693n/a one = PyLong_FromLong(1L);
694n/a if (one == NULL) {
695n/a Py_DECREF(num);
696n/a return NULL;
697n/a }
698n/a temp = PyNumber_Subtract(num, one);
699n/a Py_DECREF(one);
700n/a Py_DECREF(num);
701n/a num = temp;
702n/a if (num == NULL)
703n/a return NULL;
704n/a overflow = 0;
705n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
706n/a Py_DECREF(num);
707n/a if (value == -1 && PyErr_Occurred())
708n/a return NULL;
709n/a if (value != -1)
710n/a return raiseTestError("test_long_long_and_overflow",
711n/a "return value was not set to -1");
712n/a if (overflow != -1)
713n/a return raiseTestError("test_long_long_and_overflow",
714n/a "overflow was not set to -1");
715n/a
716n/a /* Test that overflow is cleared properly for small values. */
717n/a num = PyLong_FromString("FF", NULL, 16);
718n/a if (num == NULL)
719n/a return NULL;
720n/a overflow = 1234;
721n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
722n/a Py_DECREF(num);
723n/a if (value == -1 && PyErr_Occurred())
724n/a return NULL;
725n/a if (value != 0xFF)
726n/a return raiseTestError("test_long_long_and_overflow",
727n/a "expected return value 0xFF");
728n/a if (overflow != 0)
729n/a return raiseTestError("test_long_long_and_overflow",
730n/a "overflow was not cleared");
731n/a
732n/a num = PyLong_FromString("-FF", NULL, 16);
733n/a if (num == NULL)
734n/a return NULL;
735n/a overflow = 0;
736n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
737n/a Py_DECREF(num);
738n/a if (value == -1 && PyErr_Occurred())
739n/a return NULL;
740n/a if (value != -0xFF)
741n/a return raiseTestError("test_long_long_and_overflow",
742n/a "expected return value 0xFF");
743n/a if (overflow != 0)
744n/a return raiseTestError("test_long_long_and_overflow",
745n/a "overflow was set incorrectly");
746n/a
747n/a num = PyLong_FromLongLong(PY_LLONG_MAX);
748n/a if (num == NULL)
749n/a return NULL;
750n/a overflow = 1234;
751n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
752n/a Py_DECREF(num);
753n/a if (value == -1 && PyErr_Occurred())
754n/a return NULL;
755n/a if (value != PY_LLONG_MAX)
756n/a return raiseTestError("test_long_long_and_overflow",
757n/a "expected return value PY_LLONG_MAX");
758n/a if (overflow != 0)
759n/a return raiseTestError("test_long_long_and_overflow",
760n/a "overflow was not cleared");
761n/a
762n/a num = PyLong_FromLongLong(PY_LLONG_MIN);
763n/a if (num == NULL)
764n/a return NULL;
765n/a overflow = 0;
766n/a value = PyLong_AsLongLongAndOverflow(num, &overflow);
767n/a Py_DECREF(num);
768n/a if (value == -1 && PyErr_Occurred())
769n/a return NULL;
770n/a if (value != PY_LLONG_MIN)
771n/a return raiseTestError("test_long_long_and_overflow",
772n/a "expected return value PY_LLONG_MIN");
773n/a if (overflow != 0)
774n/a return raiseTestError("test_long_long_and_overflow",
775n/a "overflow was not cleared");
776n/a
777n/a Py_RETURN_NONE;
778n/a}
779n/a
780n/a/* Test the PyLong_As{Size,Ssize}_t API. At present this just tests that
781n/a non-integer arguments are handled correctly. It should be extended to
782n/a test overflow handling.
783n/a */
784n/a
785n/astatic PyObject *
786n/atest_long_as_size_t(PyObject *self)
787n/a{
788n/a size_t out_u;
789n/a Py_ssize_t out_s;
790n/a
791n/a Py_INCREF(Py_None);
792n/a
793n/a out_u = PyLong_AsSize_t(Py_None);
794n/a if (out_u != (size_t)-1 || !PyErr_Occurred())
795n/a return raiseTestError("test_long_as_size_t",
796n/a "PyLong_AsSize_t(None) didn't complain");
797n/a if (!PyErr_ExceptionMatches(PyExc_TypeError))
798n/a return raiseTestError("test_long_as_size_t",
799n/a "PyLong_AsSize_t(None) raised "
800n/a "something other than TypeError");
801n/a PyErr_Clear();
802n/a
803n/a out_s = PyLong_AsSsize_t(Py_None);
804n/a if (out_s != (Py_ssize_t)-1 || !PyErr_Occurred())
805n/a return raiseTestError("test_long_as_size_t",
806n/a "PyLong_AsSsize_t(None) didn't complain");
807n/a if (!PyErr_ExceptionMatches(PyExc_TypeError))
808n/a return raiseTestError("test_long_as_size_t",
809n/a "PyLong_AsSsize_t(None) raised "
810n/a "something other than TypeError");
811n/a PyErr_Clear();
812n/a
813n/a /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
814n/a return Py_None;
815n/a}
816n/a
817n/a/* Test the PyLong_AsDouble API. At present this just tests that
818n/a non-integer arguments are handled correctly.
819n/a */
820n/a
821n/astatic PyObject *
822n/atest_long_as_double(PyObject *self)
823n/a{
824n/a double out;
825n/a
826n/a Py_INCREF(Py_None);
827n/a
828n/a out = PyLong_AsDouble(Py_None);
829n/a if (out != -1.0 || !PyErr_Occurred())
830n/a return raiseTestError("test_long_as_double",
831n/a "PyLong_AsDouble(None) didn't complain");
832n/a if (!PyErr_ExceptionMatches(PyExc_TypeError))
833n/a return raiseTestError("test_long_as_double",
834n/a "PyLong_AsDouble(None) raised "
835n/a "something other than TypeError");
836n/a PyErr_Clear();
837n/a
838n/a /* Py_INCREF(Py_None) omitted - we already have a reference to it. */
839n/a return Py_None;
840n/a}
841n/a
842n/a/* Test the L code for PyArg_ParseTuple. This should deliver a long long
843n/a for both long and int arguments. The test may leak a little memory if
844n/a it fails.
845n/a*/
846n/astatic PyObject *
847n/atest_L_code(PyObject *self)
848n/a{
849n/a PyObject *tuple, *num;
850n/a long long value;
851n/a
852n/a tuple = PyTuple_New(1);
853n/a if (tuple == NULL)
854n/a return NULL;
855n/a
856n/a num = PyLong_FromLong(42);
857n/a if (num == NULL)
858n/a return NULL;
859n/a
860n/a PyTuple_SET_ITEM(tuple, 0, num);
861n/a
862n/a value = -1;
863n/a if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
864n/a return NULL;
865n/a if (value != 42)
866n/a return raiseTestError("test_L_code",
867n/a "L code returned wrong value for long 42");
868n/a
869n/a Py_DECREF(num);
870n/a num = PyLong_FromLong(42);
871n/a if (num == NULL)
872n/a return NULL;
873n/a
874n/a PyTuple_SET_ITEM(tuple, 0, num);
875n/a
876n/a value = -1;
877n/a if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
878n/a return NULL;
879n/a if (value != 42)
880n/a return raiseTestError("test_L_code",
881n/a "L code returned wrong value for int 42");
882n/a
883n/a Py_DECREF(tuple);
884n/a Py_RETURN_NONE;
885n/a}
886n/a
887n/astatic PyObject *
888n/areturn_none(void *unused)
889n/a{
890n/a Py_RETURN_NONE;
891n/a}
892n/a
893n/astatic PyObject *
894n/araise_error(void *unused)
895n/a{
896n/a PyErr_SetNone(PyExc_ValueError);
897n/a return NULL;
898n/a}
899n/a
900n/astatic int
901n/atest_buildvalue_N_error(const char *fmt)
902n/a{
903n/a PyObject *arg, *res;
904n/a
905n/a arg = PyList_New(0);
906n/a if (arg == NULL) {
907n/a return -1;
908n/a }
909n/a
910n/a Py_INCREF(arg);
911n/a res = Py_BuildValue(fmt, return_none, NULL, arg);
912n/a if (res == NULL) {
913n/a return -1;
914n/a }
915n/a Py_DECREF(res);
916n/a if (Py_REFCNT(arg) != 1) {
917n/a PyErr_Format(TestError, "test_buildvalue_N: "
918n/a "arg was not decrefed in successful "
919n/a "Py_BuildValue(\"%s\")", fmt);
920n/a return -1;
921n/a }
922n/a
923n/a Py_INCREF(arg);
924n/a res = Py_BuildValue(fmt, raise_error, NULL, arg);
925n/a if (res != NULL || !PyErr_Occurred()) {
926n/a PyErr_Format(TestError, "test_buildvalue_N: "
927n/a "Py_BuildValue(\"%s\") didn't complain", fmt);
928n/a return -1;
929n/a }
930n/a PyErr_Clear();
931n/a if (Py_REFCNT(arg) != 1) {
932n/a PyErr_Format(TestError, "test_buildvalue_N: "
933n/a "arg was not decrefed in failed "
934n/a "Py_BuildValue(\"%s\")", fmt);
935n/a return -1;
936n/a }
937n/a Py_DECREF(arg);
938n/a return 0;
939n/a}
940n/a
941n/astatic PyObject *
942n/atest_buildvalue_N(PyObject *self, PyObject *noargs)
943n/a{
944n/a PyObject *arg, *res;
945n/a
946n/a arg = PyList_New(0);
947n/a if (arg == NULL) {
948n/a return NULL;
949n/a }
950n/a Py_INCREF(arg);
951n/a res = Py_BuildValue("N", arg);
952n/a if (res == NULL) {
953n/a return NULL;
954n/a }
955n/a if (res != arg) {
956n/a return raiseTestError("test_buildvalue_N",
957n/a "Py_BuildValue(\"N\") returned wrong result");
958n/a }
959n/a if (Py_REFCNT(arg) != 2) {
960n/a return raiseTestError("test_buildvalue_N",
961n/a "arg was not decrefed in Py_BuildValue(\"N\")");
962n/a }
963n/a Py_DECREF(res);
964n/a Py_DECREF(arg);
965n/a
966n/a if (test_buildvalue_N_error("O&N") < 0)
967n/a return NULL;
968n/a if (test_buildvalue_N_error("(O&N)") < 0)
969n/a return NULL;
970n/a if (test_buildvalue_N_error("[O&N]") < 0)
971n/a return NULL;
972n/a if (test_buildvalue_N_error("{O&N}") < 0)
973n/a return NULL;
974n/a if (test_buildvalue_N_error("{()O&(())N}") < 0)
975n/a return NULL;
976n/a
977n/a Py_RETURN_NONE;
978n/a}
979n/a
980n/a
981n/astatic PyObject *
982n/aget_args(PyObject *self, PyObject *args)
983n/a{
984n/a if (args == NULL) {
985n/a args = Py_None;
986n/a }
987n/a Py_INCREF(args);
988n/a return args;
989n/a}
990n/a
991n/astatic PyObject *
992n/aget_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
993n/a{
994n/a if (kwargs == NULL) {
995n/a kwargs = Py_None;
996n/a }
997n/a Py_INCREF(kwargs);
998n/a return kwargs;
999n/a}
1000n/a
1001n/a/* Test tuple argument processing */
1002n/astatic PyObject *
1003n/agetargs_tuple(PyObject *self, PyObject *args)
1004n/a{
1005n/a int a, b, c;
1006n/a if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
1007n/a return NULL;
1008n/a return Py_BuildValue("iii", a, b, c);
1009n/a}
1010n/a
1011n/a/* test PyArg_ParseTupleAndKeywords */
1012n/astatic PyObject *
1013n/agetargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1014n/a{
1015n/a static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
1016n/a static const char fmt[] = "(ii)i|(i(ii))(iii)i";
1017n/a int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
1018n/a
1019n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
1020n/a &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
1021n/a &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
1022n/a return NULL;
1023n/a return Py_BuildValue("iiiiiiiiii",
1024n/a int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
1025n/a int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
1026n/a}
1027n/a
1028n/a/* test PyArg_ParseTupleAndKeywords keyword-only arguments */
1029n/astatic PyObject *
1030n/agetargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs)
1031n/a{
1032n/a static char *keywords[] = {"required", "optional", "keyword_only", NULL};
1033n/a int required = -1;
1034n/a int optional = -1;
1035n/a int keyword_only = -1;
1036n/a
1037n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", keywords,
1038n/a &required, &optional, &keyword_only))
1039n/a return NULL;
1040n/a return Py_BuildValue("iii", required, optional, keyword_only);
1041n/a}
1042n/a
1043n/a/* test PyArg_ParseTupleAndKeywords positional-only arguments */
1044n/astatic PyObject *
1045n/agetargs_positional_only_and_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1046n/a{
1047n/a static char *keywords[] = {"", "", "keyword", NULL};
1048n/a int required = -1;
1049n/a int optional = -1;
1050n/a int keyword = -1;
1051n/a
1052n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii", keywords,
1053n/a &required, &optional, &keyword))
1054n/a return NULL;
1055n/a return Py_BuildValue("iii", required, optional, keyword);
1056n/a}
1057n/a
1058n/a/* Functions to call PyArg_ParseTuple with integer format codes,
1059n/a and return the result.
1060n/a*/
1061n/astatic PyObject *
1062n/agetargs_b(PyObject *self, PyObject *args)
1063n/a{
1064n/a unsigned char value;
1065n/a if (!PyArg_ParseTuple(args, "b", &value))
1066n/a return NULL;
1067n/a return PyLong_FromUnsignedLong((unsigned long)value);
1068n/a}
1069n/a
1070n/astatic PyObject *
1071n/agetargs_B(PyObject *self, PyObject *args)
1072n/a{
1073n/a unsigned char value;
1074n/a if (!PyArg_ParseTuple(args, "B", &value))
1075n/a return NULL;
1076n/a return PyLong_FromUnsignedLong((unsigned long)value);
1077n/a}
1078n/a
1079n/astatic PyObject *
1080n/agetargs_h(PyObject *self, PyObject *args)
1081n/a{
1082n/a short value;
1083n/a if (!PyArg_ParseTuple(args, "h", &value))
1084n/a return NULL;
1085n/a return PyLong_FromLong((long)value);
1086n/a}
1087n/a
1088n/astatic PyObject *
1089n/agetargs_H(PyObject *self, PyObject *args)
1090n/a{
1091n/a unsigned short value;
1092n/a if (!PyArg_ParseTuple(args, "H", &value))
1093n/a return NULL;
1094n/a return PyLong_FromUnsignedLong((unsigned long)value);
1095n/a}
1096n/a
1097n/astatic PyObject *
1098n/agetargs_I(PyObject *self, PyObject *args)
1099n/a{
1100n/a unsigned int value;
1101n/a if (!PyArg_ParseTuple(args, "I", &value))
1102n/a return NULL;
1103n/a return PyLong_FromUnsignedLong((unsigned long)value);
1104n/a}
1105n/a
1106n/astatic PyObject *
1107n/agetargs_k(PyObject *self, PyObject *args)
1108n/a{
1109n/a unsigned long value;
1110n/a if (!PyArg_ParseTuple(args, "k", &value))
1111n/a return NULL;
1112n/a return PyLong_FromUnsignedLong(value);
1113n/a}
1114n/a
1115n/astatic PyObject *
1116n/agetargs_i(PyObject *self, PyObject *args)
1117n/a{
1118n/a int value;
1119n/a if (!PyArg_ParseTuple(args, "i", &value))
1120n/a return NULL;
1121n/a return PyLong_FromLong((long)value);
1122n/a}
1123n/a
1124n/astatic PyObject *
1125n/agetargs_l(PyObject *self, PyObject *args)
1126n/a{
1127n/a long value;
1128n/a if (!PyArg_ParseTuple(args, "l", &value))
1129n/a return NULL;
1130n/a return PyLong_FromLong(value);
1131n/a}
1132n/a
1133n/astatic PyObject *
1134n/agetargs_n(PyObject *self, PyObject *args)
1135n/a{
1136n/a Py_ssize_t value;
1137n/a if (!PyArg_ParseTuple(args, "n", &value))
1138n/a return NULL;
1139n/a return PyLong_FromSsize_t(value);
1140n/a}
1141n/a
1142n/astatic PyObject *
1143n/agetargs_p(PyObject *self, PyObject *args)
1144n/a{
1145n/a int value;
1146n/a if (!PyArg_ParseTuple(args, "p", &value))
1147n/a return NULL;
1148n/a return PyLong_FromLong(value);
1149n/a}
1150n/a
1151n/astatic PyObject *
1152n/agetargs_L(PyObject *self, PyObject *args)
1153n/a{
1154n/a long long value;
1155n/a if (!PyArg_ParseTuple(args, "L", &value))
1156n/a return NULL;
1157n/a return PyLong_FromLongLong(value);
1158n/a}
1159n/a
1160n/astatic PyObject *
1161n/agetargs_K(PyObject *self, PyObject *args)
1162n/a{
1163n/a unsigned long long value;
1164n/a if (!PyArg_ParseTuple(args, "K", &value))
1165n/a return NULL;
1166n/a return PyLong_FromUnsignedLongLong(value);
1167n/a}
1168n/a
1169n/a/* This function not only tests the 'k' getargs code, but also the
1170n/a PyLong_AsUnsignedLongMask() and PyLong_AsUnsignedLongMask() functions. */
1171n/astatic PyObject *
1172n/atest_k_code(PyObject *self)
1173n/a{
1174n/a PyObject *tuple, *num;
1175n/a unsigned long value;
1176n/a
1177n/a tuple = PyTuple_New(1);
1178n/a if (tuple == NULL)
1179n/a return NULL;
1180n/a
1181n/a /* a number larger than ULONG_MAX even on 64-bit platforms */
1182n/a num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
1183n/a if (num == NULL)
1184n/a return NULL;
1185n/a
1186n/a value = PyLong_AsUnsignedLongMask(num);
1187n/a if (value != ULONG_MAX)
1188n/a return raiseTestError("test_k_code",
1189n/a "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
1190n/a
1191n/a PyTuple_SET_ITEM(tuple, 0, num);
1192n/a
1193n/a value = 0;
1194n/a if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
1195n/a return NULL;
1196n/a if (value != ULONG_MAX)
1197n/a return raiseTestError("test_k_code",
1198n/a "k code returned wrong value for long 0xFFF...FFF");
1199n/a
1200n/a Py_DECREF(num);
1201n/a num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
1202n/a if (num == NULL)
1203n/a return NULL;
1204n/a
1205n/a value = PyLong_AsUnsignedLongMask(num);
1206n/a if (value != (unsigned long)-0x42)
1207n/a return raiseTestError("test_k_code",
1208n/a "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
1209n/a
1210n/a PyTuple_SET_ITEM(tuple, 0, num);
1211n/a
1212n/a value = 0;
1213n/a if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
1214n/a return NULL;
1215n/a if (value != (unsigned long)-0x42)
1216n/a return raiseTestError("test_k_code",
1217n/a "k code returned wrong value for long -0xFFF..000042");
1218n/a
1219n/a Py_DECREF(tuple);
1220n/a Py_RETURN_NONE;
1221n/a}
1222n/a
1223n/astatic PyObject *
1224n/agetargs_f(PyObject *self, PyObject *args)
1225n/a{
1226n/a float f;
1227n/a if (!PyArg_ParseTuple(args, "f", &f))
1228n/a return NULL;
1229n/a return PyFloat_FromDouble(f);
1230n/a}
1231n/a
1232n/astatic PyObject *
1233n/agetargs_d(PyObject *self, PyObject *args)
1234n/a{
1235n/a double d;
1236n/a if (!PyArg_ParseTuple(args, "d", &d))
1237n/a return NULL;
1238n/a return PyFloat_FromDouble(d);
1239n/a}
1240n/a
1241n/astatic PyObject *
1242n/agetargs_D(PyObject *self, PyObject *args)
1243n/a{
1244n/a Py_complex cval;
1245n/a if (!PyArg_ParseTuple(args, "D", &cval))
1246n/a return NULL;
1247n/a return PyComplex_FromCComplex(cval);
1248n/a}
1249n/a
1250n/astatic PyObject *
1251n/agetargs_S(PyObject *self, PyObject *args)
1252n/a{
1253n/a PyObject *obj;
1254n/a if (!PyArg_ParseTuple(args, "S", &obj))
1255n/a return NULL;
1256n/a Py_INCREF(obj);
1257n/a return obj;
1258n/a}
1259n/a
1260n/astatic PyObject *
1261n/agetargs_Y(PyObject *self, PyObject *args)
1262n/a{
1263n/a PyObject *obj;
1264n/a if (!PyArg_ParseTuple(args, "Y", &obj))
1265n/a return NULL;
1266n/a Py_INCREF(obj);
1267n/a return obj;
1268n/a}
1269n/a
1270n/astatic PyObject *
1271n/agetargs_U(PyObject *self, PyObject *args)
1272n/a{
1273n/a PyObject *obj;
1274n/a if (!PyArg_ParseTuple(args, "U", &obj))
1275n/a return NULL;
1276n/a Py_INCREF(obj);
1277n/a return obj;
1278n/a}
1279n/a
1280n/astatic PyObject *
1281n/agetargs_c(PyObject *self, PyObject *args)
1282n/a{
1283n/a char c;
1284n/a if (!PyArg_ParseTuple(args, "c", &c))
1285n/a return NULL;
1286n/a return PyLong_FromLong((unsigned char)c);
1287n/a}
1288n/a
1289n/astatic PyObject *
1290n/agetargs_C(PyObject *self, PyObject *args)
1291n/a{
1292n/a int c;
1293n/a if (!PyArg_ParseTuple(args, "C", &c))
1294n/a return NULL;
1295n/a return PyLong_FromLong(c);
1296n/a}
1297n/a
1298n/astatic PyObject *
1299n/agetargs_s(PyObject *self, PyObject *args)
1300n/a{
1301n/a char *str;
1302n/a if (!PyArg_ParseTuple(args, "s", &str))
1303n/a return NULL;
1304n/a return PyBytes_FromString(str);
1305n/a}
1306n/a
1307n/astatic PyObject *
1308n/agetargs_s_star(PyObject *self, PyObject *args)
1309n/a{
1310n/a Py_buffer buffer;
1311n/a PyObject *bytes;
1312n/a if (!PyArg_ParseTuple(args, "s*", &buffer))
1313n/a return NULL;
1314n/a bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1315n/a PyBuffer_Release(&buffer);
1316n/a return bytes;
1317n/a}
1318n/a
1319n/astatic PyObject *
1320n/agetargs_s_hash(PyObject *self, PyObject *args)
1321n/a{
1322n/a char *str;
1323n/a Py_ssize_t size;
1324n/a if (!PyArg_ParseTuple(args, "s#", &str, &size))
1325n/a return NULL;
1326n/a return PyBytes_FromStringAndSize(str, size);
1327n/a}
1328n/a
1329n/astatic PyObject *
1330n/agetargs_z(PyObject *self, PyObject *args)
1331n/a{
1332n/a char *str;
1333n/a if (!PyArg_ParseTuple(args, "z", &str))
1334n/a return NULL;
1335n/a if (str != NULL)
1336n/a return PyBytes_FromString(str);
1337n/a else
1338n/a Py_RETURN_NONE;
1339n/a}
1340n/a
1341n/astatic PyObject *
1342n/agetargs_z_star(PyObject *self, PyObject *args)
1343n/a{
1344n/a Py_buffer buffer;
1345n/a PyObject *bytes;
1346n/a if (!PyArg_ParseTuple(args, "z*", &buffer))
1347n/a return NULL;
1348n/a if (buffer.buf != NULL)
1349n/a bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1350n/a else {
1351n/a Py_INCREF(Py_None);
1352n/a bytes = Py_None;
1353n/a }
1354n/a PyBuffer_Release(&buffer);
1355n/a return bytes;
1356n/a}
1357n/a
1358n/astatic PyObject *
1359n/agetargs_z_hash(PyObject *self, PyObject *args)
1360n/a{
1361n/a char *str;
1362n/a Py_ssize_t size;
1363n/a if (!PyArg_ParseTuple(args, "z#", &str, &size))
1364n/a return NULL;
1365n/a if (str != NULL)
1366n/a return PyBytes_FromStringAndSize(str, size);
1367n/a else
1368n/a Py_RETURN_NONE;
1369n/a}
1370n/a
1371n/astatic PyObject *
1372n/agetargs_y(PyObject *self, PyObject *args)
1373n/a{
1374n/a char *str;
1375n/a if (!PyArg_ParseTuple(args, "y", &str))
1376n/a return NULL;
1377n/a return PyBytes_FromString(str);
1378n/a}
1379n/a
1380n/astatic PyObject *
1381n/agetargs_y_star(PyObject *self, PyObject *args)
1382n/a{
1383n/a Py_buffer buffer;
1384n/a PyObject *bytes;
1385n/a if (!PyArg_ParseTuple(args, "y*", &buffer))
1386n/a return NULL;
1387n/a bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1388n/a PyBuffer_Release(&buffer);
1389n/a return bytes;
1390n/a}
1391n/a
1392n/astatic PyObject *
1393n/agetargs_y_hash(PyObject *self, PyObject *args)
1394n/a{
1395n/a char *str;
1396n/a Py_ssize_t size;
1397n/a if (!PyArg_ParseTuple(args, "y#", &str, &size))
1398n/a return NULL;
1399n/a return PyBytes_FromStringAndSize(str, size);
1400n/a}
1401n/a
1402n/astatic PyObject *
1403n/agetargs_u(PyObject *self, PyObject *args)
1404n/a{
1405n/a Py_UNICODE *str;
1406n/a if (!PyArg_ParseTuple(args, "u", &str))
1407n/a return NULL;
1408n/a return PyUnicode_FromWideChar(str, -1);
1409n/a}
1410n/a
1411n/astatic PyObject *
1412n/agetargs_u_hash(PyObject *self, PyObject *args)
1413n/a{
1414n/a Py_UNICODE *str;
1415n/a Py_ssize_t size;
1416n/a if (!PyArg_ParseTuple(args, "u#", &str, &size))
1417n/a return NULL;
1418n/a return PyUnicode_FromWideChar(str, size);
1419n/a}
1420n/a
1421n/astatic PyObject *
1422n/agetargs_Z(PyObject *self, PyObject *args)
1423n/a{
1424n/a Py_UNICODE *str;
1425n/a if (!PyArg_ParseTuple(args, "Z", &str))
1426n/a return NULL;
1427n/a if (str != NULL) {
1428n/a return PyUnicode_FromWideChar(str, -1);
1429n/a } else
1430n/a Py_RETURN_NONE;
1431n/a}
1432n/a
1433n/astatic PyObject *
1434n/agetargs_Z_hash(PyObject *self, PyObject *args)
1435n/a{
1436n/a Py_UNICODE *str;
1437n/a Py_ssize_t size;
1438n/a if (!PyArg_ParseTuple(args, "Z#", &str, &size))
1439n/a return NULL;
1440n/a if (str != NULL)
1441n/a return PyUnicode_FromWideChar(str, size);
1442n/a else
1443n/a Py_RETURN_NONE;
1444n/a}
1445n/a
1446n/astatic PyObject *
1447n/agetargs_es(PyObject *self, PyObject *args)
1448n/a{
1449n/a PyObject *arg, *result;
1450n/a const char *encoding = NULL;
1451n/a char *str;
1452n/a
1453n/a if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1454n/a return NULL;
1455n/a if (!PyArg_Parse(arg, "es", encoding, &str))
1456n/a return NULL;
1457n/a result = PyBytes_FromString(str);
1458n/a PyMem_Free(str);
1459n/a return result;
1460n/a}
1461n/a
1462n/astatic PyObject *
1463n/agetargs_et(PyObject *self, PyObject *args)
1464n/a{
1465n/a PyObject *arg, *result;
1466n/a const char *encoding = NULL;
1467n/a char *str;
1468n/a
1469n/a if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1470n/a return NULL;
1471n/a if (!PyArg_Parse(arg, "et", encoding, &str))
1472n/a return NULL;
1473n/a result = PyBytes_FromString(str);
1474n/a PyMem_Free(str);
1475n/a return result;
1476n/a}
1477n/a
1478n/astatic PyObject *
1479n/agetargs_es_hash(PyObject *self, PyObject *args)
1480n/a{
1481n/a PyObject *arg, *result;
1482n/a const char *encoding = NULL;
1483n/a PyByteArrayObject *buffer = NULL;
1484n/a char *str = NULL;
1485n/a Py_ssize_t size;
1486n/a
1487n/a if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1488n/a return NULL;
1489n/a if (buffer != NULL) {
1490n/a str = PyByteArray_AS_STRING(buffer);
1491n/a size = PyByteArray_GET_SIZE(buffer);
1492n/a }
1493n/a if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
1494n/a return NULL;
1495n/a result = PyBytes_FromStringAndSize(str, size);
1496n/a if (buffer == NULL)
1497n/a PyMem_Free(str);
1498n/a return result;
1499n/a}
1500n/a
1501n/astatic PyObject *
1502n/agetargs_et_hash(PyObject *self, PyObject *args)
1503n/a{
1504n/a PyObject *arg, *result;
1505n/a const char *encoding = NULL;
1506n/a PyByteArrayObject *buffer = NULL;
1507n/a char *str = NULL;
1508n/a Py_ssize_t size;
1509n/a
1510n/a if (!PyArg_ParseTuple(args, "O|sY", &arg, &encoding, &buffer))
1511n/a return NULL;
1512n/a if (buffer != NULL) {
1513n/a str = PyByteArray_AS_STRING(buffer);
1514n/a size = PyByteArray_GET_SIZE(buffer);
1515n/a }
1516n/a if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
1517n/a return NULL;
1518n/a result = PyBytes_FromStringAndSize(str, size);
1519n/a if (buffer == NULL)
1520n/a PyMem_Free(str);
1521n/a return result;
1522n/a}
1523n/a
1524n/a/* Test the s and z codes for PyArg_ParseTuple.
1525n/a*/
1526n/astatic PyObject *
1527n/atest_s_code(PyObject *self)
1528n/a{
1529n/a /* Unicode strings should be accepted */
1530n/a PyObject *tuple, *obj;
1531n/a char *value;
1532n/a
1533n/a tuple = PyTuple_New(1);
1534n/a if (tuple == NULL)
1535n/a return NULL;
1536n/a
1537n/a obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"),
1538n/a "latin-1", NULL);
1539n/a if (obj == NULL)
1540n/a return NULL;
1541n/a
1542n/a PyTuple_SET_ITEM(tuple, 0, obj);
1543n/a
1544n/a /* These two blocks used to raise a TypeError:
1545n/a * "argument must be string without null bytes, not str"
1546n/a */
1547n/a if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0)
1548n/a return NULL;
1549n/a
1550n/a if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0)
1551n/a return NULL;
1552n/a
1553n/a Py_DECREF(tuple);
1554n/a Py_RETURN_NONE;
1555n/a}
1556n/a
1557n/astatic PyObject *
1558n/aparse_tuple_and_keywords(PyObject *self, PyObject *args)
1559n/a{
1560n/a PyObject *sub_args;
1561n/a PyObject *sub_kwargs;
1562n/a char *sub_format;
1563n/a PyObject *sub_keywords;
1564n/a
1565n/a Py_ssize_t i, size;
1566n/a char *keywords[8 + 1]; /* space for NULL at end */
1567n/a PyObject *o;
1568n/a PyObject *converted[8];
1569n/a
1570n/a int result;
1571n/a PyObject *return_value = NULL;
1572n/a
1573n/a double buffers[8][4]; /* double ensures alignment where necessary */
1574n/a
1575n/a if (!PyArg_ParseTuple(args, "OOyO:parse_tuple_and_keywords",
1576n/a &sub_args, &sub_kwargs,
1577n/a &sub_format, &sub_keywords))
1578n/a return NULL;
1579n/a
1580n/a if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) {
1581n/a PyErr_SetString(PyExc_ValueError,
1582n/a "parse_tuple_and_keywords: sub_keywords must be either list or tuple");
1583n/a return NULL;
1584n/a }
1585n/a
1586n/a memset(buffers, 0, sizeof(buffers));
1587n/a memset(converted, 0, sizeof(converted));
1588n/a memset(keywords, 0, sizeof(keywords));
1589n/a
1590n/a size = PySequence_Fast_GET_SIZE(sub_keywords);
1591n/a if (size > 8) {
1592n/a PyErr_SetString(PyExc_ValueError,
1593n/a "parse_tuple_and_keywords: too many keywords in sub_keywords");
1594n/a goto exit;
1595n/a }
1596n/a
1597n/a for (i = 0; i < size; i++) {
1598n/a o = PySequence_Fast_GET_ITEM(sub_keywords, i);
1599n/a if (!PyUnicode_FSConverter(o, (void *)(converted + i))) {
1600n/a PyErr_Format(PyExc_ValueError,
1601n/a "parse_tuple_and_keywords: could not convert keywords[%zd] to narrow string", i);
1602n/a goto exit;
1603n/a }
1604n/a keywords[i] = PyBytes_AS_STRING(converted[i]);
1605n/a }
1606n/a
1607n/a result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs,
1608n/a sub_format, keywords,
1609n/a buffers + 0, buffers + 1, buffers + 2, buffers + 3,
1610n/a buffers + 4, buffers + 5, buffers + 6, buffers + 7);
1611n/a
1612n/a if (result) {
1613n/a return_value = Py_None;
1614n/a Py_INCREF(Py_None);
1615n/a }
1616n/a
1617n/aexit:
1618n/a size = sizeof(converted) / sizeof(converted[0]);
1619n/a for (i = 0; i < size; i++) {
1620n/a Py_XDECREF(converted[i]);
1621n/a }
1622n/a return return_value;
1623n/a}
1624n/a
1625n/astatic volatile int x;
1626n/a
1627n/a/* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
1628n/a of an error.
1629n/a*/
1630n/astatic PyObject *
1631n/atest_u_code(PyObject *self)
1632n/a{
1633n/a PyObject *tuple, *obj;
1634n/a Py_UNICODE *value;
1635n/a Py_ssize_t len;
1636n/a
1637n/a /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
1638n/a /* Just use the macro and check that it compiles */
1639n/a x = Py_UNICODE_ISSPACE(25);
1640n/a
1641n/a tuple = PyTuple_New(1);
1642n/a if (tuple == NULL)
1643n/a return NULL;
1644n/a
1645n/a obj = PyUnicode_Decode("test", strlen("test"),
1646n/a "ascii", NULL);
1647n/a if (obj == NULL)
1648n/a return NULL;
1649n/a
1650n/a PyTuple_SET_ITEM(tuple, 0, obj);
1651n/a
1652n/a value = 0;
1653n/a if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
1654n/a return NULL;
1655n/a if (value != PyUnicode_AS_UNICODE(obj))
1656n/a return raiseTestError("test_u_code",
1657n/a "u code returned wrong value for u'test'");
1658n/a value = 0;
1659n/a if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
1660n/a return NULL;
1661n/a if (value != PyUnicode_AS_UNICODE(obj) ||
1662n/a len != PyUnicode_GET_SIZE(obj))
1663n/a return raiseTestError("test_u_code",
1664n/a "u# code returned wrong values for u'test'");
1665n/a
1666n/a Py_DECREF(tuple);
1667n/a Py_RETURN_NONE;
1668n/a}
1669n/a
1670n/a/* Test Z and Z# codes for PyArg_ParseTuple */
1671n/astatic PyObject *
1672n/atest_Z_code(PyObject *self)
1673n/a{
1674n/a PyObject *tuple, *obj;
1675n/a const Py_UNICODE *value1, *value2;
1676n/a Py_ssize_t len1, len2;
1677n/a
1678n/a tuple = PyTuple_New(2);
1679n/a if (tuple == NULL)
1680n/a return NULL;
1681n/a
1682n/a obj = PyUnicode_FromString("test");
1683n/a PyTuple_SET_ITEM(tuple, 0, obj);
1684n/a Py_INCREF(Py_None);
1685n/a PyTuple_SET_ITEM(tuple, 1, Py_None);
1686n/a
1687n/a /* swap values on purpose */
1688n/a value1 = NULL;
1689n/a value2 = PyUnicode_AS_UNICODE(obj);
1690n/a
1691n/a /* Test Z for both values */
1692n/a if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0)
1693n/a return NULL;
1694n/a if (value1 != PyUnicode_AS_UNICODE(obj))
1695n/a return raiseTestError("test_Z_code",
1696n/a "Z code returned wrong value for 'test'");
1697n/a if (value2 != NULL)
1698n/a return raiseTestError("test_Z_code",
1699n/a "Z code returned wrong value for None");
1700n/a
1701n/a value1 = NULL;
1702n/a value2 = PyUnicode_AS_UNICODE(obj);
1703n/a len1 = -1;
1704n/a len2 = -1;
1705n/a
1706n/a /* Test Z# for both values */
1707n/a if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
1708n/a &value2, &len2) < 0)
1709n/a return NULL;
1710n/a if (value1 != PyUnicode_AS_UNICODE(obj) ||
1711n/a len1 != PyUnicode_GET_SIZE(obj))
1712n/a return raiseTestError("test_Z_code",
1713n/a "Z# code returned wrong values for 'test'");
1714n/a if (value2 != NULL ||
1715n/a len2 != 0)
1716n/a return raiseTestError("test_Z_code",
1717n/a "Z# code returned wrong values for None'");
1718n/a
1719n/a Py_DECREF(tuple);
1720n/a Py_RETURN_NONE;
1721n/a}
1722n/a
1723n/astatic PyObject *
1724n/atest_widechar(PyObject *self)
1725n/a{
1726n/a#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
1727n/a const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
1728n/a size_t wtextlen = 1;
1729n/a const wchar_t invalid[1] = {(wchar_t)0x110000u};
1730n/a#else
1731n/a const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
1732n/a size_t wtextlen = 2;
1733n/a#endif
1734n/a PyObject *wide, *utf8;
1735n/a
1736n/a wide = PyUnicode_FromWideChar(wtext, wtextlen);
1737n/a if (wide == NULL)
1738n/a return NULL;
1739n/a
1740n/a utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
1741n/a if (utf8 == NULL) {
1742n/a Py_DECREF(wide);
1743n/a return NULL;
1744n/a }
1745n/a
1746n/a if (PyUnicode_GET_LENGTH(wide) != PyUnicode_GET_LENGTH(utf8)) {
1747n/a Py_DECREF(wide);
1748n/a Py_DECREF(utf8);
1749n/a return raiseTestError("test_widechar",
1750n/a "wide string and utf8 string "
1751n/a "have different length");
1752n/a }
1753n/a if (PyUnicode_Compare(wide, utf8)) {
1754n/a Py_DECREF(wide);
1755n/a Py_DECREF(utf8);
1756n/a if (PyErr_Occurred())
1757n/a return NULL;
1758n/a return raiseTestError("test_widechar",
1759n/a "wide string and utf8 string "
1760n/a "are different");
1761n/a }
1762n/a
1763n/a Py_DECREF(wide);
1764n/a Py_DECREF(utf8);
1765n/a
1766n/a#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
1767n/a wide = PyUnicode_FromWideChar(invalid, 1);
1768n/a if (wide == NULL)
1769n/a PyErr_Clear();
1770n/a else
1771n/a return raiseTestError("test_widechar",
1772n/a "PyUnicode_FromWideChar(L\"\\U00110000\", 1) didn't fail");
1773n/a
1774n/a wide = PyUnicode_FromUnicode(invalid, 1);
1775n/a if (wide == NULL)
1776n/a PyErr_Clear();
1777n/a else
1778n/a return raiseTestError("test_widechar",
1779n/a "PyUnicode_FromUnicode(L\"\\U00110000\", 1) didn't fail");
1780n/a
1781n/a wide = PyUnicode_FromUnicode(NULL, 1);
1782n/a if (wide == NULL)
1783n/a return NULL;
1784n/a PyUnicode_AS_UNICODE(wide)[0] = invalid[0];
1785n/a if (_PyUnicode_Ready(wide) < 0) {
1786n/a Py_DECREF(wide);
1787n/a PyErr_Clear();
1788n/a }
1789n/a else {
1790n/a Py_DECREF(wide);
1791n/a return raiseTestError("test_widechar",
1792n/a "PyUnicode_Ready() didn't fail");
1793n/a }
1794n/a#endif
1795n/a
1796n/a Py_RETURN_NONE;
1797n/a}
1798n/a
1799n/astatic PyObject *
1800n/aunicode_aswidechar(PyObject *self, PyObject *args)
1801n/a{
1802n/a PyObject *unicode, *result;
1803n/a Py_ssize_t buflen, size;
1804n/a wchar_t *buffer;
1805n/a
1806n/a if (!PyArg_ParseTuple(args, "Un", &unicode, &buflen))
1807n/a return NULL;
1808n/a buffer = PyMem_New(wchar_t, buflen);
1809n/a if (buffer == NULL)
1810n/a return PyErr_NoMemory();
1811n/a
1812n/a size = PyUnicode_AsWideChar(unicode, buffer, buflen);
1813n/a if (size == -1) {
1814n/a PyMem_Free(buffer);
1815n/a return NULL;
1816n/a }
1817n/a
1818n/a if (size < buflen)
1819n/a buflen = size + 1;
1820n/a else
1821n/a buflen = size;
1822n/a result = PyUnicode_FromWideChar(buffer, buflen);
1823n/a PyMem_Free(buffer);
1824n/a if (result == NULL)
1825n/a return NULL;
1826n/a
1827n/a return Py_BuildValue("(Nn)", result, size);
1828n/a}
1829n/a
1830n/astatic PyObject *
1831n/aunicode_aswidecharstring(PyObject *self, PyObject *args)
1832n/a{
1833n/a PyObject *unicode, *result;
1834n/a Py_ssize_t size;
1835n/a wchar_t *buffer;
1836n/a
1837n/a if (!PyArg_ParseTuple(args, "U", &unicode))
1838n/a return NULL;
1839n/a
1840n/a buffer = PyUnicode_AsWideCharString(unicode, &size);
1841n/a if (buffer == NULL)
1842n/a return NULL;
1843n/a
1844n/a result = PyUnicode_FromWideChar(buffer, size + 1);
1845n/a PyMem_Free(buffer);
1846n/a if (result == NULL)
1847n/a return NULL;
1848n/a return Py_BuildValue("(Nn)", result, size);
1849n/a}
1850n/a
1851n/astatic PyObject *
1852n/aunicode_asucs4(PyObject *self, PyObject *args)
1853n/a{
1854n/a PyObject *unicode, *result;
1855n/a Py_UCS4 *buffer;
1856n/a int copy_null;
1857n/a Py_ssize_t str_len, buf_len;
1858n/a
1859n/a if (!PyArg_ParseTuple(args, "Unp:unicode_asucs4", &unicode, &str_len, &copy_null)) {
1860n/a return NULL;
1861n/a }
1862n/a
1863n/a buf_len = str_len + 1;
1864n/a buffer = PyMem_NEW(Py_UCS4, buf_len);
1865n/a if (buffer == NULL) {
1866n/a return PyErr_NoMemory();
1867n/a }
1868n/a memset(buffer, 0, sizeof(Py_UCS4)*buf_len);
1869n/a buffer[str_len] = 0xffffU;
1870n/a
1871n/a if (!PyUnicode_AsUCS4(unicode, buffer, buf_len, copy_null)) {
1872n/a PyMem_FREE(buffer);
1873n/a return NULL;
1874n/a }
1875n/a
1876n/a result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buffer, buf_len);
1877n/a PyMem_FREE(buffer);
1878n/a return result;
1879n/a}
1880n/a
1881n/astatic PyObject *
1882n/aunicode_findchar(PyObject *self, PyObject *args)
1883n/a{
1884n/a PyObject *str;
1885n/a int direction;
1886n/a unsigned int ch;
1887n/a Py_ssize_t result;
1888n/a Py_ssize_t start, end;
1889n/a
1890n/a if (!PyArg_ParseTuple(args, "UInni:unicode_findchar", &str, &ch,
1891n/a &start, &end, &direction)) {
1892n/a return NULL;
1893n/a }
1894n/a
1895n/a result = PyUnicode_FindChar(str, (Py_UCS4)ch, start, end, direction);
1896n/a if (result == -2)
1897n/a return NULL;
1898n/a else
1899n/a return PyLong_FromSsize_t(result);
1900n/a}
1901n/a
1902n/astatic PyObject *
1903n/aunicode_copycharacters(PyObject *self, PyObject *args)
1904n/a{
1905n/a PyObject *from, *to, *to_copy;
1906n/a Py_ssize_t from_start, to_start, how_many, copied;
1907n/a
1908n/a if (!PyArg_ParseTuple(args, "UnOnn:unicode_copycharacters", &to, &to_start,
1909n/a &from, &from_start, &how_many)) {
1910n/a return NULL;
1911n/a }
1912n/a
1913n/a if (!(to_copy = PyUnicode_New(PyUnicode_GET_LENGTH(to),
1914n/a PyUnicode_MAX_CHAR_VALUE(to)))) {
1915n/a return NULL;
1916n/a }
1917n/a if (PyUnicode_Fill(to_copy, 0, PyUnicode_GET_LENGTH(to_copy), 0U) < 0) {
1918n/a Py_DECREF(to_copy);
1919n/a return NULL;
1920n/a }
1921n/a
1922n/a if ((copied = PyUnicode_CopyCharacters(to_copy, to_start, from,
1923n/a from_start, how_many)) < 0) {
1924n/a Py_DECREF(to_copy);
1925n/a return NULL;
1926n/a }
1927n/a
1928n/a return Py_BuildValue("(Nn)", to_copy, copied);
1929n/a}
1930n/a
1931n/astatic PyObject *
1932n/aunicode_encodedecimal(PyObject *self, PyObject *args)
1933n/a{
1934n/a Py_UNICODE *unicode;
1935n/a Py_ssize_t length;
1936n/a char *errors = NULL;
1937n/a PyObject *decimal;
1938n/a Py_ssize_t decimal_length, new_length;
1939n/a int res;
1940n/a
1941n/a if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors))
1942n/a return NULL;
1943n/a
1944n/a decimal_length = length * 7; /* len('&#8364;') */
1945n/a decimal = PyBytes_FromStringAndSize(NULL, decimal_length);
1946n/a if (decimal == NULL)
1947n/a return NULL;
1948n/a
1949n/a res = PyUnicode_EncodeDecimal(unicode, length,
1950n/a PyBytes_AS_STRING(decimal),
1951n/a errors);
1952n/a if (res < 0) {
1953n/a Py_DECREF(decimal);
1954n/a return NULL;
1955n/a }
1956n/a
1957n/a new_length = strlen(PyBytes_AS_STRING(decimal));
1958n/a assert(new_length <= decimal_length);
1959n/a res = _PyBytes_Resize(&decimal, new_length);
1960n/a if (res < 0)
1961n/a return NULL;
1962n/a
1963n/a return decimal;
1964n/a}
1965n/a
1966n/astatic PyObject *
1967n/aunicode_transformdecimaltoascii(PyObject *self, PyObject *args)
1968n/a{
1969n/a Py_UNICODE *unicode;
1970n/a Py_ssize_t length;
1971n/a if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length))
1972n/a return NULL;
1973n/a return PyUnicode_TransformDecimalToASCII(unicode, length);
1974n/a}
1975n/a
1976n/astatic PyObject *
1977n/aunicode_legacy_string(PyObject *self, PyObject *args)
1978n/a{
1979n/a Py_UNICODE *data;
1980n/a Py_ssize_t len;
1981n/a PyObject *u;
1982n/a
1983n/a if (!PyArg_ParseTuple(args, "u#", &data, &len))
1984n/a return NULL;
1985n/a
1986n/a u = PyUnicode_FromUnicode(NULL, len);
1987n/a if (u == NULL)
1988n/a return NULL;
1989n/a
1990n/a memcpy(PyUnicode_AS_UNICODE(u), data, len * sizeof(Py_UNICODE));
1991n/a
1992n/a if (len > 0) { /* The empty string is always ready. */
1993n/a assert(!PyUnicode_IS_READY(u));
1994n/a }
1995n/a
1996n/a return u;
1997n/a}
1998n/a
1999n/astatic PyObject *
2000n/agetargs_w_star(PyObject *self, PyObject *args)
2001n/a{
2002n/a Py_buffer buffer;
2003n/a PyObject *result;
2004n/a char *str;
2005n/a
2006n/a if (!PyArg_ParseTuple(args, "w*:getargs_w_star", &buffer))
2007n/a return NULL;
2008n/a
2009n/a if (2 <= buffer.len) {
2010n/a str = buffer.buf;
2011n/a str[0] = '[';
2012n/a str[buffer.len-1] = ']';
2013n/a }
2014n/a
2015n/a result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
2016n/a PyBuffer_Release(&buffer);
2017n/a return result;
2018n/a}
2019n/a
2020n/a
2021n/astatic PyObject *
2022n/atest_empty_argparse(PyObject *self)
2023n/a{
2024n/a /* Test that formats can begin with '|'. See issue #4720. */
2025n/a PyObject *tuple, *dict = NULL;
2026n/a static char *kwlist[] = {NULL};
2027n/a int result;
2028n/a tuple = PyTuple_New(0);
2029n/a if (!tuple)
2030n/a return NULL;
2031n/a if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
2032n/a goto done;
2033n/a dict = PyDict_New();
2034n/a if (!dict)
2035n/a goto done;
2036n/a result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
2037n/a done:
2038n/a Py_DECREF(tuple);
2039n/a Py_XDECREF(dict);
2040n/a if (result < 0)
2041n/a return NULL;
2042n/a else {
2043n/a Py_RETURN_NONE;
2044n/a }
2045n/a}
2046n/a
2047n/astatic PyObject *
2048n/acodec_incrementalencoder(PyObject *self, PyObject *args)
2049n/a{
2050n/a const char *encoding, *errors = NULL;
2051n/a if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
2052n/a &encoding, &errors))
2053n/a return NULL;
2054n/a return PyCodec_IncrementalEncoder(encoding, errors);
2055n/a}
2056n/a
2057n/astatic PyObject *
2058n/acodec_incrementaldecoder(PyObject *self, PyObject *args)
2059n/a{
2060n/a const char *encoding, *errors = NULL;
2061n/a if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
2062n/a &encoding, &errors))
2063n/a return NULL;
2064n/a return PyCodec_IncrementalDecoder(encoding, errors);
2065n/a}
2066n/a
2067n/a
2068n/a/* Simple test of _PyLong_NumBits and _PyLong_Sign. */
2069n/astatic PyObject *
2070n/atest_long_numbits(PyObject *self)
2071n/a{
2072n/a struct triple {
2073n/a long input;
2074n/a size_t nbits;
2075n/a int sign;
2076n/a } testcases[] = {{0, 0, 0},
2077n/a {1L, 1, 1},
2078n/a {-1L, 1, -1},
2079n/a {2L, 2, 1},
2080n/a {-2L, 2, -1},
2081n/a {3L, 2, 1},
2082n/a {-3L, 2, -1},
2083n/a {4L, 3, 1},
2084n/a {-4L, 3, -1},
2085n/a {0x7fffL, 15, 1}, /* one Python int digit */
2086n/a {-0x7fffL, 15, -1},
2087n/a {0xffffL, 16, 1},
2088n/a {-0xffffL, 16, -1},
2089n/a {0xfffffffL, 28, 1},
2090n/a {-0xfffffffL, 28, -1}};
2091n/a size_t i;
2092n/a
2093n/a for (i = 0; i < Py_ARRAY_LENGTH(testcases); ++i) {
2094n/a size_t nbits;
2095n/a int sign;
2096n/a PyObject *plong;
2097n/a
2098n/a plong = PyLong_FromLong(testcases[i].input);
2099n/a if (plong == NULL)
2100n/a return NULL;
2101n/a nbits = _PyLong_NumBits(plong);
2102n/a sign = _PyLong_Sign(plong);
2103n/a
2104n/a Py_DECREF(plong);
2105n/a if (nbits != testcases[i].nbits)
2106n/a return raiseTestError("test_long_numbits",
2107n/a "wrong result for _PyLong_NumBits");
2108n/a if (sign != testcases[i].sign)
2109n/a return raiseTestError("test_long_numbits",
2110n/a "wrong result for _PyLong_Sign");
2111n/a }
2112n/a Py_RETURN_NONE;
2113n/a}
2114n/a
2115n/a/* Example passing NULLs to PyObject_Str(NULL). */
2116n/a
2117n/astatic PyObject *
2118n/atest_null_strings(PyObject *self)
2119n/a{
2120n/a PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL);
2121n/a PyObject *tuple = PyTuple_Pack(2, o1, o2);
2122n/a Py_XDECREF(o1);
2123n/a Py_XDECREF(o2);
2124n/a return tuple;
2125n/a}
2126n/a
2127n/astatic PyObject *
2128n/araise_exception(PyObject *self, PyObject *args)
2129n/a{
2130n/a PyObject *exc;
2131n/a PyObject *exc_args, *v;
2132n/a int num_args, i;
2133n/a
2134n/a if (!PyArg_ParseTuple(args, "Oi:raise_exception",
2135n/a &exc, &num_args))
2136n/a return NULL;
2137n/a
2138n/a exc_args = PyTuple_New(num_args);
2139n/a if (exc_args == NULL)
2140n/a return NULL;
2141n/a for (i = 0; i < num_args; ++i) {
2142n/a v = PyLong_FromLong(i);
2143n/a if (v == NULL) {
2144n/a Py_DECREF(exc_args);
2145n/a return NULL;
2146n/a }
2147n/a PyTuple_SET_ITEM(exc_args, i, v);
2148n/a }
2149n/a PyErr_SetObject(exc, exc_args);
2150n/a Py_DECREF(exc_args);
2151n/a return NULL;
2152n/a}
2153n/a
2154n/astatic PyObject *
2155n/aset_errno(PyObject *self, PyObject *args)
2156n/a{
2157n/a int new_errno;
2158n/a
2159n/a if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
2160n/a return NULL;
2161n/a
2162n/a errno = new_errno;
2163n/a Py_RETURN_NONE;
2164n/a}
2165n/a
2166n/astatic PyObject *
2167n/atest_set_exc_info(PyObject *self, PyObject *args)
2168n/a{
2169n/a PyObject *orig_exc;
2170n/a PyObject *new_type, *new_value, *new_tb;
2171n/a PyObject *type, *value, *tb;
2172n/a if (!PyArg_ParseTuple(args, "OOO:test_set_exc_info",
2173n/a &new_type, &new_value, &new_tb))
2174n/a return NULL;
2175n/a
2176n/a PyErr_GetExcInfo(&type, &value, &tb);
2177n/a
2178n/a Py_INCREF(new_type);
2179n/a Py_INCREF(new_value);
2180n/a Py_INCREF(new_tb);
2181n/a PyErr_SetExcInfo(new_type, new_value, new_tb);
2182n/a
2183n/a orig_exc = PyTuple_Pack(3, type ? type : Py_None, value ? value : Py_None, tb ? tb : Py_None);
2184n/a Py_XDECREF(type);
2185n/a Py_XDECREF(value);
2186n/a Py_XDECREF(tb);
2187n/a return orig_exc;
2188n/a}
2189n/a
2190n/astatic int test_run_counter = 0;
2191n/a
2192n/astatic PyObject *
2193n/atest_datetime_capi(PyObject *self, PyObject *args) {
2194n/a if (PyDateTimeAPI) {
2195n/a if (test_run_counter) {
2196n/a /* Probably regrtest.py -R */
2197n/a Py_RETURN_NONE;
2198n/a }
2199n/a else {
2200n/a PyErr_SetString(PyExc_AssertionError,
2201n/a "PyDateTime_CAPI somehow initialized");
2202n/a return NULL;
2203n/a }
2204n/a }
2205n/a test_run_counter++;
2206n/a PyDateTime_IMPORT;
2207n/a if (PyDateTimeAPI)
2208n/a Py_RETURN_NONE;
2209n/a else
2210n/a return NULL;
2211n/a}
2212n/a
2213n/a
2214n/a#ifdef WITH_THREAD
2215n/a
2216n/a/* test_thread_state spawns a thread of its own, and that thread releases
2217n/a * `thread_done` when it's finished. The driver code has to know when the
2218n/a * thread finishes, because the thread uses a PyObject (the callable) that
2219n/a * may go away when the driver finishes. The former lack of this explicit
2220n/a * synchronization caused rare segfaults, so rare that they were seen only
2221n/a * on a Mac buildbot (although they were possible on any box).
2222n/a */
2223n/astatic PyThread_type_lock thread_done = NULL;
2224n/a
2225n/astatic int
2226n/a_make_call(void *callable)
2227n/a{
2228n/a PyObject *rc;
2229n/a int success;
2230n/a PyGILState_STATE s = PyGILState_Ensure();
2231n/a rc = _PyObject_CallNoArg((PyObject *)callable);
2232n/a success = (rc != NULL);
2233n/a Py_XDECREF(rc);
2234n/a PyGILState_Release(s);
2235n/a return success;
2236n/a}
2237n/a
2238n/a/* Same thing, but releases `thread_done` when it returns. This variant
2239n/a * should be called only from threads spawned by test_thread_state().
2240n/a */
2241n/astatic void
2242n/a_make_call_from_thread(void *callable)
2243n/a{
2244n/a _make_call(callable);
2245n/a PyThread_release_lock(thread_done);
2246n/a}
2247n/a
2248n/astatic PyObject *
2249n/atest_thread_state(PyObject *self, PyObject *args)
2250n/a{
2251n/a PyObject *fn;
2252n/a int success = 1;
2253n/a
2254n/a if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
2255n/a return NULL;
2256n/a
2257n/a if (!PyCallable_Check(fn)) {
2258n/a PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
2259n/a fn->ob_type->tp_name);
2260n/a return NULL;
2261n/a }
2262n/a
2263n/a /* Ensure Python is set up for threading */
2264n/a PyEval_InitThreads();
2265n/a thread_done = PyThread_allocate_lock();
2266n/a if (thread_done == NULL)
2267n/a return PyErr_NoMemory();
2268n/a PyThread_acquire_lock(thread_done, 1);
2269n/a
2270n/a /* Start a new thread with our callback. */
2271n/a PyThread_start_new_thread(_make_call_from_thread, fn);
2272n/a /* Make the callback with the thread lock held by this thread */
2273n/a success &= _make_call(fn);
2274n/a /* Do it all again, but this time with the thread-lock released */
2275n/a Py_BEGIN_ALLOW_THREADS
2276n/a success &= _make_call(fn);
2277n/a PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2278n/a Py_END_ALLOW_THREADS
2279n/a
2280n/a /* And once more with and without a thread
2281n/a XXX - should use a lock and work out exactly what we are trying
2282n/a to test <wink>
2283n/a */
2284n/a Py_BEGIN_ALLOW_THREADS
2285n/a PyThread_start_new_thread(_make_call_from_thread, fn);
2286n/a success &= _make_call(fn);
2287n/a PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2288n/a Py_END_ALLOW_THREADS
2289n/a
2290n/a /* Release lock we acquired above. This is required on HP-UX. */
2291n/a PyThread_release_lock(thread_done);
2292n/a
2293n/a PyThread_free_lock(thread_done);
2294n/a if (!success)
2295n/a return NULL;
2296n/a Py_RETURN_NONE;
2297n/a}
2298n/a
2299n/a/* test Py_AddPendingCalls using threads */
2300n/astatic int _pending_callback(void *arg)
2301n/a{
2302n/a /* we assume the argument is callable object to which we own a reference */
2303n/a PyObject *callable = (PyObject *)arg;
2304n/a PyObject *r = _PyObject_CallNoArg(callable);
2305n/a Py_DECREF(callable);
2306n/a Py_XDECREF(r);
2307n/a return r != NULL ? 0 : -1;
2308n/a}
2309n/a
2310n/a/* The following requests n callbacks to _pending_callback. It can be
2311n/a * run from any python thread.
2312n/a */
2313n/aPyObject *pending_threadfunc(PyObject *self, PyObject *arg)
2314n/a{
2315n/a PyObject *callable;
2316n/a int r;
2317n/a if (PyArg_ParseTuple(arg, "O", &callable) == 0)
2318n/a return NULL;
2319n/a
2320n/a /* create the reference for the callbackwhile we hold the lock */
2321n/a Py_INCREF(callable);
2322n/a
2323n/a Py_BEGIN_ALLOW_THREADS
2324n/a r = Py_AddPendingCall(&_pending_callback, callable);
2325n/a Py_END_ALLOW_THREADS
2326n/a
2327n/a if (r<0) {
2328n/a Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
2329n/a Py_RETURN_FALSE;
2330n/a }
2331n/a Py_RETURN_TRUE;
2332n/a}
2333n/a#endif
2334n/a
2335n/a/* Some tests of PyUnicode_FromFormat(). This needs more tests. */
2336n/astatic PyObject *
2337n/atest_string_from_format(PyObject *self, PyObject *args)
2338n/a{
2339n/a PyObject *result;
2340n/a char *msg;
2341n/a
2342n/a#define CHECK_1_FORMAT(FORMAT, TYPE) \
2343n/a result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
2344n/a if (result == NULL) \
2345n/a return NULL; \
2346n/a if (!_PyUnicode_EqualToASCIIString(result, "1")) { \
2347n/a msg = FORMAT " failed at 1"; \
2348n/a goto Fail; \
2349n/a } \
2350n/a Py_DECREF(result)
2351n/a
2352n/a CHECK_1_FORMAT("%d", int);
2353n/a CHECK_1_FORMAT("%ld", long);
2354n/a /* The z width modifier was added in Python 2.5. */
2355n/a CHECK_1_FORMAT("%zd", Py_ssize_t);
2356n/a
2357n/a /* The u type code was added in Python 2.5. */
2358n/a CHECK_1_FORMAT("%u", unsigned int);
2359n/a CHECK_1_FORMAT("%lu", unsigned long);
2360n/a CHECK_1_FORMAT("%zu", size_t);
2361n/a
2362n/a /* "%lld" and "%llu" support added in Python 2.7. */
2363n/a CHECK_1_FORMAT("%llu", unsigned long long);
2364n/a CHECK_1_FORMAT("%lld", long long);
2365n/a
2366n/a Py_RETURN_NONE;
2367n/a
2368n/a Fail:
2369n/a Py_XDECREF(result);
2370n/a return raiseTestError("test_string_from_format", msg);
2371n/a
2372n/a#undef CHECK_1_FORMAT
2373n/a}
2374n/a
2375n/a
2376n/astatic PyObject *
2377n/atest_unicode_compare_with_ascii(PyObject *self) {
2378n/a PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
2379n/a int result;
2380n/a if (py_s == NULL)
2381n/a return NULL;
2382n/a result = PyUnicode_CompareWithASCIIString(py_s, "str");
2383n/a Py_DECREF(py_s);
2384n/a if (!result) {
2385n/a PyErr_SetString(TestError, "Python string ending in NULL "
2386n/a "should not compare equal to c string.");
2387n/a return NULL;
2388n/a }
2389n/a Py_RETURN_NONE;
2390n/a}
2391n/a
2392n/a/* This is here to provide a docstring for test_descr. */
2393n/astatic PyObject *
2394n/atest_with_docstring(PyObject *self)
2395n/a{
2396n/a Py_RETURN_NONE;
2397n/a}
2398n/a
2399n/a/* Test PyOS_string_to_double. */
2400n/astatic PyObject *
2401n/atest_string_to_double(PyObject *self) {
2402n/a double result;
2403n/a char *msg;
2404n/a
2405n/a#define CHECK_STRING(STR, expected) \
2406n/a result = PyOS_string_to_double(STR, NULL, NULL); \
2407n/a if (result == -1.0 && PyErr_Occurred()) \
2408n/a return NULL; \
2409n/a if (result != (double)expected) { \
2410n/a msg = "conversion of " STR " to float failed"; \
2411n/a goto fail; \
2412n/a }
2413n/a
2414n/a#define CHECK_INVALID(STR) \
2415n/a result = PyOS_string_to_double(STR, NULL, NULL); \
2416n/a if (result == -1.0 && PyErr_Occurred()) { \
2417n/a if (PyErr_ExceptionMatches(PyExc_ValueError)) \
2418n/a PyErr_Clear(); \
2419n/a else \
2420n/a return NULL; \
2421n/a } \
2422n/a else { \
2423n/a msg = "conversion of " STR " didn't raise ValueError"; \
2424n/a goto fail; \
2425n/a }
2426n/a
2427n/a CHECK_STRING("0.1", 0.1);
2428n/a CHECK_STRING("1.234", 1.234);
2429n/a CHECK_STRING("-1.35", -1.35);
2430n/a CHECK_STRING(".1e01", 1.0);
2431n/a CHECK_STRING("2.e-2", 0.02);
2432n/a
2433n/a CHECK_INVALID(" 0.1");
2434n/a CHECK_INVALID("\t\n-3");
2435n/a CHECK_INVALID(".123 ");
2436n/a CHECK_INVALID("3\n");
2437n/a CHECK_INVALID("123abc");
2438n/a
2439n/a Py_RETURN_NONE;
2440n/a fail:
2441n/a return raiseTestError("test_string_to_double", msg);
2442n/a#undef CHECK_STRING
2443n/a#undef CHECK_INVALID
2444n/a}
2445n/a
2446n/a
2447n/a/* Coverage testing of capsule objects. */
2448n/a
2449n/astatic const char *capsule_name = "capsule name";
2450n/astatic char *capsule_pointer = "capsule pointer";
2451n/astatic char *capsule_context = "capsule context";
2452n/astatic const char *capsule_error = NULL;
2453n/astatic int
2454n/acapsule_destructor_call_count = 0;
2455n/a
2456n/astatic void
2457n/acapsule_destructor(PyObject *o) {
2458n/a capsule_destructor_call_count++;
2459n/a if (PyCapsule_GetContext(o) != capsule_context) {
2460n/a capsule_error = "context did not match in destructor!";
2461n/a } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
2462n/a capsule_error = "destructor did not match in destructor! (woah!)";
2463n/a } else if (PyCapsule_GetName(o) != capsule_name) {
2464n/a capsule_error = "name did not match in destructor!";
2465n/a } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
2466n/a capsule_error = "pointer did not match in destructor!";
2467n/a }
2468n/a}
2469n/a
2470n/atypedef struct {
2471n/a char *name;
2472n/a char *module;
2473n/a char *attribute;
2474n/a} known_capsule;
2475n/a
2476n/astatic PyObject *
2477n/atest_capsule(PyObject *self, PyObject *args)
2478n/a{
2479n/a PyObject *object;
2480n/a const char *error = NULL;
2481n/a void *pointer;
2482n/a void *pointer2;
2483n/a known_capsule known_capsules[] = {
2484n/a #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
2485n/a KNOWN_CAPSULE("_socket", "CAPI"),
2486n/a KNOWN_CAPSULE("_curses", "_C_API"),
2487n/a KNOWN_CAPSULE("datetime", "datetime_CAPI"),
2488n/a { NULL, NULL },
2489n/a };
2490n/a known_capsule *known = &known_capsules[0];
2491n/a
2492n/a#define FAIL(x) { error = (x); goto exit; }
2493n/a
2494n/a#define CHECK_DESTRUCTOR \
2495n/a if (capsule_error) { \
2496n/a FAIL(capsule_error); \
2497n/a } \
2498n/a else if (!capsule_destructor_call_count) { \
2499n/a FAIL("destructor not called!"); \
2500n/a } \
2501n/a capsule_destructor_call_count = 0; \
2502n/a
2503n/a object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
2504n/a PyCapsule_SetContext(object, capsule_context);
2505n/a capsule_destructor(object);
2506n/a CHECK_DESTRUCTOR;
2507n/a Py_DECREF(object);
2508n/a CHECK_DESTRUCTOR;
2509n/a
2510n/a object = PyCapsule_New(known, "ignored", NULL);
2511n/a PyCapsule_SetPointer(object, capsule_pointer);
2512n/a PyCapsule_SetName(object, capsule_name);
2513n/a PyCapsule_SetDestructor(object, capsule_destructor);
2514n/a PyCapsule_SetContext(object, capsule_context);
2515n/a capsule_destructor(object);
2516n/a CHECK_DESTRUCTOR;
2517n/a /* intentionally access using the wrong name */
2518n/a pointer2 = PyCapsule_GetPointer(object, "the wrong name");
2519n/a if (!PyErr_Occurred()) {
2520n/a FAIL("PyCapsule_GetPointer should have failed but did not!");
2521n/a }
2522n/a PyErr_Clear();
2523n/a if (pointer2) {
2524n/a if (pointer2 == capsule_pointer) {
2525n/a FAIL("PyCapsule_GetPointer should not have"
2526n/a " returned the internal pointer!");
2527n/a } else {
2528n/a FAIL("PyCapsule_GetPointer should have "
2529n/a "returned NULL pointer but did not!");
2530n/a }
2531n/a }
2532n/a PyCapsule_SetDestructor(object, NULL);
2533n/a Py_DECREF(object);
2534n/a if (capsule_destructor_call_count) {
2535n/a FAIL("destructor called when it should not have been!");
2536n/a }
2537n/a
2538n/a for (known = &known_capsules[0]; known->module != NULL; known++) {
2539n/a /* yeah, ordinarily I wouldn't do this either,
2540n/a but it's fine for this test harness.
2541n/a */
2542n/a static char buffer[256];
2543n/a#undef FAIL
2544n/a#define FAIL(x) \
2545n/a { \
2546n/a sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
2547n/a x, known->module, known->attribute); \
2548n/a error = buffer; \
2549n/a goto exit; \
2550n/a } \
2551n/a
2552n/a PyObject *module = PyImport_ImportModule(known->module);
2553n/a if (module) {
2554n/a pointer = PyCapsule_Import(known->name, 0);
2555n/a if (!pointer) {
2556n/a Py_DECREF(module);
2557n/a FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
2558n/a }
2559n/a object = PyObject_GetAttrString(module, known->attribute);
2560n/a if (!object) {
2561n/a Py_DECREF(module);
2562n/a return NULL;
2563n/a }
2564n/a pointer2 = PyCapsule_GetPointer(object,
2565n/a "weebles wobble but they don't fall down");
2566n/a if (!PyErr_Occurred()) {
2567n/a Py_DECREF(object);
2568n/a Py_DECREF(module);
2569n/a FAIL("PyCapsule_GetPointer should have failed but did not!");
2570n/a }
2571n/a PyErr_Clear();
2572n/a if (pointer2) {
2573n/a Py_DECREF(module);
2574n/a Py_DECREF(object);
2575n/a if (pointer2 == pointer) {
2576n/a FAIL("PyCapsule_GetPointer should not have"
2577n/a " returned its internal pointer!");
2578n/a } else {
2579n/a FAIL("PyCapsule_GetPointer should have"
2580n/a " returned NULL pointer but did not!");
2581n/a }
2582n/a }
2583n/a Py_DECREF(object);
2584n/a Py_DECREF(module);
2585n/a }
2586n/a else
2587n/a PyErr_Clear();
2588n/a }
2589n/a
2590n/a exit:
2591n/a if (error) {
2592n/a return raiseTestError("test_capsule", error);
2593n/a }
2594n/a Py_RETURN_NONE;
2595n/a#undef FAIL
2596n/a}
2597n/a
2598n/a#ifdef HAVE_GETTIMEOFDAY
2599n/a/* Profiling of integer performance */
2600n/astatic void print_delta(int test, struct timeval *s, struct timeval *e)
2601n/a{
2602n/a e->tv_sec -= s->tv_sec;
2603n/a e->tv_usec -= s->tv_usec;
2604n/a if (e->tv_usec < 0) {
2605n/a e->tv_sec -=1;
2606n/a e->tv_usec += 1000000;
2607n/a }
2608n/a printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
2609n/a}
2610n/a
2611n/astatic PyObject *
2612n/aprofile_int(PyObject *self, PyObject* args)
2613n/a{
2614n/a int i, k;
2615n/a struct timeval start, stop;
2616n/a PyObject *single, **multiple, *op1, *result;
2617n/a
2618n/a /* Test 1: Allocate and immediately deallocate
2619n/a many small integers */
2620n/a gettimeofday(&start, NULL);
2621n/a for(k=0; k < 20000; k++)
2622n/a for(i=0; i < 1000; i++) {
2623n/a single = PyLong_FromLong(i);
2624n/a Py_DECREF(single);
2625n/a }
2626n/a gettimeofday(&stop, NULL);
2627n/a print_delta(1, &start, &stop);
2628n/a
2629n/a /* Test 2: Allocate and immediately deallocate
2630n/a many large integers */
2631n/a gettimeofday(&start, NULL);
2632n/a for(k=0; k < 20000; k++)
2633n/a for(i=0; i < 1000; i++) {
2634n/a single = PyLong_FromLong(i+1000000);
2635n/a Py_DECREF(single);
2636n/a }
2637n/a gettimeofday(&stop, NULL);
2638n/a print_delta(2, &start, &stop);
2639n/a
2640n/a /* Test 3: Allocate a few integers, then release
2641n/a them all simultaneously. */
2642n/a multiple = malloc(sizeof(PyObject*) * 1000);
2643n/a if (multiple == NULL)
2644n/a return PyErr_NoMemory();
2645n/a gettimeofday(&start, NULL);
2646n/a for(k=0; k < 20000; k++) {
2647n/a for(i=0; i < 1000; i++) {
2648n/a multiple[i] = PyLong_FromLong(i+1000000);
2649n/a }
2650n/a for(i=0; i < 1000; i++) {
2651n/a Py_DECREF(multiple[i]);
2652n/a }
2653n/a }
2654n/a gettimeofday(&stop, NULL);
2655n/a print_delta(3, &start, &stop);
2656n/a free(multiple);
2657n/a
2658n/a /* Test 4: Allocate many integers, then release
2659n/a them all simultaneously. */
2660n/a multiple = malloc(sizeof(PyObject*) * 1000000);
2661n/a if (multiple == NULL)
2662n/a return PyErr_NoMemory();
2663n/a gettimeofday(&start, NULL);
2664n/a for(k=0; k < 20; k++) {
2665n/a for(i=0; i < 1000000; i++) {
2666n/a multiple[i] = PyLong_FromLong(i+1000000);
2667n/a }
2668n/a for(i=0; i < 1000000; i++) {
2669n/a Py_DECREF(multiple[i]);
2670n/a }
2671n/a }
2672n/a gettimeofday(&stop, NULL);
2673n/a print_delta(4, &start, &stop);
2674n/a free(multiple);
2675n/a
2676n/a /* Test 5: Allocate many integers < 32000 */
2677n/a multiple = malloc(sizeof(PyObject*) * 1000000);
2678n/a if (multiple == NULL)
2679n/a return PyErr_NoMemory();
2680n/a gettimeofday(&start, NULL);
2681n/a for(k=0; k < 10; k++) {
2682n/a for(i=0; i < 1000000; i++) {
2683n/a multiple[i] = PyLong_FromLong(i+1000);
2684n/a }
2685n/a for(i=0; i < 1000000; i++) {
2686n/a Py_DECREF(multiple[i]);
2687n/a }
2688n/a }
2689n/a gettimeofday(&stop, NULL);
2690n/a print_delta(5, &start, &stop);
2691n/a free(multiple);
2692n/a
2693n/a /* Test 6: Perform small int addition */
2694n/a op1 = PyLong_FromLong(1);
2695n/a gettimeofday(&start, NULL);
2696n/a for(i=0; i < 10000000; i++) {
2697n/a result = PyNumber_Add(op1, op1);
2698n/a Py_DECREF(result);
2699n/a }
2700n/a gettimeofday(&stop, NULL);
2701n/a Py_DECREF(op1);
2702n/a print_delta(6, &start, &stop);
2703n/a
2704n/a /* Test 7: Perform medium int addition */
2705n/a op1 = PyLong_FromLong(1000);
2706n/a if (op1 == NULL)
2707n/a return NULL;
2708n/a gettimeofday(&start, NULL);
2709n/a for(i=0; i < 10000000; i++) {
2710n/a result = PyNumber_Add(op1, op1);
2711n/a Py_XDECREF(result);
2712n/a }
2713n/a gettimeofday(&stop, NULL);
2714n/a Py_DECREF(op1);
2715n/a print_delta(7, &start, &stop);
2716n/a
2717n/a Py_RETURN_NONE;
2718n/a}
2719n/a#endif
2720n/a
2721n/a/* To test the format of tracebacks as printed out. */
2722n/astatic PyObject *
2723n/atraceback_print(PyObject *self, PyObject *args)
2724n/a{
2725n/a PyObject *file;
2726n/a PyObject *traceback;
2727n/a int result;
2728n/a
2729n/a if (!PyArg_ParseTuple(args, "OO:traceback_print",
2730n/a &traceback, &file))
2731n/a return NULL;
2732n/a
2733n/a result = PyTraceBack_Print(traceback, file);
2734n/a if (result < 0)
2735n/a return NULL;
2736n/a Py_RETURN_NONE;
2737n/a}
2738n/a
2739n/a/* To test the format of exceptions as printed out. */
2740n/astatic PyObject *
2741n/aexception_print(PyObject *self, PyObject *args)
2742n/a{
2743n/a PyObject *value;
2744n/a PyObject *tb;
2745n/a
2746n/a if (!PyArg_ParseTuple(args, "O:exception_print",
2747n/a &value))
2748n/a return NULL;
2749n/a if (!PyExceptionInstance_Check(value)) {
2750n/a PyErr_Format(PyExc_TypeError, "an exception instance is required");
2751n/a return NULL;
2752n/a }
2753n/a
2754n/a tb = PyException_GetTraceback(value);
2755n/a PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
2756n/a Py_XDECREF(tb);
2757n/a
2758n/a Py_RETURN_NONE;
2759n/a}
2760n/a
2761n/a
2762n/a
2763n/a
2764n/a/* reliably raise a MemoryError */
2765n/astatic PyObject *
2766n/araise_memoryerror(PyObject *self)
2767n/a{
2768n/a PyErr_NoMemory();
2769n/a return NULL;
2770n/a}
2771n/a
2772n/a/* Issue 6012 */
2773n/astatic PyObject *str1, *str2;
2774n/astatic int
2775n/afailing_converter(PyObject *obj, void *arg)
2776n/a{
2777n/a /* Clone str1, then let the conversion fail. */
2778n/a assert(str1);
2779n/a str2 = str1;
2780n/a Py_INCREF(str2);
2781n/a return 0;
2782n/a}
2783n/astatic PyObject*
2784n/aargparsing(PyObject *o, PyObject *args)
2785n/a{
2786n/a PyObject *res;
2787n/a str1 = str2 = NULL;
2788n/a if (!PyArg_ParseTuple(args, "O&O&",
2789n/a PyUnicode_FSConverter, &str1,
2790n/a failing_converter, &str2)) {
2791n/a if (!str2)
2792n/a /* argument converter not called? */
2793n/a return NULL;
2794n/a /* Should be 1 */
2795n/a res = PyLong_FromSsize_t(Py_REFCNT(str2));
2796n/a Py_DECREF(str2);
2797n/a PyErr_Clear();
2798n/a return res;
2799n/a }
2800n/a Py_RETURN_NONE;
2801n/a}
2802n/a
2803n/a/* To test that the result of PyCode_NewEmpty has the right members. */
2804n/astatic PyObject *
2805n/acode_newempty(PyObject *self, PyObject *args)
2806n/a{
2807n/a const char *filename;
2808n/a const char *funcname;
2809n/a int firstlineno;
2810n/a
2811n/a if (!PyArg_ParseTuple(args, "ssi:code_newempty",
2812n/a &filename, &funcname, &firstlineno))
2813n/a return NULL;
2814n/a
2815n/a return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
2816n/a}
2817n/a
2818n/a/* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
2819n/a Run via Lib/test/test_exceptions.py */
2820n/astatic PyObject *
2821n/amake_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
2822n/a{
2823n/a const char *name;
2824n/a const char *doc = NULL;
2825n/a PyObject *base = NULL;
2826n/a PyObject *dict = NULL;
2827n/a
2828n/a static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
2829n/a
2830n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2831n/a "s|sOO:make_exception_with_doc", kwlist,
2832n/a &name, &doc, &base, &dict))
2833n/a return NULL;
2834n/a
2835n/a return PyErr_NewExceptionWithDoc(name, doc, base, dict);
2836n/a}
2837n/a
2838n/astatic PyObject *
2839n/amake_memoryview_from_NULL_pointer(PyObject *self)
2840n/a{
2841n/a Py_buffer info;
2842n/a if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
2843n/a return NULL;
2844n/a return PyMemoryView_FromBuffer(&info);
2845n/a}
2846n/a
2847n/astatic PyObject *
2848n/atest_from_contiguous(PyObject* self, PyObject *noargs)
2849n/a{
2850n/a int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
2851n/a int init[5] = {0, 1, 2, 3, 4};
2852n/a Py_ssize_t itemsize = sizeof(int);
2853n/a Py_ssize_t shape = 5;
2854n/a Py_ssize_t strides = 2 * itemsize;
2855n/a Py_buffer view = {
2856n/a data,
2857n/a NULL,
2858n/a 5 * itemsize,
2859n/a itemsize,
2860n/a 1,
2861n/a 1,
2862n/a NULL,
2863n/a &shape,
2864n/a &strides,
2865n/a NULL,
2866n/a NULL
2867n/a };
2868n/a int *ptr;
2869n/a int i;
2870n/a
2871n/a PyBuffer_FromContiguous(&view, init, view.len, 'C');
2872n/a ptr = view.buf;
2873n/a for (i = 0; i < 5; i++) {
2874n/a if (ptr[2*i] != i) {
2875n/a PyErr_SetString(TestError,
2876n/a "test_from_contiguous: incorrect result");
2877n/a return NULL;
2878n/a }
2879n/a }
2880n/a
2881n/a view.buf = &data[8];
2882n/a view.strides[0] = -2 * itemsize;
2883n/a
2884n/a PyBuffer_FromContiguous(&view, init, view.len, 'C');
2885n/a ptr = view.buf;
2886n/a for (i = 0; i < 5; i++) {
2887n/a if (*(ptr-2*i) != i) {
2888n/a PyErr_SetString(TestError,
2889n/a "test_from_contiguous: incorrect result");
2890n/a return NULL;
2891n/a }
2892n/a }
2893n/a
2894n/a Py_RETURN_NONE;
2895n/a}
2896n/a
2897n/a#if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
2898n/aextern PyTypeObject _PyBytesIOBuffer_Type;
2899n/a
2900n/astatic PyObject *
2901n/atest_pep3118_obsolete_write_locks(PyObject* self, PyObject *noargs)
2902n/a{
2903n/a PyTypeObject *type = &_PyBytesIOBuffer_Type;
2904n/a PyObject *b;
2905n/a char *dummy[1];
2906n/a int ret, match;
2907n/a
2908n/a /* PyBuffer_FillInfo() */
2909n/a ret = PyBuffer_FillInfo(NULL, NULL, dummy, 1, 0, PyBUF_SIMPLE);
2910n/a match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
2911n/a PyErr_Clear();
2912n/a if (ret != -1 || match == 0)
2913n/a goto error;
2914n/a
2915n/a /* bytesiobuf_getbuffer() */
2916n/a b = type->tp_alloc(type, 0);
2917n/a if (b == NULL) {
2918n/a return NULL;
2919n/a }
2920n/a
2921n/a ret = PyObject_GetBuffer(b, NULL, PyBUF_SIMPLE);
2922n/a Py_DECREF(b);
2923n/a match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);
2924n/a PyErr_Clear();
2925n/a if (ret != -1 || match == 0)
2926n/a goto error;
2927n/a
2928n/a Py_RETURN_NONE;
2929n/a
2930n/aerror:
2931n/a PyErr_SetString(TestError,
2932n/a "test_pep3118_obsolete_write_locks: failure");
2933n/a return NULL;
2934n/a}
2935n/a#endif
2936n/a
2937n/a/* This tests functions that historically supported write locks. It is
2938n/a wrong to call getbuffer() with view==NULL and a compliant getbufferproc
2939n/a is entitled to segfault in that case. */
2940n/astatic PyObject *
2941n/agetbuffer_with_null_view(PyObject* self, PyObject *obj)
2942n/a{
2943n/a if (PyObject_GetBuffer(obj, NULL, PyBUF_SIMPLE) < 0)
2944n/a return NULL;
2945n/a
2946n/a Py_RETURN_NONE;
2947n/a}
2948n/a
2949n/a/* Test that the fatal error from not having a current thread doesn't
2950n/a cause an infinite loop. Run via Lib/test/test_capi.py */
2951n/astatic PyObject *
2952n/acrash_no_current_thread(PyObject *self)
2953n/a{
2954n/a Py_BEGIN_ALLOW_THREADS
2955n/a /* Using PyThreadState_Get() directly allows the test to pass in
2956n/a !pydebug mode. However, the test only actually tests anything
2957n/a in pydebug mode, since that's where the infinite loop was in
2958n/a the first place. */
2959n/a PyThreadState_Get();
2960n/a Py_END_ALLOW_THREADS
2961n/a return NULL;
2962n/a}
2963n/a
2964n/a/* To run some code in a sub-interpreter. */
2965n/astatic PyObject *
2966n/arun_in_subinterp(PyObject *self, PyObject *args)
2967n/a{
2968n/a const char *code;
2969n/a int r;
2970n/a PyThreadState *substate, *mainstate;
2971n/a
2972n/a if (!PyArg_ParseTuple(args, "s:run_in_subinterp",
2973n/a &code))
2974n/a return NULL;
2975n/a
2976n/a mainstate = PyThreadState_Get();
2977n/a
2978n/a PyThreadState_Swap(NULL);
2979n/a
2980n/a substate = Py_NewInterpreter();
2981n/a if (substate == NULL) {
2982n/a /* Since no new thread state was created, there is no exception to
2983n/a propagate; raise a fresh one after swapping in the old thread
2984n/a state. */
2985n/a PyThreadState_Swap(mainstate);
2986n/a PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
2987n/a return NULL;
2988n/a }
2989n/a r = PyRun_SimpleString(code);
2990n/a Py_EndInterpreter(substate);
2991n/a
2992n/a PyThreadState_Swap(mainstate);
2993n/a
2994n/a return PyLong_FromLong(r);
2995n/a}
2996n/a
2997n/astatic int
2998n/acheck_time_rounding(int round)
2999n/a{
3000n/a if (round != _PyTime_ROUND_FLOOR
3001n/a && round != _PyTime_ROUND_CEILING
3002n/a && round != _PyTime_ROUND_HALF_EVEN) {
3003n/a PyErr_SetString(PyExc_ValueError, "invalid rounding");
3004n/a return -1;
3005n/a }
3006n/a return 0;
3007n/a}
3008n/a
3009n/astatic PyObject *
3010n/atest_pytime_object_to_time_t(PyObject *self, PyObject *args)
3011n/a{
3012n/a PyObject *obj;
3013n/a time_t sec;
3014n/a int round;
3015n/a if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_time_t", &obj, &round))
3016n/a return NULL;
3017n/a if (check_time_rounding(round) < 0)
3018n/a return NULL;
3019n/a if (_PyTime_ObjectToTime_t(obj, &sec, round) == -1)
3020n/a return NULL;
3021n/a return _PyLong_FromTime_t(sec);
3022n/a}
3023n/a
3024n/astatic PyObject *
3025n/atest_pytime_object_to_timeval(PyObject *self, PyObject *args)
3026n/a{
3027n/a PyObject *obj;
3028n/a time_t sec;
3029n/a long usec;
3030n/a int round;
3031n/a if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timeval", &obj, &round))
3032n/a return NULL;
3033n/a if (check_time_rounding(round) < 0)
3034n/a return NULL;
3035n/a if (_PyTime_ObjectToTimeval(obj, &sec, &usec, round) == -1)
3036n/a return NULL;
3037n/a return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), usec);
3038n/a}
3039n/a
3040n/astatic PyObject *
3041n/atest_pytime_object_to_timespec(PyObject *self, PyObject *args)
3042n/a{
3043n/a PyObject *obj;
3044n/a time_t sec;
3045n/a long nsec;
3046n/a int round;
3047n/a if (!PyArg_ParseTuple(args, "Oi:pytime_object_to_timespec", &obj, &round))
3048n/a return NULL;
3049n/a if (check_time_rounding(round) < 0)
3050n/a return NULL;
3051n/a if (_PyTime_ObjectToTimespec(obj, &sec, &nsec, round) == -1)
3052n/a return NULL;
3053n/a return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), nsec);
3054n/a}
3055n/a
3056n/astatic void
3057n/aslot_tp_del(PyObject *self)
3058n/a{
3059n/a _Py_IDENTIFIER(__tp_del__);
3060n/a PyObject *del, *res;
3061n/a PyObject *error_type, *error_value, *error_traceback;
3062n/a
3063n/a /* Temporarily resurrect the object. */
3064n/a assert(self->ob_refcnt == 0);
3065n/a self->ob_refcnt = 1;
3066n/a
3067n/a /* Save the current exception, if any. */
3068n/a PyErr_Fetch(&error_type, &error_value, &error_traceback);
3069n/a
3070n/a /* Execute __del__ method, if any. */
3071n/a del = _PyObject_LookupSpecial(self, &PyId___tp_del__);
3072n/a if (del != NULL) {
3073n/a res = PyEval_CallObject(del, NULL);
3074n/a if (res == NULL)
3075n/a PyErr_WriteUnraisable(del);
3076n/a else
3077n/a Py_DECREF(res);
3078n/a Py_DECREF(del);
3079n/a }
3080n/a
3081n/a /* Restore the saved exception. */
3082n/a PyErr_Restore(error_type, error_value, error_traceback);
3083n/a
3084n/a /* Undo the temporary resurrection; can't use DECREF here, it would
3085n/a * cause a recursive call.
3086n/a */
3087n/a assert(self->ob_refcnt > 0);
3088n/a if (--self->ob_refcnt == 0)
3089n/a return; /* this is the normal path out */
3090n/a
3091n/a /* __del__ resurrected it! Make it look like the original Py_DECREF
3092n/a * never happened.
3093n/a */
3094n/a {
3095n/a Py_ssize_t refcnt = self->ob_refcnt;
3096n/a _Py_NewReference(self);
3097n/a self->ob_refcnt = refcnt;
3098n/a }
3099n/a assert(!PyType_IS_GC(Py_TYPE(self)) ||
3100n/a _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
3101n/a /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
3102n/a * we need to undo that. */
3103n/a _Py_DEC_REFTOTAL;
3104n/a /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3105n/a * chain, so no more to do there.
3106n/a * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3107n/a * _Py_NewReference bumped tp_allocs: both of those need to be
3108n/a * undone.
3109n/a */
3110n/a#ifdef COUNT_ALLOCS
3111n/a --Py_TYPE(self)->tp_frees;
3112n/a --Py_TYPE(self)->tp_allocs;
3113n/a#endif
3114n/a}
3115n/a
3116n/astatic PyObject *
3117n/awith_tp_del(PyObject *self, PyObject *args)
3118n/a{
3119n/a PyObject *obj;
3120n/a PyTypeObject *tp;
3121n/a
3122n/a if (!PyArg_ParseTuple(args, "O:with_tp_del", &obj))
3123n/a return NULL;
3124n/a tp = (PyTypeObject *) obj;
3125n/a if (!PyType_Check(obj) || !PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) {
3126n/a PyErr_Format(PyExc_TypeError,
3127n/a "heap type expected, got %R", obj);
3128n/a return NULL;
3129n/a }
3130n/a tp->tp_del = slot_tp_del;
3131n/a Py_INCREF(obj);
3132n/a return obj;
3133n/a}
3134n/a
3135n/astatic PyMethodDef ml;
3136n/a
3137n/astatic PyObject *
3138n/acreate_cfunction(PyObject *self, PyObject *args)
3139n/a{
3140n/a return PyCFunction_NewEx(&ml, self, NULL);
3141n/a}
3142n/a
3143n/astatic PyMethodDef ml = {
3144n/a "create_cfunction",
3145n/a create_cfunction,
3146n/a METH_NOARGS,
3147n/a NULL
3148n/a};
3149n/a
3150n/astatic PyObject *
3151n/a_test_incref(PyObject *ob)
3152n/a{
3153n/a Py_INCREF(ob);
3154n/a return ob;
3155n/a}
3156n/a
3157n/astatic PyObject *
3158n/atest_xincref_doesnt_leak(PyObject *ob)
3159n/a{
3160n/a PyObject *obj = PyLong_FromLong(0);
3161n/a Py_XINCREF(_test_incref(obj));
3162n/a Py_DECREF(obj);
3163n/a Py_DECREF(obj);
3164n/a Py_DECREF(obj);
3165n/a Py_RETURN_NONE;
3166n/a}
3167n/a
3168n/astatic PyObject *
3169n/atest_incref_doesnt_leak(PyObject *ob)
3170n/a{
3171n/a PyObject *obj = PyLong_FromLong(0);
3172n/a Py_INCREF(_test_incref(obj));
3173n/a Py_DECREF(obj);
3174n/a Py_DECREF(obj);
3175n/a Py_DECREF(obj);
3176n/a Py_RETURN_NONE;
3177n/a}
3178n/a
3179n/astatic PyObject *
3180n/atest_xdecref_doesnt_leak(PyObject *ob)
3181n/a{
3182n/a Py_XDECREF(PyLong_FromLong(0));
3183n/a Py_RETURN_NONE;
3184n/a}
3185n/a
3186n/astatic PyObject *
3187n/atest_decref_doesnt_leak(PyObject *ob)
3188n/a{
3189n/a Py_DECREF(PyLong_FromLong(0));
3190n/a Py_RETURN_NONE;
3191n/a}
3192n/a
3193n/astatic PyObject *
3194n/atest_incref_decref_API(PyObject *ob)
3195n/a{
3196n/a PyObject *obj = PyLong_FromLong(0);
3197n/a Py_IncRef(obj);
3198n/a Py_DecRef(obj);
3199n/a Py_DecRef(obj);
3200n/a Py_RETURN_NONE;
3201n/a}
3202n/a
3203n/astatic PyObject *
3204n/atest_pymem_alloc0(PyObject *self)
3205n/a{
3206n/a void *ptr;
3207n/a
3208n/a ptr = PyMem_RawMalloc(0);
3209n/a if (ptr == NULL) {
3210n/a PyErr_SetString(PyExc_RuntimeError, "PyMem_RawMalloc(0) returns NULL");
3211n/a return NULL;
3212n/a }
3213n/a PyMem_RawFree(ptr);
3214n/a
3215n/a ptr = PyMem_RawCalloc(0, 0);
3216n/a if (ptr == NULL) {
3217n/a PyErr_SetString(PyExc_RuntimeError, "PyMem_RawCalloc(0, 0) returns NULL");
3218n/a return NULL;
3219n/a }
3220n/a PyMem_RawFree(ptr);
3221n/a
3222n/a ptr = PyMem_Malloc(0);
3223n/a if (ptr == NULL) {
3224n/a PyErr_SetString(PyExc_RuntimeError, "PyMem_Malloc(0) returns NULL");
3225n/a return NULL;
3226n/a }
3227n/a PyMem_Free(ptr);
3228n/a
3229n/a ptr = PyMem_Calloc(0, 0);
3230n/a if (ptr == NULL) {
3231n/a PyErr_SetString(PyExc_RuntimeError, "PyMem_Calloc(0, 0) returns NULL");
3232n/a return NULL;
3233n/a }
3234n/a PyMem_Free(ptr);
3235n/a
3236n/a ptr = PyObject_Malloc(0);
3237n/a if (ptr == NULL) {
3238n/a PyErr_SetString(PyExc_RuntimeError, "PyObject_Malloc(0) returns NULL");
3239n/a return NULL;
3240n/a }
3241n/a PyObject_Free(ptr);
3242n/a
3243n/a ptr = PyObject_Calloc(0, 0);
3244n/a if (ptr == NULL) {
3245n/a PyErr_SetString(PyExc_RuntimeError, "PyObject_Calloc(0, 0) returns NULL");
3246n/a return NULL;
3247n/a }
3248n/a PyObject_Free(ptr);
3249n/a
3250n/a Py_RETURN_NONE;
3251n/a}
3252n/a
3253n/atypedef struct {
3254n/a PyMemAllocatorEx alloc;
3255n/a
3256n/a size_t malloc_size;
3257n/a size_t calloc_nelem;
3258n/a size_t calloc_elsize;
3259n/a void *realloc_ptr;
3260n/a size_t realloc_new_size;
3261n/a void *free_ptr;
3262n/a} alloc_hook_t;
3263n/a
3264n/astatic void* hook_malloc (void* ctx, size_t size)
3265n/a{
3266n/a alloc_hook_t *hook = (alloc_hook_t *)ctx;
3267n/a hook->malloc_size = size;
3268n/a return hook->alloc.malloc(hook->alloc.ctx, size);
3269n/a}
3270n/a
3271n/astatic void* hook_calloc (void* ctx, size_t nelem, size_t elsize)
3272n/a{
3273n/a alloc_hook_t *hook = (alloc_hook_t *)ctx;
3274n/a hook->calloc_nelem = nelem;
3275n/a hook->calloc_elsize = elsize;
3276n/a return hook->alloc.calloc(hook->alloc.ctx, nelem, elsize);
3277n/a}
3278n/a
3279n/astatic void* hook_realloc (void* ctx, void* ptr, size_t new_size)
3280n/a{
3281n/a alloc_hook_t *hook = (alloc_hook_t *)ctx;
3282n/a hook->realloc_ptr = ptr;
3283n/a hook->realloc_new_size = new_size;
3284n/a return hook->alloc.realloc(hook->alloc.ctx, ptr, new_size);
3285n/a}
3286n/a
3287n/astatic void hook_free (void *ctx, void *ptr)
3288n/a{
3289n/a alloc_hook_t *hook = (alloc_hook_t *)ctx;
3290n/a hook->free_ptr = ptr;
3291n/a hook->alloc.free(hook->alloc.ctx, ptr);
3292n/a}
3293n/a
3294n/astatic PyObject *
3295n/atest_setallocators(PyMemAllocatorDomain domain)
3296n/a{
3297n/a PyObject *res = NULL;
3298n/a const char *error_msg;
3299n/a alloc_hook_t hook;
3300n/a PyMemAllocatorEx alloc;
3301n/a size_t size, size2, nelem, elsize;
3302n/a void *ptr, *ptr2;
3303n/a
3304n/a memset(&hook, 0, sizeof(hook));
3305n/a
3306n/a alloc.ctx = &hook;
3307n/a alloc.malloc = &hook_malloc;
3308n/a alloc.calloc = &hook_calloc;
3309n/a alloc.realloc = &hook_realloc;
3310n/a alloc.free = &hook_free;
3311n/a PyMem_GetAllocator(domain, &hook.alloc);
3312n/a PyMem_SetAllocator(domain, &alloc);
3313n/a
3314n/a size = 42;
3315n/a switch(domain)
3316n/a {
3317n/a case PYMEM_DOMAIN_RAW: ptr = PyMem_RawMalloc(size); break;
3318n/a case PYMEM_DOMAIN_MEM: ptr = PyMem_Malloc(size); break;
3319n/a case PYMEM_DOMAIN_OBJ: ptr = PyObject_Malloc(size); break;
3320n/a default: ptr = NULL; break;
3321n/a }
3322n/a
3323n/a if (ptr == NULL) {
3324n/a error_msg = "malloc failed";
3325n/a goto fail;
3326n/a }
3327n/a
3328n/a if (hook.malloc_size != size) {
3329n/a error_msg = "malloc invalid size";
3330n/a goto fail;
3331n/a }
3332n/a
3333n/a size2 = 200;
3334n/a switch(domain)
3335n/a {
3336n/a case PYMEM_DOMAIN_RAW: ptr2 = PyMem_RawRealloc(ptr, size2); break;
3337n/a case PYMEM_DOMAIN_MEM: ptr2 = PyMem_Realloc(ptr, size2); break;
3338n/a case PYMEM_DOMAIN_OBJ: ptr2 = PyObject_Realloc(ptr, size2); break;
3339n/a default: ptr2 = NULL; break;
3340n/a }
3341n/a
3342n/a if (ptr2 == NULL) {
3343n/a error_msg = "realloc failed";
3344n/a goto fail;
3345n/a }
3346n/a
3347n/a if (hook.realloc_ptr != ptr
3348n/a || hook.realloc_new_size != size2) {
3349n/a error_msg = "realloc invalid parameters";
3350n/a goto fail;
3351n/a }
3352n/a
3353n/a switch(domain)
3354n/a {
3355n/a case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr2); break;
3356n/a case PYMEM_DOMAIN_MEM: PyMem_Free(ptr2); break;
3357n/a case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr2); break;
3358n/a }
3359n/a
3360n/a if (hook.free_ptr != ptr2) {
3361n/a error_msg = "free invalid pointer";
3362n/a goto fail;
3363n/a }
3364n/a
3365n/a nelem = 2;
3366n/a elsize = 5;
3367n/a switch(domain)
3368n/a {
3369n/a case PYMEM_DOMAIN_RAW: ptr = PyMem_RawCalloc(nelem, elsize); break;
3370n/a case PYMEM_DOMAIN_MEM: ptr = PyMem_Calloc(nelem, elsize); break;
3371n/a case PYMEM_DOMAIN_OBJ: ptr = PyObject_Calloc(nelem, elsize); break;
3372n/a default: ptr = NULL; break;
3373n/a }
3374n/a
3375n/a if (ptr == NULL) {
3376n/a error_msg = "calloc failed";
3377n/a goto fail;
3378n/a }
3379n/a
3380n/a if (hook.calloc_nelem != nelem || hook.calloc_elsize != elsize) {
3381n/a error_msg = "calloc invalid nelem or elsize";
3382n/a goto fail;
3383n/a }
3384n/a
3385n/a switch(domain)
3386n/a {
3387n/a case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr); break;
3388n/a case PYMEM_DOMAIN_MEM: PyMem_Free(ptr); break;
3389n/a case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr); break;
3390n/a }
3391n/a
3392n/a Py_INCREF(Py_None);
3393n/a res = Py_None;
3394n/a goto finally;
3395n/a
3396n/afail:
3397n/a PyErr_SetString(PyExc_RuntimeError, error_msg);
3398n/a
3399n/afinally:
3400n/a PyMem_SetAllocator(domain, &hook.alloc);
3401n/a return res;
3402n/a}
3403n/a
3404n/astatic PyObject *
3405n/atest_pymem_setrawallocators(PyObject *self)
3406n/a{
3407n/a return test_setallocators(PYMEM_DOMAIN_RAW);
3408n/a}
3409n/a
3410n/astatic PyObject *
3411n/atest_pymem_setallocators(PyObject *self)
3412n/a{
3413n/a return test_setallocators(PYMEM_DOMAIN_MEM);
3414n/a}
3415n/a
3416n/astatic PyObject *
3417n/atest_pyobject_setallocators(PyObject *self)
3418n/a{
3419n/a return test_setallocators(PYMEM_DOMAIN_OBJ);
3420n/a}
3421n/a
3422n/aPyDoc_STRVAR(docstring_empty,
3423n/a""
3424n/a);
3425n/a
3426n/aPyDoc_STRVAR(docstring_no_signature,
3427n/a"This docstring has no signature."
3428n/a);
3429n/a
3430n/aPyDoc_STRVAR(docstring_with_invalid_signature,
3431n/a"docstring_with_invalid_signature($module, /, boo)\n"
3432n/a"\n"
3433n/a"This docstring has an invalid signature."
3434n/a);
3435n/a
3436n/aPyDoc_STRVAR(docstring_with_invalid_signature2,
3437n/a"docstring_with_invalid_signature2($module, /, boo)\n"
3438n/a"\n"
3439n/a"--\n"
3440n/a"\n"
3441n/a"This docstring also has an invalid signature."
3442n/a);
3443n/a
3444n/aPyDoc_STRVAR(docstring_with_signature,
3445n/a"docstring_with_signature($module, /, sig)\n"
3446n/a"--\n"
3447n/a"\n"
3448n/a"This docstring has a valid signature."
3449n/a);
3450n/a
3451n/aPyDoc_STRVAR(docstring_with_signature_but_no_doc,
3452n/a"docstring_with_signature_but_no_doc($module, /, sig)\n"
3453n/a"--\n"
3454n/a"\n"
3455n/a);
3456n/a
3457n/aPyDoc_STRVAR(docstring_with_signature_and_extra_newlines,
3458n/a"docstring_with_signature_and_extra_newlines($module, /, parameter)\n"
3459n/a"--\n"
3460n/a"\n"
3461n/a"\n"
3462n/a"This docstring has a valid signature and some extra newlines."
3463n/a);
3464n/a
3465n/aPyDoc_STRVAR(docstring_with_signature_with_defaults,
3466n/a"docstring_with_signature_with_defaults(module, s='avocado',\n"
3467n/a" b=b'bytes', d=3.14, i=35, n=None, t=True, f=False,\n"
3468n/a" local=the_number_three, sys=sys.maxsize,\n"
3469n/a" exp=sys.maxsize - 1)\n"
3470n/a"--\n"
3471n/a"\n"
3472n/a"\n"
3473n/a"\n"
3474n/a"This docstring has a valid signature with parameters,\n"
3475n/a"and the parameters take defaults of varying types."
3476n/a);
3477n/a
3478n/a#ifdef WITH_THREAD
3479n/atypedef struct {
3480n/a PyThread_type_lock start_event;
3481n/a PyThread_type_lock exit_event;
3482n/a PyObject *callback;
3483n/a} test_c_thread_t;
3484n/a
3485n/astatic void
3486n/atemporary_c_thread(void *data)
3487n/a{
3488n/a test_c_thread_t *test_c_thread = data;
3489n/a PyGILState_STATE state;
3490n/a PyObject *res;
3491n/a
3492n/a PyThread_release_lock(test_c_thread->start_event);
3493n/a
3494n/a /* Allocate a Python thread state for this thread */
3495n/a state = PyGILState_Ensure();
3496n/a
3497n/a res = _PyObject_CallNoArg(test_c_thread->callback);
3498n/a Py_CLEAR(test_c_thread->callback);
3499n/a
3500n/a if (res == NULL) {
3501n/a PyErr_Print();
3502n/a }
3503n/a else {
3504n/a Py_DECREF(res);
3505n/a }
3506n/a
3507n/a /* Destroy the Python thread state for this thread */
3508n/a PyGILState_Release(state);
3509n/a
3510n/a PyThread_release_lock(test_c_thread->exit_event);
3511n/a
3512n/a PyThread_exit_thread();
3513n/a}
3514n/a
3515n/astatic PyObject *
3516n/acall_in_temporary_c_thread(PyObject *self, PyObject *callback)
3517n/a{
3518n/a PyObject *res = NULL;
3519n/a test_c_thread_t test_c_thread;
3520n/a long thread;
3521n/a
3522n/a PyEval_InitThreads();
3523n/a
3524n/a test_c_thread.start_event = PyThread_allocate_lock();
3525n/a test_c_thread.exit_event = PyThread_allocate_lock();
3526n/a test_c_thread.callback = NULL;
3527n/a if (!test_c_thread.start_event || !test_c_thread.exit_event) {
3528n/a PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
3529n/a goto exit;
3530n/a }
3531n/a
3532n/a Py_INCREF(callback);
3533n/a test_c_thread.callback = callback;
3534n/a
3535n/a PyThread_acquire_lock(test_c_thread.start_event, 1);
3536n/a PyThread_acquire_lock(test_c_thread.exit_event, 1);
3537n/a
3538n/a thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
3539n/a if (thread == -1) {
3540n/a PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
3541n/a PyThread_release_lock(test_c_thread.start_event);
3542n/a PyThread_release_lock(test_c_thread.exit_event);
3543n/a goto exit;
3544n/a }
3545n/a
3546n/a PyThread_acquire_lock(test_c_thread.start_event, 1);
3547n/a PyThread_release_lock(test_c_thread.start_event);
3548n/a
3549n/a Py_BEGIN_ALLOW_THREADS
3550n/a PyThread_acquire_lock(test_c_thread.exit_event, 1);
3551n/a PyThread_release_lock(test_c_thread.exit_event);
3552n/a Py_END_ALLOW_THREADS
3553n/a
3554n/a Py_INCREF(Py_None);
3555n/a res = Py_None;
3556n/a
3557n/aexit:
3558n/a Py_CLEAR(test_c_thread.callback);
3559n/a if (test_c_thread.start_event)
3560n/a PyThread_free_lock(test_c_thread.start_event);
3561n/a if (test_c_thread.exit_event)
3562n/a PyThread_free_lock(test_c_thread.exit_event);
3563n/a return res;
3564n/a}
3565n/a#endif /* WITH_THREAD */
3566n/a
3567n/astatic PyObject*
3568n/atest_raise_signal(PyObject* self, PyObject *args)
3569n/a{
3570n/a int signum, err;
3571n/a
3572n/a if (PyArg_ParseTuple(args, "i:raise_signal", &signum) < 0)
3573n/a return NULL;
3574n/a
3575n/a err = raise(signum);
3576n/a if (err)
3577n/a return PyErr_SetFromErrno(PyExc_OSError);
3578n/a
3579n/a if (PyErr_CheckSignals() < 0)
3580n/a return NULL;
3581n/a
3582n/a Py_RETURN_NONE;
3583n/a}
3584n/a
3585n/a/* marshal */
3586n/a
3587n/astatic PyObject*
3588n/apymarshal_write_long_to_file(PyObject* self, PyObject *args)
3589n/a{
3590n/a long value;
3591n/a char *filename;
3592n/a int version;
3593n/a FILE *fp;
3594n/a
3595n/a if (!PyArg_ParseTuple(args, "lsi:pymarshal_write_long_to_file",
3596n/a &value, &filename, &version))
3597n/a return NULL;
3598n/a
3599n/a fp = fopen(filename, "wb");
3600n/a if (fp == NULL) {
3601n/a PyErr_SetFromErrno(PyExc_OSError);
3602n/a return NULL;
3603n/a }
3604n/a
3605n/a PyMarshal_WriteLongToFile(value, fp, version);
3606n/a
3607n/a fclose(fp);
3608n/a if (PyErr_Occurred())
3609n/a return NULL;
3610n/a Py_RETURN_NONE;
3611n/a}
3612n/a
3613n/astatic PyObject*
3614n/apymarshal_write_object_to_file(PyObject* self, PyObject *args)
3615n/a{
3616n/a PyObject *obj;
3617n/a char *filename;
3618n/a int version;
3619n/a FILE *fp;
3620n/a
3621n/a if (!PyArg_ParseTuple(args, "Osi:pymarshal_write_object_to_file",
3622n/a &obj, &filename, &version))
3623n/a return NULL;
3624n/a
3625n/a fp = fopen(filename, "wb");
3626n/a if (fp == NULL) {
3627n/a PyErr_SetFromErrno(PyExc_OSError);
3628n/a return NULL;
3629n/a }
3630n/a
3631n/a PyMarshal_WriteObjectToFile(obj, fp, version);
3632n/a
3633n/a fclose(fp);
3634n/a if (PyErr_Occurred())
3635n/a return NULL;
3636n/a Py_RETURN_NONE;
3637n/a}
3638n/a
3639n/astatic PyObject*
3640n/apymarshal_read_short_from_file(PyObject* self, PyObject *args)
3641n/a{
3642n/a int value;
3643n/a long pos;
3644n/a char *filename;
3645n/a FILE *fp;
3646n/a
3647n/a if (!PyArg_ParseTuple(args, "s:pymarshal_read_short_from_file", &filename))
3648n/a return NULL;
3649n/a
3650n/a fp = fopen(filename, "rb");
3651n/a if (fp == NULL) {
3652n/a PyErr_SetFromErrno(PyExc_OSError);
3653n/a return NULL;
3654n/a }
3655n/a
3656n/a value = PyMarshal_ReadShortFromFile(fp);
3657n/a pos = ftell(fp);
3658n/a
3659n/a fclose(fp);
3660n/a if (PyErr_Occurred())
3661n/a return NULL;
3662n/a return Py_BuildValue("il", value, pos);
3663n/a}
3664n/a
3665n/astatic PyObject*
3666n/apymarshal_read_long_from_file(PyObject* self, PyObject *args)
3667n/a{
3668n/a long value, pos;
3669n/a char *filename;
3670n/a FILE *fp;
3671n/a
3672n/a if (!PyArg_ParseTuple(args, "s:pymarshal_read_long_from_file", &filename))
3673n/a return NULL;
3674n/a
3675n/a fp = fopen(filename, "rb");
3676n/a if (fp == NULL) {
3677n/a PyErr_SetFromErrno(PyExc_OSError);
3678n/a return NULL;
3679n/a }
3680n/a
3681n/a value = PyMarshal_ReadLongFromFile(fp);
3682n/a pos = ftell(fp);
3683n/a
3684n/a fclose(fp);
3685n/a if (PyErr_Occurred())
3686n/a return NULL;
3687n/a return Py_BuildValue("ll", value, pos);
3688n/a}
3689n/a
3690n/astatic PyObject*
3691n/apymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
3692n/a{
3693n/a PyObject *obj;
3694n/a long pos;
3695n/a char *filename;
3696n/a FILE *fp;
3697n/a
3698n/a if (!PyArg_ParseTuple(args, "s:pymarshal_read_last_object_from_file", &filename))
3699n/a return NULL;
3700n/a
3701n/a fp = fopen(filename, "rb");
3702n/a if (fp == NULL) {
3703n/a PyErr_SetFromErrno(PyExc_OSError);
3704n/a return NULL;
3705n/a }
3706n/a
3707n/a obj = PyMarshal_ReadLastObjectFromFile(fp);
3708n/a pos = ftell(fp);
3709n/a
3710n/a fclose(fp);
3711n/a return Py_BuildValue("Nl", obj, pos);
3712n/a}
3713n/a
3714n/astatic PyObject*
3715n/apymarshal_read_object_from_file(PyObject* self, PyObject *args)
3716n/a{
3717n/a PyObject *obj;
3718n/a long pos;
3719n/a char *filename;
3720n/a FILE *fp;
3721n/a
3722n/a if (!PyArg_ParseTuple(args, "s:pymarshal_read_object_from_file", &filename))
3723n/a return NULL;
3724n/a
3725n/a fp = fopen(filename, "rb");
3726n/a if (fp == NULL) {
3727n/a PyErr_SetFromErrno(PyExc_OSError);
3728n/a return NULL;
3729n/a }
3730n/a
3731n/a obj = PyMarshal_ReadObjectFromFile(fp);
3732n/a pos = ftell(fp);
3733n/a
3734n/a fclose(fp);
3735n/a return Py_BuildValue("Nl", obj, pos);
3736n/a}
3737n/a
3738n/astatic PyObject*
3739n/areturn_null_without_error(PyObject *self, PyObject *args)
3740n/a{
3741n/a /* invalid call: return NULL without setting an error,
3742n/a * _Py_CheckFunctionResult() must detect such bug at runtime. */
3743n/a PyErr_Clear();
3744n/a return NULL;
3745n/a}
3746n/a
3747n/astatic PyObject*
3748n/areturn_result_with_error(PyObject *self, PyObject *args)
3749n/a{
3750n/a /* invalid call: return a result with an error set,
3751n/a * _Py_CheckFunctionResult() must detect such bug at runtime. */
3752n/a PyErr_SetNone(PyExc_ValueError);
3753n/a Py_RETURN_NONE;
3754n/a}
3755n/a
3756n/astatic PyObject *
3757n/atest_pytime_fromseconds(PyObject *self, PyObject *args)
3758n/a{
3759n/a int seconds;
3760n/a _PyTime_t ts;
3761n/a
3762n/a if (!PyArg_ParseTuple(args, "i", &seconds))
3763n/a return NULL;
3764n/a ts = _PyTime_FromSeconds(seconds);
3765n/a return _PyTime_AsNanosecondsObject(ts);
3766n/a}
3767n/a
3768n/astatic PyObject *
3769n/atest_pytime_fromsecondsobject(PyObject *self, PyObject *args)
3770n/a{
3771n/a PyObject *obj;
3772n/a int round;
3773n/a _PyTime_t ts;
3774n/a
3775n/a if (!PyArg_ParseTuple(args, "Oi", &obj, &round))
3776n/a return NULL;
3777n/a if (check_time_rounding(round) < 0)
3778n/a return NULL;
3779n/a if (_PyTime_FromSecondsObject(&ts, obj, round) == -1)
3780n/a return NULL;
3781n/a return _PyTime_AsNanosecondsObject(ts);
3782n/a}
3783n/a
3784n/astatic PyObject *
3785n/atest_pytime_assecondsdouble(PyObject *self, PyObject *args)
3786n/a{
3787n/a long long ns;
3788n/a _PyTime_t ts;
3789n/a double d;
3790n/a
3791n/a if (!PyArg_ParseTuple(args, "L", &ns))
3792n/a return NULL;
3793n/a ts = _PyTime_FromNanoseconds(ns);
3794n/a d = _PyTime_AsSecondsDouble(ts);
3795n/a return PyFloat_FromDouble(d);
3796n/a}
3797n/a
3798n/astatic PyObject *
3799n/atest_PyTime_AsTimeval(PyObject *self, PyObject *args)
3800n/a{
3801n/a long long ns;
3802n/a int round;
3803n/a _PyTime_t t;
3804n/a struct timeval tv;
3805n/a PyObject *seconds;
3806n/a
3807n/a if (!PyArg_ParseTuple(args, "Li", &ns, &round))
3808n/a return NULL;
3809n/a if (check_time_rounding(round) < 0)
3810n/a return NULL;
3811n/a t = _PyTime_FromNanoseconds(ns);
3812n/a if (_PyTime_AsTimeval(t, &tv, round) < 0)
3813n/a return NULL;
3814n/a
3815n/a seconds = PyLong_FromLong((long long)tv.tv_sec);
3816n/a if (seconds == NULL)
3817n/a return NULL;
3818n/a return Py_BuildValue("Nl", seconds, tv.tv_usec);
3819n/a}
3820n/a
3821n/a#ifdef HAVE_CLOCK_GETTIME
3822n/astatic PyObject *
3823n/atest_PyTime_AsTimespec(PyObject *self, PyObject *args)
3824n/a{
3825n/a long long ns;
3826n/a _PyTime_t t;
3827n/a struct timespec ts;
3828n/a
3829n/a if (!PyArg_ParseTuple(args, "L", &ns))
3830n/a return NULL;
3831n/a t = _PyTime_FromNanoseconds(ns);
3832n/a if (_PyTime_AsTimespec(t, &ts) == -1)
3833n/a return NULL;
3834n/a return Py_BuildValue("Nl", _PyLong_FromTime_t(ts.tv_sec), ts.tv_nsec);
3835n/a}
3836n/a#endif
3837n/a
3838n/astatic PyObject *
3839n/atest_PyTime_AsMilliseconds(PyObject *self, PyObject *args)
3840n/a{
3841n/a long long ns;
3842n/a int round;
3843n/a _PyTime_t t, ms;
3844n/a
3845n/a if (!PyArg_ParseTuple(args, "Li", &ns, &round))
3846n/a return NULL;
3847n/a if (check_time_rounding(round) < 0)
3848n/a return NULL;
3849n/a t = _PyTime_FromNanoseconds(ns);
3850n/a ms = _PyTime_AsMilliseconds(t, round);
3851n/a /* This conversion rely on the fact that _PyTime_t is a number of
3852n/a nanoseconds */
3853n/a return _PyTime_AsNanosecondsObject(ms);
3854n/a}
3855n/a
3856n/astatic PyObject *
3857n/atest_PyTime_AsMicroseconds(PyObject *self, PyObject *args)
3858n/a{
3859n/a long long ns;
3860n/a int round;
3861n/a _PyTime_t t, ms;
3862n/a
3863n/a if (!PyArg_ParseTuple(args, "Li", &ns, &round))
3864n/a return NULL;
3865n/a if (check_time_rounding(round) < 0)
3866n/a return NULL;
3867n/a t = _PyTime_FromNanoseconds(ns);
3868n/a ms = _PyTime_AsMicroseconds(t, round);
3869n/a /* This conversion rely on the fact that _PyTime_t is a number of
3870n/a nanoseconds */
3871n/a return _PyTime_AsNanosecondsObject(ms);
3872n/a}
3873n/a
3874n/astatic PyObject*
3875n/aget_recursion_depth(PyObject *self, PyObject *args)
3876n/a{
3877n/a PyThreadState *tstate = PyThreadState_GET();
3878n/a
3879n/a /* subtract one to ignore the frame of the get_recursion_depth() call */
3880n/a return PyLong_FromLong(tstate->recursion_depth - 1);
3881n/a}
3882n/a
3883n/astatic PyObject*
3884n/apymem_buffer_overflow(PyObject *self, PyObject *args)
3885n/a{
3886n/a char *buffer;
3887n/a
3888n/a /* Deliberate buffer overflow to check that PyMem_Free() detects
3889n/a the overflow when debug hooks are installed. */
3890n/a buffer = PyMem_Malloc(16);
3891n/a buffer[16] = 'x';
3892n/a PyMem_Free(buffer);
3893n/a
3894n/a Py_RETURN_NONE;
3895n/a}
3896n/a
3897n/astatic PyObject*
3898n/apymem_api_misuse(PyObject *self, PyObject *args)
3899n/a{
3900n/a char *buffer;
3901n/a
3902n/a /* Deliberate misusage of Python allocators:
3903n/a allococate with PyMem but release with PyMem_Raw. */
3904n/a buffer = PyMem_Malloc(16);
3905n/a PyMem_RawFree(buffer);
3906n/a
3907n/a Py_RETURN_NONE;
3908n/a}
3909n/a
3910n/astatic PyObject*
3911n/apymem_malloc_without_gil(PyObject *self, PyObject *args)
3912n/a{
3913n/a char *buffer;
3914n/a
3915n/a /* Deliberate bug to test debug hooks on Python memory allocators:
3916n/a call PyMem_Malloc() without holding the GIL */
3917n/a Py_BEGIN_ALLOW_THREADS
3918n/a buffer = PyMem_Malloc(10);
3919n/a Py_END_ALLOW_THREADS
3920n/a
3921n/a PyMem_Free(buffer);
3922n/a
3923n/a Py_RETURN_NONE;
3924n/a}
3925n/a
3926n/astatic PyObject*
3927n/apyobject_malloc_without_gil(PyObject *self, PyObject *args)
3928n/a{
3929n/a char *buffer;
3930n/a
3931n/a /* Deliberate bug to test debug hooks on Python memory allocators:
3932n/a call PyObject_Malloc() without holding the GIL */
3933n/a Py_BEGIN_ALLOW_THREADS
3934n/a buffer = PyObject_Malloc(10);
3935n/a Py_END_ALLOW_THREADS
3936n/a
3937n/a PyObject_Free(buffer);
3938n/a
3939n/a Py_RETURN_NONE;
3940n/a}
3941n/a
3942n/astatic PyObject *
3943n/atracemalloc_track(PyObject *self, PyObject *args)
3944n/a{
3945n/a unsigned int domain;
3946n/a PyObject *ptr_obj;
3947n/a void *ptr;
3948n/a Py_ssize_t size;
3949n/a int release_gil = 0;
3950n/a int res;
3951n/a
3952n/a if (!PyArg_ParseTuple(args, "IOn|i", &domain, &ptr_obj, &size, &release_gil))
3953n/a return NULL;
3954n/a ptr = PyLong_AsVoidPtr(ptr_obj);
3955n/a if (PyErr_Occurred())
3956n/a return NULL;
3957n/a
3958n/a if (release_gil) {
3959n/a Py_BEGIN_ALLOW_THREADS
3960n/a res = _PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
3961n/a Py_END_ALLOW_THREADS
3962n/a }
3963n/a else {
3964n/a res = _PyTraceMalloc_Track(domain, (uintptr_t)ptr, size);
3965n/a }
3966n/a
3967n/a if (res < 0) {
3968n/a PyErr_SetString(PyExc_RuntimeError, "_PyTraceMalloc_Track error");
3969n/a return NULL;
3970n/a }
3971n/a
3972n/a Py_RETURN_NONE;
3973n/a}
3974n/a
3975n/astatic PyObject *
3976n/atracemalloc_untrack(PyObject *self, PyObject *args)
3977n/a{
3978n/a unsigned int domain;
3979n/a PyObject *ptr_obj;
3980n/a void *ptr;
3981n/a int res;
3982n/a
3983n/a if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
3984n/a return NULL;
3985n/a ptr = PyLong_AsVoidPtr(ptr_obj);
3986n/a if (PyErr_Occurred())
3987n/a return NULL;
3988n/a
3989n/a res = _PyTraceMalloc_Untrack(domain, (uintptr_t)ptr);
3990n/a if (res < 0) {
3991n/a PyErr_SetString(PyExc_RuntimeError, "_PyTraceMalloc_Track error");
3992n/a return NULL;
3993n/a }
3994n/a
3995n/a Py_RETURN_NONE;
3996n/a}
3997n/a
3998n/astatic PyObject *
3999n/atracemalloc_get_traceback(PyObject *self, PyObject *args)
4000n/a{
4001n/a unsigned int domain;
4002n/a PyObject *ptr_obj;
4003n/a void *ptr;
4004n/a
4005n/a if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj))
4006n/a return NULL;
4007n/a ptr = PyLong_AsVoidPtr(ptr_obj);
4008n/a if (PyErr_Occurred())
4009n/a return NULL;
4010n/a
4011n/a return _PyTraceMalloc_GetTraceback(domain, (uintptr_t)ptr);
4012n/a}
4013n/a
4014n/astatic PyObject *
4015n/adict_get_version(PyObject *self, PyObject *args)
4016n/a{
4017n/a PyDictObject *dict;
4018n/a uint64_t version;
4019n/a
4020n/a if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
4021n/a return NULL;
4022n/a
4023n/a version = dict->ma_version_tag;
4024n/a
4025n/a Py_BUILD_ASSERT(sizeof(unsigned PY_LONG_LONG) >= sizeof(version));
4026n/a return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)version);
4027n/a}
4028n/a
4029n/a
4030n/astatic PyMethodDef TestMethods[] = {
4031n/a {"raise_exception", raise_exception, METH_VARARGS},
4032n/a {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS},
4033n/a {"set_errno", set_errno, METH_VARARGS},
4034n/a {"test_config", (PyCFunction)test_config, METH_NOARGS},
4035n/a {"test_sizeof_c_types", (PyCFunction)test_sizeof_c_types, METH_NOARGS},
4036n/a {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
4037n/a {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
4038n/a {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
4039n/a {"dict_getitem_knownhash", dict_getitem_knownhash, METH_VARARGS},
4040n/a {"dict_hassplittable", dict_hassplittable, METH_O},
4041n/a {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
4042n/a {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
4043n/a {"test_xincref_doesnt_leak",(PyCFunction)test_xincref_doesnt_leak, METH_NOARGS},
4044n/a {"test_incref_doesnt_leak", (PyCFunction)test_incref_doesnt_leak, METH_NOARGS},
4045n/a {"test_xdecref_doesnt_leak",(PyCFunction)test_xdecref_doesnt_leak, METH_NOARGS},
4046n/a {"test_decref_doesnt_leak", (PyCFunction)test_decref_doesnt_leak, METH_NOARGS},
4047n/a {"test_incref_decref_API", (PyCFunction)test_incref_decref_API, METH_NOARGS},
4048n/a {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
4049n/a METH_NOARGS},
4050n/a {"test_long_as_double", (PyCFunction)test_long_as_double,METH_NOARGS},
4051n/a {"test_long_as_size_t", (PyCFunction)test_long_as_size_t,METH_NOARGS},
4052n/a {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
4053n/a {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
4054n/a {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
4055n/a {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS},
4056n/a {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
4057n/a {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
4058n/a {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
4059n/a PyDoc_STR("This is a pretty normal docstring.")},
4060n/a {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS},
4061n/a {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS},
4062n/a {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
4063n/a {"test_from_contiguous", (PyCFunction)test_from_contiguous, METH_NOARGS},
4064n/a#if (defined(__linux__) || defined(__FreeBSD__)) && defined(__GNUC__)
4065n/a {"test_pep3118_obsolete_write_locks", (PyCFunction)test_pep3118_obsolete_write_locks, METH_NOARGS},
4066n/a#endif
4067n/a {"getbuffer_with_null_view", getbuffer_with_null_view, METH_O},
4068n/a {"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
4069n/a {"get_args", get_args, METH_VARARGS},
4070n/a {"get_kwargs", (PyCFunction)get_kwargs, METH_VARARGS|METH_KEYWORDS},
4071n/a {"getargs_tuple", getargs_tuple, METH_VARARGS},
4072n/a {"getargs_keywords", (PyCFunction)getargs_keywords,
4073n/a METH_VARARGS|METH_KEYWORDS},
4074n/a {"getargs_keyword_only", (PyCFunction)getargs_keyword_only,
4075n/a METH_VARARGS|METH_KEYWORDS},
4076n/a {"getargs_positional_only_and_keywords",
4077n/a (PyCFunction)getargs_positional_only_and_keywords,
4078n/a METH_VARARGS|METH_KEYWORDS},
4079n/a {"getargs_b", getargs_b, METH_VARARGS},
4080n/a {"getargs_B", getargs_B, METH_VARARGS},
4081n/a {"getargs_h", getargs_h, METH_VARARGS},
4082n/a {"getargs_H", getargs_H, METH_VARARGS},
4083n/a {"getargs_I", getargs_I, METH_VARARGS},
4084n/a {"getargs_k", getargs_k, METH_VARARGS},
4085n/a {"getargs_i", getargs_i, METH_VARARGS},
4086n/a {"getargs_l", getargs_l, METH_VARARGS},
4087n/a {"getargs_n", getargs_n, METH_VARARGS},
4088n/a {"getargs_p", getargs_p, METH_VARARGS},
4089n/a {"getargs_L", getargs_L, METH_VARARGS},
4090n/a {"getargs_K", getargs_K, METH_VARARGS},
4091n/a {"test_longlong_api", test_longlong_api, METH_NOARGS},
4092n/a {"test_long_long_and_overflow",
4093n/a (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
4094n/a {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
4095n/a {"getargs_f", getargs_f, METH_VARARGS},
4096n/a {"getargs_d", getargs_d, METH_VARARGS},
4097n/a {"getargs_D", getargs_D, METH_VARARGS},
4098n/a {"getargs_S", getargs_S, METH_VARARGS},
4099n/a {"getargs_Y", getargs_Y, METH_VARARGS},
4100n/a {"getargs_U", getargs_U, METH_VARARGS},
4101n/a {"getargs_c", getargs_c, METH_VARARGS},
4102n/a {"getargs_C", getargs_C, METH_VARARGS},
4103n/a {"getargs_s", getargs_s, METH_VARARGS},
4104n/a {"getargs_s_star", getargs_s_star, METH_VARARGS},
4105n/a {"getargs_s_hash", getargs_s_hash, METH_VARARGS},
4106n/a {"getargs_z", getargs_z, METH_VARARGS},
4107n/a {"getargs_z_star", getargs_z_star, METH_VARARGS},
4108n/a {"getargs_z_hash", getargs_z_hash, METH_VARARGS},
4109n/a {"getargs_y", getargs_y, METH_VARARGS},
4110n/a {"getargs_y_star", getargs_y_star, METH_VARARGS},
4111n/a {"getargs_y_hash", getargs_y_hash, METH_VARARGS},
4112n/a {"getargs_u", getargs_u, METH_VARARGS},
4113n/a {"getargs_u_hash", getargs_u_hash, METH_VARARGS},
4114n/a {"getargs_Z", getargs_Z, METH_VARARGS},
4115n/a {"getargs_Z_hash", getargs_Z_hash, METH_VARARGS},
4116n/a {"getargs_w_star", getargs_w_star, METH_VARARGS},
4117n/a {"getargs_es", getargs_es, METH_VARARGS},
4118n/a {"getargs_et", getargs_et, METH_VARARGS},
4119n/a {"getargs_es_hash", getargs_es_hash, METH_VARARGS},
4120n/a {"getargs_et_hash", getargs_et_hash, METH_VARARGS},
4121n/a {"codec_incrementalencoder",
4122n/a (PyCFunction)codec_incrementalencoder, METH_VARARGS},
4123n/a {"codec_incrementaldecoder",
4124n/a (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
4125n/a {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS},
4126n/a {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
4127n/a {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS},
4128n/a {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
4129n/a {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS},
4130n/a {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS},
4131n/a {"unicode_asucs4", unicode_asucs4, METH_VARARGS},
4132n/a {"unicode_findchar", unicode_findchar, METH_VARARGS},
4133n/a {"unicode_copycharacters", unicode_copycharacters, METH_VARARGS},
4134n/a {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS},
4135n/a {"unicode_transformdecimaltoascii", unicode_transformdecimaltoascii, METH_VARARGS},
4136n/a {"unicode_legacy_string", unicode_legacy_string, METH_VARARGS},
4137n/a#ifdef WITH_THREAD
4138n/a {"_test_thread_state", test_thread_state, METH_VARARGS},
4139n/a {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
4140n/a#endif
4141n/a#ifdef HAVE_GETTIMEOFDAY
4142n/a {"profile_int", profile_int, METH_NOARGS},
4143n/a#endif
4144n/a {"traceback_print", traceback_print, METH_VARARGS},
4145n/a {"exception_print", exception_print, METH_VARARGS},
4146n/a {"set_exc_info", test_set_exc_info, METH_VARARGS},
4147n/a {"argparsing", argparsing, METH_VARARGS},
4148n/a {"code_newempty", code_newempty, METH_VARARGS},
4149n/a {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
4150n/a METH_VARARGS | METH_KEYWORDS},
4151n/a {"make_memoryview_from_NULL_pointer", (PyCFunction)make_memoryview_from_NULL_pointer,
4152n/a METH_NOARGS},
4153n/a {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS},
4154n/a {"run_in_subinterp", run_in_subinterp, METH_VARARGS},
4155n/a {"pytime_object_to_time_t", test_pytime_object_to_time_t, METH_VARARGS},
4156n/a {"pytime_object_to_timeval", test_pytime_object_to_timeval, METH_VARARGS},
4157n/a {"pytime_object_to_timespec", test_pytime_object_to_timespec, METH_VARARGS},
4158n/a {"with_tp_del", with_tp_del, METH_VARARGS},
4159n/a {"create_cfunction", create_cfunction, METH_NOARGS},
4160n/a {"test_pymem_alloc0",
4161n/a (PyCFunction)test_pymem_alloc0, METH_NOARGS},
4162n/a {"test_pymem_setrawallocators",
4163n/a (PyCFunction)test_pymem_setrawallocators, METH_NOARGS},
4164n/a {"test_pymem_setallocators",
4165n/a (PyCFunction)test_pymem_setallocators, METH_NOARGS},
4166n/a {"test_pyobject_setallocators",
4167n/a (PyCFunction)test_pyobject_setallocators, METH_NOARGS},
4168n/a {"no_docstring",
4169n/a (PyCFunction)test_with_docstring, METH_NOARGS},
4170n/a {"docstring_empty",
4171n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4172n/a docstring_empty},
4173n/a {"docstring_no_signature",
4174n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4175n/a docstring_no_signature},
4176n/a {"docstring_with_invalid_signature",
4177n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4178n/a docstring_with_invalid_signature},
4179n/a {"docstring_with_invalid_signature2",
4180n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4181n/a docstring_with_invalid_signature2},
4182n/a {"docstring_with_signature",
4183n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4184n/a docstring_with_signature},
4185n/a {"docstring_with_signature_but_no_doc",
4186n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4187n/a docstring_with_signature_but_no_doc},
4188n/a {"docstring_with_signature_and_extra_newlines",
4189n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4190n/a docstring_with_signature_and_extra_newlines},
4191n/a {"docstring_with_signature_with_defaults",
4192n/a (PyCFunction)test_with_docstring, METH_NOARGS,
4193n/a docstring_with_signature_with_defaults},
4194n/a {"raise_signal",
4195n/a (PyCFunction)test_raise_signal, METH_VARARGS},
4196n/a#ifdef WITH_THREAD
4197n/a {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O,
4198n/a PyDoc_STR("set_error_class(error_class) -> None")},
4199n/a#endif
4200n/a {"pymarshal_write_long_to_file",
4201n/a pymarshal_write_long_to_file, METH_VARARGS},
4202n/a {"pymarshal_write_object_to_file",
4203n/a pymarshal_write_object_to_file, METH_VARARGS},
4204n/a {"pymarshal_read_short_from_file",
4205n/a pymarshal_read_short_from_file, METH_VARARGS},
4206n/a {"pymarshal_read_long_from_file",
4207n/a pymarshal_read_long_from_file, METH_VARARGS},
4208n/a {"pymarshal_read_last_object_from_file",
4209n/a pymarshal_read_last_object_from_file, METH_VARARGS},
4210n/a {"pymarshal_read_object_from_file",
4211n/a pymarshal_read_object_from_file, METH_VARARGS},
4212n/a {"return_null_without_error",
4213n/a return_null_without_error, METH_NOARGS},
4214n/a {"return_result_with_error",
4215n/a return_result_with_error, METH_NOARGS},
4216n/a {"PyTime_FromSeconds", test_pytime_fromseconds, METH_VARARGS},
4217n/a {"PyTime_FromSecondsObject", test_pytime_fromsecondsobject, METH_VARARGS},
4218n/a {"PyTime_AsSecondsDouble", test_pytime_assecondsdouble, METH_VARARGS},
4219n/a {"PyTime_AsTimeval", test_PyTime_AsTimeval, METH_VARARGS},
4220n/a#ifdef HAVE_CLOCK_GETTIME
4221n/a {"PyTime_AsTimespec", test_PyTime_AsTimespec, METH_VARARGS},
4222n/a#endif
4223n/a {"PyTime_AsMilliseconds", test_PyTime_AsMilliseconds, METH_VARARGS},
4224n/a {"PyTime_AsMicroseconds", test_PyTime_AsMicroseconds, METH_VARARGS},
4225n/a {"get_recursion_depth", get_recursion_depth, METH_NOARGS},
4226n/a {"pymem_buffer_overflow", pymem_buffer_overflow, METH_NOARGS},
4227n/a {"pymem_api_misuse", pymem_api_misuse, METH_NOARGS},
4228n/a {"pymem_malloc_without_gil", pymem_malloc_without_gil, METH_NOARGS},
4229n/a {"pyobject_malloc_without_gil", pyobject_malloc_without_gil, METH_NOARGS},
4230n/a {"tracemalloc_track", tracemalloc_track, METH_VARARGS},
4231n/a {"tracemalloc_untrack", tracemalloc_untrack, METH_VARARGS},
4232n/a {"tracemalloc_get_traceback", tracemalloc_get_traceback, METH_VARARGS},
4233n/a {"dict_get_version", dict_get_version, METH_VARARGS},
4234n/a {NULL, NULL} /* sentinel */
4235n/a};
4236n/a
4237n/a#define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
4238n/a
4239n/atypedef struct {
4240n/a char bool_member;
4241n/a char byte_member;
4242n/a unsigned char ubyte_member;
4243n/a short short_member;
4244n/a unsigned short ushort_member;
4245n/a int int_member;
4246n/a unsigned int uint_member;
4247n/a long long_member;
4248n/a unsigned long ulong_member;
4249n/a Py_ssize_t pyssizet_member;
4250n/a float float_member;
4251n/a double double_member;
4252n/a char inplace_member[6];
4253n/a long long longlong_member;
4254n/a unsigned long long ulonglong_member;
4255n/a} all_structmembers;
4256n/a
4257n/atypedef struct {
4258n/a PyObject_HEAD
4259n/a all_structmembers structmembers;
4260n/a} test_structmembers;
4261n/a
4262n/astatic struct PyMemberDef test_members[] = {
4263n/a {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
4264n/a {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
4265n/a {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
4266n/a {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
4267n/a {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
4268n/a {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
4269n/a {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
4270n/a {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
4271n/a {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
4272n/a {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
4273n/a {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
4274n/a {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
4275n/a {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
4276n/a {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
4277n/a {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
4278n/a {NULL}
4279n/a};
4280n/a
4281n/a
4282n/astatic PyObject *
4283n/atest_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
4284n/a{
4285n/a static char *keywords[] = {
4286n/a "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
4287n/a "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
4288n/a "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
4289n/a "T_LONGLONG", "T_ULONGLONG",
4290n/a NULL};
4291n/a static const char fmt[] = "|bbBhHiIlknfds#LK";
4292n/a test_structmembers *ob;
4293n/a const char *s = NULL;
4294n/a Py_ssize_t string_len = 0;
4295n/a ob = PyObject_New(test_structmembers, type);
4296n/a if (ob == NULL)
4297n/a return NULL;
4298n/a memset(&ob->structmembers, 0, sizeof(all_structmembers));
4299n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
4300n/a &ob->structmembers.bool_member,
4301n/a &ob->structmembers.byte_member,
4302n/a &ob->structmembers.ubyte_member,
4303n/a &ob->structmembers.short_member,
4304n/a &ob->structmembers.ushort_member,
4305n/a &ob->structmembers.int_member,
4306n/a &ob->structmembers.uint_member,
4307n/a &ob->structmembers.long_member,
4308n/a &ob->structmembers.ulong_member,
4309n/a &ob->structmembers.pyssizet_member,
4310n/a &ob->structmembers.float_member,
4311n/a &ob->structmembers.double_member,
4312n/a &s, &string_len
4313n/a , &ob->structmembers.longlong_member,
4314n/a &ob->structmembers.ulonglong_member
4315n/a )) {
4316n/a Py_DECREF(ob);
4317n/a return NULL;
4318n/a }
4319n/a if (s != NULL) {
4320n/a if (string_len > 5) {
4321n/a Py_DECREF(ob);
4322n/a PyErr_SetString(PyExc_ValueError, "string too long");
4323n/a return NULL;
4324n/a }
4325n/a strcpy(ob->structmembers.inplace_member, s);
4326n/a }
4327n/a else {
4328n/a strcpy(ob->structmembers.inplace_member, "");
4329n/a }
4330n/a return (PyObject *)ob;
4331n/a}
4332n/a
4333n/astatic void
4334n/atest_structmembers_free(PyObject *ob)
4335n/a{
4336n/a PyObject_FREE(ob);
4337n/a}
4338n/a
4339n/astatic PyTypeObject test_structmembersType = {
4340n/a PyVarObject_HEAD_INIT(NULL, 0)
4341n/a "test_structmembersType",
4342n/a sizeof(test_structmembers), /* tp_basicsize */
4343n/a 0, /* tp_itemsize */
4344n/a test_structmembers_free, /* destructor tp_dealloc */
4345n/a 0, /* tp_print */
4346n/a 0, /* tp_getattr */
4347n/a 0, /* tp_setattr */
4348n/a 0, /* tp_reserved */
4349n/a 0, /* tp_repr */
4350n/a 0, /* tp_as_number */
4351n/a 0, /* tp_as_sequence */
4352n/a 0, /* tp_as_mapping */
4353n/a 0, /* tp_hash */
4354n/a 0, /* tp_call */
4355n/a 0, /* tp_str */
4356n/a PyObject_GenericGetAttr, /* tp_getattro */
4357n/a PyObject_GenericSetAttr, /* tp_setattro */
4358n/a 0, /* tp_as_buffer */
4359n/a 0, /* tp_flags */
4360n/a "Type containing all structmember types",
4361n/a 0, /* traverseproc tp_traverse */
4362n/a 0, /* tp_clear */
4363n/a 0, /* tp_richcompare */
4364n/a 0, /* tp_weaklistoffset */
4365n/a 0, /* tp_iter */
4366n/a 0, /* tp_iternext */
4367n/a 0, /* tp_methods */
4368n/a test_members, /* tp_members */
4369n/a 0,
4370n/a 0,
4371n/a 0,
4372n/a 0,
4373n/a 0,
4374n/a 0,
4375n/a 0,
4376n/a 0,
4377n/a test_structmembers_new, /* tp_new */
4378n/a};
4379n/a
4380n/a
4381n/atypedef struct {
4382n/a PyObject_HEAD
4383n/a} matmulObject;
4384n/a
4385n/astatic PyObject *
4386n/amatmulType_matmul(PyObject *self, PyObject *other)
4387n/a{
4388n/a return Py_BuildValue("(sOO)", "matmul", self, other);
4389n/a}
4390n/a
4391n/astatic PyObject *
4392n/amatmulType_imatmul(PyObject *self, PyObject *other)
4393n/a{
4394n/a return Py_BuildValue("(sOO)", "imatmul", self, other);
4395n/a}
4396n/a
4397n/astatic void
4398n/amatmulType_dealloc(PyObject *self)
4399n/a{
4400n/a Py_TYPE(self)->tp_free(self);
4401n/a}
4402n/a
4403n/astatic PyNumberMethods matmulType_as_number = {
4404n/a 0, /* nb_add */
4405n/a 0, /* nb_subtract */
4406n/a 0, /* nb_multiply */
4407n/a 0, /* nb_remainde r*/
4408n/a 0, /* nb_divmod */
4409n/a 0, /* nb_power */
4410n/a 0, /* nb_negative */
4411n/a 0, /* tp_positive */
4412n/a 0, /* tp_absolute */
4413n/a 0, /* tp_bool */
4414n/a 0, /* nb_invert */
4415n/a 0, /* nb_lshift */
4416n/a 0, /* nb_rshift */
4417n/a 0, /* nb_and */
4418n/a 0, /* nb_xor */
4419n/a 0, /* nb_or */
4420n/a 0, /* nb_int */
4421n/a 0, /* nb_reserved */
4422n/a 0, /* nb_float */
4423n/a 0, /* nb_inplace_add */
4424n/a 0, /* nb_inplace_subtract */
4425n/a 0, /* nb_inplace_multiply */
4426n/a 0, /* nb_inplace_remainder */
4427n/a 0, /* nb_inplace_power */
4428n/a 0, /* nb_inplace_lshift */
4429n/a 0, /* nb_inplace_rshift */
4430n/a 0, /* nb_inplace_and */
4431n/a 0, /* nb_inplace_xor */
4432n/a 0, /* nb_inplace_or */
4433n/a 0, /* nb_floor_divide */
4434n/a 0, /* nb_true_divide */
4435n/a 0, /* nb_inplace_floor_divide */
4436n/a 0, /* nb_inplace_true_divide */
4437n/a 0, /* nb_index */
4438n/a matmulType_matmul, /* nb_matrix_multiply */
4439n/a matmulType_imatmul /* nb_matrix_inplace_multiply */
4440n/a};
4441n/a
4442n/astatic PyTypeObject matmulType = {
4443n/a PyVarObject_HEAD_INIT(NULL, 0)
4444n/a "matmulType",
4445n/a sizeof(matmulObject), /* tp_basicsize */
4446n/a 0, /* tp_itemsize */
4447n/a matmulType_dealloc, /* destructor tp_dealloc */
4448n/a 0, /* tp_print */
4449n/a 0, /* tp_getattr */
4450n/a 0, /* tp_setattr */
4451n/a 0, /* tp_reserved */
4452n/a 0, /* tp_repr */
4453n/a &matmulType_as_number, /* tp_as_number */
4454n/a 0, /* tp_as_sequence */
4455n/a 0, /* tp_as_mapping */
4456n/a 0, /* tp_hash */
4457n/a 0, /* tp_call */
4458n/a 0, /* tp_str */
4459n/a PyObject_GenericGetAttr, /* tp_getattro */
4460n/a PyObject_GenericSetAttr, /* tp_setattro */
4461n/a 0, /* tp_as_buffer */
4462n/a 0, /* tp_flags */
4463n/a "C level type with matrix operations defined",
4464n/a 0, /* traverseproc tp_traverse */
4465n/a 0, /* tp_clear */
4466n/a 0, /* tp_richcompare */
4467n/a 0, /* tp_weaklistoffset */
4468n/a 0, /* tp_iter */
4469n/a 0, /* tp_iternext */
4470n/a 0, /* tp_methods */
4471n/a 0, /* tp_members */
4472n/a 0,
4473n/a 0,
4474n/a 0,
4475n/a 0,
4476n/a 0,
4477n/a 0,
4478n/a 0,
4479n/a 0,
4480n/a PyType_GenericNew, /* tp_new */
4481n/a PyObject_Del, /* tp_free */
4482n/a};
4483n/a
4484n/a
4485n/atypedef struct {
4486n/a PyObject_HEAD
4487n/a PyObject *ao_iterator;
4488n/a} awaitObject;
4489n/a
4490n/a
4491n/astatic PyObject *
4492n/aawaitObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4493n/a{
4494n/a PyObject *v;
4495n/a awaitObject *ao;
4496n/a
4497n/a if (!PyArg_UnpackTuple(args, "awaitObject", 1, 1, &v))
4498n/a return NULL;
4499n/a
4500n/a ao = (awaitObject *)type->tp_alloc(type, 0);
4501n/a if (ao == NULL) {
4502n/a return NULL;
4503n/a }
4504n/a
4505n/a Py_INCREF(v);
4506n/a ao->ao_iterator = v;
4507n/a
4508n/a return (PyObject *)ao;
4509n/a}
4510n/a
4511n/a
4512n/astatic void
4513n/aawaitObject_dealloc(awaitObject *ao)
4514n/a{
4515n/a Py_CLEAR(ao->ao_iterator);
4516n/a Py_TYPE(ao)->tp_free(ao);
4517n/a}
4518n/a
4519n/a
4520n/astatic PyObject *
4521n/aawaitObject_await(awaitObject *ao)
4522n/a{
4523n/a Py_INCREF(ao->ao_iterator);
4524n/a return ao->ao_iterator;
4525n/a}
4526n/a
4527n/astatic PyAsyncMethods awaitType_as_async = {
4528n/a (unaryfunc)awaitObject_await, /* am_await */
4529n/a 0, /* am_aiter */
4530n/a 0 /* am_anext */
4531n/a};
4532n/a
4533n/a
4534n/astatic PyTypeObject awaitType = {
4535n/a PyVarObject_HEAD_INIT(NULL, 0)
4536n/a "awaitType",
4537n/a sizeof(awaitObject), /* tp_basicsize */
4538n/a 0, /* tp_itemsize */
4539n/a (destructor)awaitObject_dealloc, /* destructor tp_dealloc */
4540n/a 0, /* tp_print */
4541n/a 0, /* tp_getattr */
4542n/a 0, /* tp_setattr */
4543n/a &awaitType_as_async, /* tp_as_async */
4544n/a 0, /* tp_repr */
4545n/a 0, /* tp_as_number */
4546n/a 0, /* tp_as_sequence */
4547n/a 0, /* tp_as_mapping */
4548n/a 0, /* tp_hash */
4549n/a 0, /* tp_call */
4550n/a 0, /* tp_str */
4551n/a PyObject_GenericGetAttr, /* tp_getattro */
4552n/a PyObject_GenericSetAttr, /* tp_setattro */
4553n/a 0, /* tp_as_buffer */
4554n/a 0, /* tp_flags */
4555n/a "C level type with tp_as_async",
4556n/a 0, /* traverseproc tp_traverse */
4557n/a 0, /* tp_clear */
4558n/a 0, /* tp_richcompare */
4559n/a 0, /* tp_weaklistoffset */
4560n/a 0, /* tp_iter */
4561n/a 0, /* tp_iternext */
4562n/a 0, /* tp_methods */
4563n/a 0, /* tp_members */
4564n/a 0,
4565n/a 0,
4566n/a 0,
4567n/a 0,
4568n/a 0,
4569n/a 0,
4570n/a 0,
4571n/a 0,
4572n/a awaitObject_new, /* tp_new */
4573n/a PyObject_Del, /* tp_free */
4574n/a};
4575n/a
4576n/a
4577n/astatic struct PyModuleDef _testcapimodule = {
4578n/a PyModuleDef_HEAD_INIT,
4579n/a "_testcapi",
4580n/a NULL,
4581n/a -1,
4582n/a TestMethods,
4583n/a NULL,
4584n/a NULL,
4585n/a NULL,
4586n/a NULL
4587n/a};
4588n/a
4589n/a/* Per PEP 489, this module will not be converted to multi-phase initialization
4590n/a */
4591n/a
4592n/aPyMODINIT_FUNC
4593n/aPyInit__testcapi(void)
4594n/a{
4595n/a PyObject *m;
4596n/a
4597n/a m = PyModule_Create(&_testcapimodule);
4598n/a if (m == NULL)
4599n/a return NULL;
4600n/a
4601n/a Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
4602n/a
4603n/a Py_TYPE(&test_structmembersType)=&PyType_Type;
4604n/a Py_INCREF(&test_structmembersType);
4605n/a /* don't use a name starting with "test", since we don't want
4606n/a test_capi to automatically call this */
4607n/a PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
4608n/a if (PyType_Ready(&matmulType) < 0)
4609n/a return NULL;
4610n/a Py_INCREF(&matmulType);
4611n/a PyModule_AddObject(m, "matmulType", (PyObject *)&matmulType);
4612n/a
4613n/a if (PyType_Ready(&awaitType) < 0)
4614n/a return NULL;
4615n/a Py_INCREF(&awaitType);
4616n/a PyModule_AddObject(m, "awaitType", (PyObject *)&awaitType);
4617n/a
4618n/a PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
4619n/a PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
4620n/a PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
4621n/a PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
4622n/a PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
4623n/a PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
4624n/a PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
4625n/a PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
4626n/a PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
4627n/a PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
4628n/a PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
4629n/a PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
4630n/a PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
4631n/a PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
4632n/a PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
4633n/a PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
4634n/a PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
4635n/a PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
4636n/a PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
4637n/a PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
4638n/a PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
4639n/a PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head)));
4640n/a PyModule_AddObject(m, "SIZEOF_TIME_T", PyLong_FromSsize_t(sizeof(time_t)));
4641n/a Py_INCREF(&PyInstanceMethod_Type);
4642n/a PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
4643n/a
4644n/a PyModule_AddIntConstant(m, "the_number_three", 3);
4645n/a
4646n/a TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
4647n/a Py_INCREF(TestError);
4648n/a PyModule_AddObject(m, "error", TestError);
4649n/a return m;
4650n/a}