1 /*
2 * C Extension module to test Python interpreter C APIs.
3 *
4 * The 'test_*' functions exported by this module are run as part of the
5 * standard Python regression test, via Lib/test/test_capi.py.
6 */
7
8 #include "Python.h"
9 #include <float.h>
10 #include "structmember.h"
11 #include "datetime.h"
12 #include "marshal.h"
13 #include <signal.h>
14 #ifdef MS_WINDOWS
15 # include <crtdbg.h>
16 #endif
17
18 #ifdef HAVE_SYS_WAIT_H
19 #include <sys/wait.h> /* For W_STOPCODE */
20 #endif
21
22 #ifdef WITH_THREAD
23 #include "pythread.h"
24 #endif /* WITH_THREAD */
25 static PyObject *TestError; /* set to exception object in init */
26
27 /* Raise TestError with test_name + ": " + msg, and return NULL. */
28
29 static PyObject *
raiseTestError(const char * test_name,const char * msg)30 raiseTestError(const char* test_name, const char* msg)
31 {
32 char buf[2048];
33
34 if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
35 PyErr_SetString(TestError, "internal error msg too large");
36 else {
37 PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
38 PyErr_SetString(TestError, buf);
39 }
40 return NULL;
41 }
42
43 /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
44
45 The ones derived from autoconf on the UNIX-like OSes can be relied
46 upon (in the absence of sloppy cross-compiling), but the Windows
47 platforms have these hardcoded. Better safe than sorry.
48 */
49 static PyObject*
sizeof_error(const char * fatname,const char * typname,int expected,int got)50 sizeof_error(const char* fatname, const char* typname,
51 int expected, int got)
52 {
53 char buf[1024];
54 PyOS_snprintf(buf, sizeof(buf),
55 "%.200s #define == %d but sizeof(%.200s) == %d",
56 fatname, expected, typname, got);
57 PyErr_SetString(TestError, buf);
58 return (PyObject*)NULL;
59 }
60
61 static PyObject*
test_config(PyObject * self)62 test_config(PyObject *self)
63 {
64 #define CHECK_SIZEOF(FATNAME, TYPE) \
65 if (FATNAME != sizeof(TYPE)) \
66 return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
67
68 CHECK_SIZEOF(SIZEOF_SHORT, short);
69 CHECK_SIZEOF(SIZEOF_INT, int);
70 CHECK_SIZEOF(SIZEOF_LONG, long);
71 CHECK_SIZEOF(SIZEOF_VOID_P, void*);
72 CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
73 #ifdef HAVE_LONG_LONG
74 CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
75 #endif
76
77 #undef CHECK_SIZEOF
78
79 Py_INCREF(Py_None);
80 return Py_None;
81 }
82
83 static PyObject*
test_list_api(PyObject * self)84 test_list_api(PyObject *self)
85 {
86 PyObject* list;
87 int i;
88
89 /* SF bug 132008: PyList_Reverse segfaults */
90 #define NLIST 30
91 list = PyList_New(NLIST);
92 if (list == (PyObject*)NULL)
93 return (PyObject*)NULL;
94 /* list = range(NLIST) */
95 for (i = 0; i < NLIST; ++i) {
96 PyObject* anint = PyInt_FromLong(i);
97 if (anint == (PyObject*)NULL) {
98 Py_DECREF(list);
99 return (PyObject*)NULL;
100 }
101 PyList_SET_ITEM(list, i, anint);
102 }
103 /* list.reverse(), via PyList_Reverse() */
104 i = PyList_Reverse(list); /* should not blow up! */
105 if (i != 0) {
106 Py_DECREF(list);
107 return (PyObject*)NULL;
108 }
109 /* Check that list == range(29, -1, -1) now */
110 for (i = 0; i < NLIST; ++i) {
111 PyObject* anint = PyList_GET_ITEM(list, i);
112 if (PyInt_AS_LONG(anint) != NLIST-1-i) {
113 PyErr_SetString(TestError,
114 "test_list_api: reverse screwed up");
115 Py_DECREF(list);
116 return (PyObject*)NULL;
117 }
118 }
119 Py_DECREF(list);
120 #undef NLIST
121
122 Py_INCREF(Py_None);
123 return Py_None;
124 }
125
126 static int
test_dict_inner(int count)127 test_dict_inner(int count)
128 {
129 Py_ssize_t pos = 0, iterations = 0;
130 int i;
131 PyObject *dict = PyDict_New();
132 PyObject *v, *k;
133
134 if (dict == NULL)
135 return -1;
136
137 for (i = 0; i < count; i++) {
138 v = PyInt_FromLong(i);
139 PyDict_SetItem(dict, v, v);
140 Py_DECREF(v);
141 }
142
143 while (PyDict_Next(dict, &pos, &k, &v)) {
144 PyObject *o;
145 iterations++;
146
147 i = PyInt_AS_LONG(v) + 1;
148 o = PyInt_FromLong(i);
149 if (o == NULL)
150 return -1;
151 if (PyDict_SetItem(dict, k, o) < 0) {
152 Py_DECREF(o);
153 return -1;
154 }
155 Py_DECREF(o);
156 }
157
158 Py_DECREF(dict);
159
160 if (iterations != count) {
161 PyErr_SetString(
162 TestError,
163 "test_dict_iteration: dict iteration went wrong ");
164 return -1;
165 } else {
166 return 0;
167 }
168 }
169
170 static PyObject*
test_dict_iteration(PyObject * self)171 test_dict_iteration(PyObject* self)
172 {
173 int i;
174
175 for (i = 0; i < 200; i++) {
176 if (test_dict_inner(i) < 0) {
177 return NULL;
178 }
179 }
180
181 Py_INCREF(Py_None);
182 return Py_None;
183 }
184
185
186 /* Issue #4701: Check that PyObject_Hash implicitly calls
187 * PyType_Ready if it hasn't already been called
188 */
189 static PyTypeObject _HashInheritanceTester_Type = {
190 PyVarObject_HEAD_INIT(NULL, 0)
191 "hashinheritancetester", /* Name of this type */
192 sizeof(PyObject), /* Basic object size */
193 0, /* Item size for varobject */
194 (destructor)PyObject_Del, /* tp_dealloc */
195 0, /* tp_print */
196 0, /* tp_getattr */
197 0, /* tp_setattr */
198 0, /* tp_compare */
199 0, /* tp_repr */
200 0, /* tp_as_number */
201 0, /* tp_as_sequence */
202 0, /* tp_as_mapping */
203 0, /* tp_hash */
204 0, /* tp_call */
205 0, /* tp_str */
206 PyObject_GenericGetAttr, /* tp_getattro */
207 0, /* tp_setattro */
208 0, /* tp_as_buffer */
209 Py_TPFLAGS_DEFAULT, /* tp_flags */
210 0, /* tp_doc */
211 0, /* tp_traverse */
212 0, /* tp_clear */
213 0, /* tp_richcompare */
214 0, /* tp_weaklistoffset */
215 0, /* tp_iter */
216 0, /* tp_iternext */
217 0, /* tp_methods */
218 0, /* tp_members */
219 0, /* tp_getset */
220 0, /* tp_base */
221 0, /* tp_dict */
222 0, /* tp_descr_get */
223 0, /* tp_descr_set */
224 0, /* tp_dictoffset */
225 0, /* tp_init */
226 0, /* tp_alloc */
227 PyType_GenericNew, /* tp_new */
228 };
229
230 static PyObject*
test_lazy_hash_inheritance(PyObject * self)231 test_lazy_hash_inheritance(PyObject* self)
232 {
233 PyTypeObject *type;
234 PyObject *obj;
235 long hash;
236
237 type = &_HashInheritanceTester_Type;
238
239 if (type->tp_dict != NULL)
240 /* The type has already been initialized. This probably means
241 -R is being used. */
242 Py_RETURN_NONE;
243
244
245 obj = PyObject_New(PyObject, type);
246 if (obj == NULL) {
247 PyErr_Clear();
248 PyErr_SetString(
249 TestError,
250 "test_lazy_hash_inheritance: failed to create object");
251 return NULL;
252 }
253
254 if (type->tp_dict != NULL) {
255 PyErr_SetString(
256 TestError,
257 "test_lazy_hash_inheritance: type initialised too soon");
258 Py_DECREF(obj);
259 return NULL;
260 }
261
262 hash = PyObject_Hash(obj);
263 if ((hash == -1) && PyErr_Occurred()) {
264 PyErr_Clear();
265 PyErr_SetString(
266 TestError,
267 "test_lazy_hash_inheritance: could not hash object");
268 Py_DECREF(obj);
269 return NULL;
270 }
271
272 if (type->tp_dict == NULL) {
273 PyErr_SetString(
274 TestError,
275 "test_lazy_hash_inheritance: type not initialised by hash()");
276 Py_DECREF(obj);
277 return NULL;
278 }
279
280 if (type->tp_hash != PyType_Type.tp_hash) {
281 PyErr_SetString(
282 TestError,
283 "test_lazy_hash_inheritance: unexpected hash function");
284 Py_DECREF(obj);
285 return NULL;
286 }
287
288 Py_DECREF(obj);
289
290 Py_RETURN_NONE;
291 }
292
293
294 /* Issue #7385: Check that memoryview() does not crash
295 * when bf_getbuffer returns an error
296 */
297
298 static int
broken_buffer_getbuffer(PyObject * self,Py_buffer * view,int flags)299 broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags)
300 {
301 PyErr_SetString(
302 TestError,
303 "test_broken_memoryview: expected error in bf_getbuffer");
304 return -1;
305 }
306
307 static PyBufferProcs memoryviewtester_as_buffer = {
308 0, /* bf_getreadbuffer */
309 0, /* bf_getwritebuffer */
310 0, /* bf_getsegcount */
311 0, /* bf_getcharbuffer */
312 (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
313 0, /* bf_releasebuffer */
314 };
315
316 static PyTypeObject _MemoryViewTester_Type = {
317 PyVarObject_HEAD_INIT(NULL, 0)
318 "memoryviewtester", /* Name of this type */
319 sizeof(PyObject), /* Basic object size */
320 0, /* Item size for varobject */
321 (destructor)PyObject_Del, /* tp_dealloc */
322 0, /* tp_print */
323 0, /* tp_getattr */
324 0, /* tp_setattr */
325 0, /* tp_compare */
326 0, /* tp_repr */
327 0, /* tp_as_number */
328 0, /* tp_as_sequence */
329 0, /* tp_as_mapping */
330 0, /* tp_hash */
331 0, /* tp_call */
332 0, /* tp_str */
333 PyObject_GenericGetAttr, /* tp_getattro */
334 0, /* tp_setattro */
335 &memoryviewtester_as_buffer, /* tp_as_buffer */
336 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */
337 0, /* tp_doc */
338 0, /* tp_traverse */
339 0, /* tp_clear */
340 0, /* tp_richcompare */
341 0, /* tp_weaklistoffset */
342 0, /* tp_iter */
343 0, /* tp_iternext */
344 0, /* tp_methods */
345 0, /* tp_members */
346 0, /* tp_getset */
347 0, /* tp_base */
348 0, /* tp_dict */
349 0, /* tp_descr_get */
350 0, /* tp_descr_set */
351 0, /* tp_dictoffset */
352 0, /* tp_init */
353 0, /* tp_alloc */
354 PyType_GenericNew, /* tp_new */
355 };
356
357 static PyObject*
test_broken_memoryview(PyObject * self)358 test_broken_memoryview(PyObject* self)
359 {
360 PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
361 PyObject *res;
362
363 if (obj == NULL) {
364 PyErr_Clear();
365 PyErr_SetString(
366 TestError,
367 "test_broken_memoryview: failed to create object");
368 return NULL;
369 }
370
371 res = PyMemoryView_FromObject(obj);
372 if (res || !PyErr_Occurred()){
373 PyErr_SetString(
374 TestError,
375 "test_broken_memoryview: memoryview() didn't raise an Exception");
376 Py_XDECREF(res);
377 Py_DECREF(obj);
378 return NULL;
379 }
380
381 PyErr_Clear();
382 Py_DECREF(obj);
383 Py_RETURN_NONE;
384 }
385
386 static PyObject *
test_to_contiguous(PyObject * self,PyObject * noargs)387 test_to_contiguous(PyObject* self, PyObject *noargs)
388 {
389 int data[9] = {0, -1, 1, -1, 2, -1, 3, -1, 4};
390 int result[5];
391 Py_ssize_t itemsize = sizeof(int);
392 Py_ssize_t shape = 5;
393 Py_ssize_t strides = 2 * itemsize;
394 Py_buffer view = {
395 data,
396 NULL,
397 5 * itemsize,
398 itemsize,
399 1,
400 1,
401 NULL,
402 &shape,
403 &strides,
404 NULL,
405 {0, 0},
406 NULL
407 };
408 int i;
409
410 PyBuffer_ToContiguous(result, &view, view.len, 'C');
411 for (i = 0; i < 5; i++) {
412 if (result[i] != i) {
413 PyErr_SetString(TestError,
414 "test_to_contiguous: incorrect result");
415 return NULL;
416 }
417 }
418
419 view.buf = &data[8];
420 view.strides[0] = -2 * itemsize;
421
422 PyBuffer_ToContiguous(result, &view, view.len, 'C');
423 for (i = 0; i < 5; i++) {
424 if (result[i] != 4-i) {
425 PyErr_SetString(TestError,
426 "test_to_contiguous: incorrect result");
427 return NULL;
428 }
429 }
430
431 Py_RETURN_NONE;
432 }
433
434 static PyObject *
test_from_contiguous(PyObject * self,PyObject * noargs)435 test_from_contiguous(PyObject* self, PyObject *noargs)
436 {
437 int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
438 int init[5] = {0, 1, 2, 3, 4};
439 Py_ssize_t itemsize = sizeof(int);
440 Py_ssize_t shape = 5;
441 Py_ssize_t strides = 2 * itemsize;
442 Py_buffer view = {
443 data,
444 NULL,
445 5 * itemsize,
446 itemsize,
447 1,
448 1,
449 NULL,
450 &shape,
451 &strides,
452 NULL,
453 {0, 0},
454 NULL
455 };
456 int *ptr;
457 int i;
458
459 PyBuffer_FromContiguous(&view, init, view.len, 'C');
460 ptr = view.buf;
461 for (i = 0; i < 5; i++) {
462 if (ptr[2*i] != i) {
463 PyErr_SetString(TestError,
464 "test_from_contiguous: incorrect result");
465 return NULL;
466 }
467 }
468
469 view.buf = &data[8];
470 view.strides[0] = -2 * itemsize;
471
472 PyBuffer_FromContiguous(&view, init, view.len, 'C');
473 ptr = view.buf;
474 for (i = 0; i < 5; i++) {
475 if (*(ptr-2*i) != i) {
476 PyErr_SetString(TestError,
477 "test_from_contiguous: incorrect result");
478 return NULL;
479 }
480 }
481
482 Py_RETURN_NONE;
483 }
484
485
486 /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG)
487 PyLong_{As, From}{Unsigned,}LongLong().
488
489 Note that the meat of the test is contained in testcapi_long.h.
490 This is revolting, but delicate code duplication is worse: "almost
491 exactly the same" code is needed to test PY_LONG_LONG, but the ubiquitous
492 dependence on type names makes it impossible to use a parameterized
493 function. A giant macro would be even worse than this. A C++ template
494 would be perfect.
495
496 The "report an error" functions are deliberately not part of the #include
497 file: if the test fails, you can set a breakpoint in the appropriate
498 error function directly, and crawl back from there in the debugger.
499 */
500
501 #define UNBIND(X) Py_DECREF(X); (X) = NULL
502
503 static PyObject *
raise_test_long_error(const char * msg)504 raise_test_long_error(const char* msg)
505 {
506 return raiseTestError("test_long_api", msg);
507 }
508
509 #define TESTNAME test_long_api_inner
510 #define TYPENAME long
511 #define F_S_TO_PY PyLong_FromLong
512 #define F_PY_TO_S PyLong_AsLong
513 #define F_U_TO_PY PyLong_FromUnsignedLong
514 #define F_PY_TO_U PyLong_AsUnsignedLong
515
516 #include "testcapi_long.h"
517
518 static PyObject *
test_long_api(PyObject * self)519 test_long_api(PyObject* self)
520 {
521 return TESTNAME(raise_test_long_error);
522 }
523
524 #undef TESTNAME
525 #undef TYPENAME
526 #undef F_S_TO_PY
527 #undef F_PY_TO_S
528 #undef F_U_TO_PY
529 #undef F_PY_TO_U
530
531 #ifdef HAVE_LONG_LONG
532
533 static PyObject *
raise_test_longlong_error(const char * msg)534 raise_test_longlong_error(const char* msg)
535 {
536 return raiseTestError("test_longlong_api", msg);
537 }
538
539 #define TESTNAME test_longlong_api_inner
540 #define TYPENAME PY_LONG_LONG
541 #define F_S_TO_PY PyLong_FromLongLong
542 #define F_PY_TO_S PyLong_AsLongLong
543 #define F_U_TO_PY PyLong_FromUnsignedLongLong
544 #define F_PY_TO_U PyLong_AsUnsignedLongLong
545
546 #include "testcapi_long.h"
547
548 static PyObject *
test_longlong_api(PyObject * self,PyObject * args)549 test_longlong_api(PyObject* self, PyObject *args)
550 {
551 return TESTNAME(raise_test_longlong_error);
552 }
553
554 #undef TESTNAME
555 #undef TYPENAME
556 #undef F_S_TO_PY
557 #undef F_PY_TO_S
558 #undef F_U_TO_PY
559 #undef F_PY_TO_U
560
561 /* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG
562 is tested by test_long_api_inner. This test will concentrate on proper
563 handling of overflow.
564 */
565
566 static PyObject *
test_long_and_overflow(PyObject * self)567 test_long_and_overflow(PyObject *self)
568 {
569 PyObject *num, *one, *temp;
570 long value;
571 int overflow;
572
573 /* Test that overflow is set properly for a large value. */
574 /* num is a number larger than LONG_MAX even on 64-bit platforms */
575 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
576 if (num == NULL)
577 return NULL;
578 overflow = 1234;
579 value = PyLong_AsLongAndOverflow(num, &overflow);
580 Py_DECREF(num);
581 if (value == -1 && PyErr_Occurred())
582 return NULL;
583 if (value != -1)
584 return raiseTestError("test_long_and_overflow",
585 "return value was not set to -1");
586 if (overflow != 1)
587 return raiseTestError("test_long_and_overflow",
588 "overflow was not set to 1");
589
590 /* Same again, with num = LONG_MAX + 1 */
591 num = PyLong_FromLong(LONG_MAX);
592 if (num == NULL)
593 return NULL;
594 one = PyLong_FromLong(1L);
595 if (one == NULL) {
596 Py_DECREF(num);
597 return NULL;
598 }
599 temp = PyNumber_Add(num, one);
600 Py_DECREF(one);
601 Py_DECREF(num);
602 num = temp;
603 if (num == NULL)
604 return NULL;
605 overflow = 0;
606 value = PyLong_AsLongAndOverflow(num, &overflow);
607 Py_DECREF(num);
608 if (value == -1 && PyErr_Occurred())
609 return NULL;
610 if (value != -1)
611 return raiseTestError("test_long_and_overflow",
612 "return value was not set to -1");
613 if (overflow != 1)
614 return raiseTestError("test_long_and_overflow",
615 "overflow was not set to 1");
616
617 /* Test that overflow is set properly for a large negative value. */
618 /* num is a number smaller than LONG_MIN even on 64-bit platforms */
619 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
620 if (num == NULL)
621 return NULL;
622 overflow = 1234;
623 value = PyLong_AsLongAndOverflow(num, &overflow);
624 Py_DECREF(num);
625 if (value == -1 && PyErr_Occurred())
626 return NULL;
627 if (value != -1)
628 return raiseTestError("test_long_and_overflow",
629 "return value was not set to -1");
630 if (overflow != -1)
631 return raiseTestError("test_long_and_overflow",
632 "overflow was not set to -1");
633
634 /* Same again, with num = LONG_MIN - 1 */
635 num = PyLong_FromLong(LONG_MIN);
636 if (num == NULL)
637 return NULL;
638 one = PyLong_FromLong(1L);
639 if (one == NULL) {
640 Py_DECREF(num);
641 return NULL;
642 }
643 temp = PyNumber_Subtract(num, one);
644 Py_DECREF(one);
645 Py_DECREF(num);
646 num = temp;
647 if (num == NULL)
648 return NULL;
649 overflow = 0;
650 value = PyLong_AsLongAndOverflow(num, &overflow);
651 Py_DECREF(num);
652 if (value == -1 && PyErr_Occurred())
653 return NULL;
654 if (value != -1)
655 return raiseTestError("test_long_and_overflow",
656 "return value was not set to -1");
657 if (overflow != -1)
658 return raiseTestError("test_long_and_overflow",
659 "overflow was not set to -1");
660
661 /* Test that overflow is cleared properly for small values. */
662 num = PyLong_FromString("FF", NULL, 16);
663 if (num == NULL)
664 return NULL;
665 overflow = 1234;
666 value = PyLong_AsLongAndOverflow(num, &overflow);
667 Py_DECREF(num);
668 if (value == -1 && PyErr_Occurred())
669 return NULL;
670 if (value != 0xFF)
671 return raiseTestError("test_long_and_overflow",
672 "expected return value 0xFF");
673 if (overflow != 0)
674 return raiseTestError("test_long_and_overflow",
675 "overflow was not cleared");
676
677 num = PyLong_FromString("-FF", NULL, 16);
678 if (num == NULL)
679 return NULL;
680 overflow = 0;
681 value = PyLong_AsLongAndOverflow(num, &overflow);
682 Py_DECREF(num);
683 if (value == -1 && PyErr_Occurred())
684 return NULL;
685 if (value != -0xFF)
686 return raiseTestError("test_long_and_overflow",
687 "expected return value 0xFF");
688 if (overflow != 0)
689 return raiseTestError("test_long_and_overflow",
690 "overflow was set incorrectly");
691
692 num = PyLong_FromLong(LONG_MAX);
693 if (num == NULL)
694 return NULL;
695 overflow = 1234;
696 value = PyLong_AsLongAndOverflow(num, &overflow);
697 Py_DECREF(num);
698 if (value == -1 && PyErr_Occurred())
699 return NULL;
700 if (value != LONG_MAX)
701 return raiseTestError("test_long_and_overflow",
702 "expected return value LONG_MAX");
703 if (overflow != 0)
704 return raiseTestError("test_long_and_overflow",
705 "overflow was not cleared");
706
707 num = PyLong_FromLong(LONG_MIN);
708 if (num == NULL)
709 return NULL;
710 overflow = 0;
711 value = PyLong_AsLongAndOverflow(num, &overflow);
712 Py_DECREF(num);
713 if (value == -1 && PyErr_Occurred())
714 return NULL;
715 if (value != LONG_MIN)
716 return raiseTestError("test_long_and_overflow",
717 "expected return value LONG_MIN");
718 if (overflow != 0)
719 return raiseTestError("test_long_and_overflow",
720 "overflow was not cleared");
721
722 Py_INCREF(Py_None);
723 return Py_None;
724 }
725
726 /* Test the PyLong_AsLongLongAndOverflow API. General conversion to
727 PY_LONG_LONG is tested by test_long_api_inner. This test will
728 concentrate on proper handling of overflow.
729 */
730
731 static PyObject *
test_long_long_and_overflow(PyObject * self)732 test_long_long_and_overflow(PyObject *self)
733 {
734 PyObject *num, *one, *temp;
735 PY_LONG_LONG value;
736 int overflow;
737
738 /* Test that overflow is set properly for a large value. */
739 /* num is a number larger than PY_LLONG_MAX on a typical machine. */
740 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
741 if (num == NULL)
742 return NULL;
743 overflow = 1234;
744 value = PyLong_AsLongLongAndOverflow(num, &overflow);
745 Py_DECREF(num);
746 if (value == -1 && PyErr_Occurred())
747 return NULL;
748 if (value != -1)
749 return raiseTestError("test_long_long_and_overflow",
750 "return value was not set to -1");
751 if (overflow != 1)
752 return raiseTestError("test_long_long_and_overflow",
753 "overflow was not set to 1");
754
755 /* Same again, with num = PY_LLONG_MAX + 1 */
756 num = PyLong_FromLongLong(PY_LLONG_MAX);
757 if (num == NULL)
758 return NULL;
759 one = PyLong_FromLong(1L);
760 if (one == NULL) {
761 Py_DECREF(num);
762 return NULL;
763 }
764 temp = PyNumber_Add(num, one);
765 Py_DECREF(one);
766 Py_DECREF(num);
767 num = temp;
768 if (num == NULL)
769 return NULL;
770 overflow = 0;
771 value = PyLong_AsLongLongAndOverflow(num, &overflow);
772 Py_DECREF(num);
773 if (value == -1 && PyErr_Occurred())
774 return NULL;
775 if (value != -1)
776 return raiseTestError("test_long_long_and_overflow",
777 "return value was not set to -1");
778 if (overflow != 1)
779 return raiseTestError("test_long_long_and_overflow",
780 "overflow was not set to 1");
781
782 /* Test that overflow is set properly for a large negative value. */
783 /* num is a number smaller than PY_LLONG_MIN on a typical platform */
784 num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
785 if (num == NULL)
786 return NULL;
787 overflow = 1234;
788 value = PyLong_AsLongLongAndOverflow(num, &overflow);
789 Py_DECREF(num);
790 if (value == -1 && PyErr_Occurred())
791 return NULL;
792 if (value != -1)
793 return raiseTestError("test_long_long_and_overflow",
794 "return value was not set to -1");
795 if (overflow != -1)
796 return raiseTestError("test_long_long_and_overflow",
797 "overflow was not set to -1");
798
799 /* Same again, with num = PY_LLONG_MIN - 1 */
800 num = PyLong_FromLongLong(PY_LLONG_MIN);
801 if (num == NULL)
802 return NULL;
803 one = PyLong_FromLong(1L);
804 if (one == NULL) {
805 Py_DECREF(num);
806 return NULL;
807 }
808 temp = PyNumber_Subtract(num, one);
809 Py_DECREF(one);
810 Py_DECREF(num);
811 num = temp;
812 if (num == NULL)
813 return NULL;
814 overflow = 0;
815 value = PyLong_AsLongLongAndOverflow(num, &overflow);
816 Py_DECREF(num);
817 if (value == -1 && PyErr_Occurred())
818 return NULL;
819 if (value != -1)
820 return raiseTestError("test_long_long_and_overflow",
821 "return value was not set to -1");
822 if (overflow != -1)
823 return raiseTestError("test_long_long_and_overflow",
824 "overflow was not set to -1");
825
826 /* Test that overflow is cleared properly for small values. */
827 num = PyLong_FromString("FF", NULL, 16);
828 if (num == NULL)
829 return NULL;
830 overflow = 1234;
831 value = PyLong_AsLongLongAndOverflow(num, &overflow);
832 Py_DECREF(num);
833 if (value == -1 && PyErr_Occurred())
834 return NULL;
835 if (value != 0xFF)
836 return raiseTestError("test_long_long_and_overflow",
837 "expected return value 0xFF");
838 if (overflow != 0)
839 return raiseTestError("test_long_long_and_overflow",
840 "overflow was not cleared");
841
842 num = PyLong_FromString("-FF", NULL, 16);
843 if (num == NULL)
844 return NULL;
845 overflow = 0;
846 value = PyLong_AsLongLongAndOverflow(num, &overflow);
847 Py_DECREF(num);
848 if (value == -1 && PyErr_Occurred())
849 return NULL;
850 if (value != -0xFF)
851 return raiseTestError("test_long_long_and_overflow",
852 "expected return value 0xFF");
853 if (overflow != 0)
854 return raiseTestError("test_long_long_and_overflow",
855 "overflow was set incorrectly");
856
857 num = PyLong_FromLongLong(PY_LLONG_MAX);
858 if (num == NULL)
859 return NULL;
860 overflow = 1234;
861 value = PyLong_AsLongLongAndOverflow(num, &overflow);
862 Py_DECREF(num);
863 if (value == -1 && PyErr_Occurred())
864 return NULL;
865 if (value != PY_LLONG_MAX)
866 return raiseTestError("test_long_long_and_overflow",
867 "expected return value PY_LLONG_MAX");
868 if (overflow != 0)
869 return raiseTestError("test_long_long_and_overflow",
870 "overflow was not cleared");
871
872 num = PyLong_FromLongLong(PY_LLONG_MIN);
873 if (num == NULL)
874 return NULL;
875 overflow = 0;
876 value = PyLong_AsLongLongAndOverflow(num, &overflow);
877 Py_DECREF(num);
878 if (value == -1 && PyErr_Occurred())
879 return NULL;
880 if (value != PY_LLONG_MIN)
881 return raiseTestError("test_long_long_and_overflow",
882 "expected return value PY_LLONG_MIN");
883 if (overflow != 0)
884 return raiseTestError("test_long_long_and_overflow",
885 "overflow was not cleared");
886
887 Py_INCREF(Py_None);
888 return Py_None;
889 }
890
891 /* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG
892 for both long and int arguments. The test may leak a little memory if
893 it fails.
894 */
895 static PyObject *
test_L_code(PyObject * self)896 test_L_code(PyObject *self)
897 {
898 PyObject *tuple, *num;
899 PY_LONG_LONG value;
900
901 tuple = PyTuple_New(1);
902 if (tuple == NULL)
903 return NULL;
904
905 num = PyLong_FromLong(42);
906 if (num == NULL)
907 return NULL;
908
909 PyTuple_SET_ITEM(tuple, 0, num);
910
911 value = -1;
912 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
913 return NULL;
914 }
915 if (value != 42)
916 return raiseTestError("test_L_code",
917 "L code returned wrong value for long 42");
918
919 Py_DECREF(num);
920 num = PyInt_FromLong(42);
921 if (num == NULL)
922 return NULL;
923
924 PyTuple_SET_ITEM(tuple, 0, num);
925
926 value = -1;
927 if (!PyArg_ParseTuple(tuple, "L:test_L_code", &value)) {
928 return NULL;
929 }
930 if (value != 42)
931 return raiseTestError("test_L_code",
932 "L code returned wrong value for int 42");
933
934 Py_DECREF(tuple);
935 Py_INCREF(Py_None);
936 return Py_None;
937 }
938
939 #endif /* ifdef HAVE_LONG_LONG */
940
941 static PyObject *
return_none(void * unused)942 return_none(void *unused)
943 {
944 Py_RETURN_NONE;
945 }
946
947 static PyObject *
raise_error(void * unused)948 raise_error(void *unused)
949 {
950 PyErr_SetNone(PyExc_ValueError);
951 return NULL;
952 }
953
954 static int
test_buildvalue_N_error(const char * fmt)955 test_buildvalue_N_error(const char *fmt)
956 {
957 PyObject *arg, *res;
958
959 arg = PyList_New(0);
960 if (arg == NULL) {
961 return -1;
962 }
963
964 Py_INCREF(arg);
965 res = Py_BuildValue(fmt, return_none, NULL, arg);
966 if (res == NULL) {
967 return -1;
968 }
969 Py_DECREF(res);
970 if (Py_REFCNT(arg) != 1) {
971 PyErr_Format(TestError, "test_buildvalue_N: "
972 "arg was not decrefed in successful "
973 "Py_BuildValue(\"%s\")", fmt);
974 return -1;
975 }
976
977 Py_INCREF(arg);
978 res = Py_BuildValue(fmt, raise_error, NULL, arg);
979 if (res != NULL || !PyErr_Occurred()) {
980 PyErr_Format(TestError, "test_buildvalue_N: "
981 "Py_BuildValue(\"%s\") didn't complain", fmt);
982 return -1;
983 }
984 PyErr_Clear();
985 if (Py_REFCNT(arg) != 1) {
986 PyErr_Format(TestError, "test_buildvalue_N: "
987 "arg was not decrefed in failed "
988 "Py_BuildValue(\"%s\")", fmt);
989 return -1;
990 }
991 Py_DECREF(arg);
992 return 0;
993 }
994
995 static PyObject *
test_buildvalue_N(PyObject * self,PyObject * noargs)996 test_buildvalue_N(PyObject *self, PyObject *noargs)
997 {
998 PyObject *arg, *res;
999
1000 arg = PyList_New(0);
1001 if (arg == NULL) {
1002 return NULL;
1003 }
1004 Py_INCREF(arg);
1005 res = Py_BuildValue("N", arg);
1006 if (res == NULL) {
1007 return NULL;
1008 }
1009 if (res != arg) {
1010 return raiseTestError("test_buildvalue_N",
1011 "Py_BuildValue(\"N\") returned wrong result");
1012 }
1013 if (Py_REFCNT(arg) != 2) {
1014 return raiseTestError("test_buildvalue_N",
1015 "arg was not decrefed in Py_BuildValue(\"N\")");
1016 }
1017 Py_DECREF(res);
1018 Py_DECREF(arg);
1019
1020 if (test_buildvalue_N_error("O&N") < 0)
1021 return NULL;
1022 if (test_buildvalue_N_error("(O&N)") < 0)
1023 return NULL;
1024 if (test_buildvalue_N_error("[O&N]") < 0)
1025 return NULL;
1026 if (test_buildvalue_N_error("{O&N}") < 0)
1027 return NULL;
1028 if (test_buildvalue_N_error("{()O&(())N}") < 0)
1029 return NULL;
1030
1031 Py_RETURN_NONE;
1032 }
1033
1034
1035 static PyObject *
get_args(PyObject * self,PyObject * args)1036 get_args(PyObject *self, PyObject *args)
1037 {
1038 if (args == NULL) {
1039 args = Py_None;
1040 }
1041 Py_INCREF(args);
1042 return args;
1043 }
1044
1045 static PyObject *
get_kwargs(PyObject * self,PyObject * args,PyObject * kwargs)1046 get_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
1047 {
1048 if (kwargs == NULL) {
1049 kwargs = Py_None;
1050 }
1051 Py_INCREF(kwargs);
1052 return kwargs;
1053 }
1054
1055 /* Test tuple argument processing */
1056 static PyObject *
getargs_tuple(PyObject * self,PyObject * args)1057 getargs_tuple(PyObject *self, PyObject *args)
1058 {
1059 int a, b, c;
1060 if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
1061 return NULL;
1062 return Py_BuildValue("iii", a, b, c);
1063 }
1064
1065 /* test PyArg_ParseTupleAndKeywords */
getargs_keywords(PyObject * self,PyObject * args,PyObject * kwargs)1066 static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
1067 {
1068 static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
1069 static char *fmt="(ii)i|(i(ii))(iii)i";
1070 int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
1071
1072 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
1073 &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
1074 &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
1075 return NULL;
1076 return Py_BuildValue("iiiiiiiiii",
1077 int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
1078 int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
1079 }
1080
1081 /* Functions to call PyArg_ParseTuple with integer format codes,
1082 and return the result.
1083 */
1084 static PyObject *
getargs_b(PyObject * self,PyObject * args)1085 getargs_b(PyObject *self, PyObject *args)
1086 {
1087 unsigned char value;
1088 if (!PyArg_ParseTuple(args, "b", &value))
1089 return NULL;
1090 return PyLong_FromUnsignedLong((unsigned long)value);
1091 }
1092
1093 static PyObject *
getargs_B(PyObject * self,PyObject * args)1094 getargs_B(PyObject *self, PyObject *args)
1095 {
1096 unsigned char value;
1097 if (!PyArg_ParseTuple(args, "B", &value))
1098 return NULL;
1099 return PyLong_FromUnsignedLong((unsigned long)value);
1100 }
1101
1102 static PyObject *
getargs_h(PyObject * self,PyObject * args)1103 getargs_h(PyObject *self, PyObject *args)
1104 {
1105 short value;
1106 if (!PyArg_ParseTuple(args, "h", &value))
1107 return NULL;
1108 return PyLong_FromLong((long)value);
1109 }
1110
1111 static PyObject *
getargs_H(PyObject * self,PyObject * args)1112 getargs_H(PyObject *self, PyObject *args)
1113 {
1114 unsigned short value;
1115 if (!PyArg_ParseTuple(args, "H", &value))
1116 return NULL;
1117 return PyLong_FromUnsignedLong((unsigned long)value);
1118 }
1119
1120 static PyObject *
getargs_I(PyObject * self,PyObject * args)1121 getargs_I(PyObject *self, PyObject *args)
1122 {
1123 unsigned int value;
1124 if (!PyArg_ParseTuple(args, "I", &value))
1125 return NULL;
1126 return PyLong_FromUnsignedLong((unsigned long)value);
1127 }
1128
1129 static PyObject *
getargs_k(PyObject * self,PyObject * args)1130 getargs_k(PyObject *self, PyObject *args)
1131 {
1132 unsigned long value;
1133 if (!PyArg_ParseTuple(args, "k", &value))
1134 return NULL;
1135 return PyLong_FromUnsignedLong(value);
1136 }
1137
1138 static PyObject *
getargs_i(PyObject * self,PyObject * args)1139 getargs_i(PyObject *self, PyObject *args)
1140 {
1141 int value;
1142 if (!PyArg_ParseTuple(args, "i", &value))
1143 return NULL;
1144 return PyLong_FromLong((long)value);
1145 }
1146
1147 static PyObject *
getargs_l(PyObject * self,PyObject * args)1148 getargs_l(PyObject *self, PyObject *args)
1149 {
1150 long value;
1151 if (!PyArg_ParseTuple(args, "l", &value))
1152 return NULL;
1153 return PyLong_FromLong(value);
1154 }
1155
1156 static PyObject *
getargs_n(PyObject * self,PyObject * args)1157 getargs_n(PyObject *self, PyObject *args)
1158 {
1159 Py_ssize_t value;
1160 if (!PyArg_ParseTuple(args, "n", &value))
1161 return NULL;
1162 return PyInt_FromSsize_t(value);
1163 }
1164
1165 #ifdef HAVE_LONG_LONG
1166 static PyObject *
getargs_L(PyObject * self,PyObject * args)1167 getargs_L(PyObject *self, PyObject *args)
1168 {
1169 PY_LONG_LONG value;
1170 if (!PyArg_ParseTuple(args, "L", &value))
1171 return NULL;
1172 return PyLong_FromLongLong(value);
1173 }
1174
1175 static PyObject *
getargs_K(PyObject * self,PyObject * args)1176 getargs_K(PyObject *self, PyObject *args)
1177 {
1178 unsigned PY_LONG_LONG value;
1179 if (!PyArg_ParseTuple(args, "K", &value))
1180 return NULL;
1181 return PyLong_FromUnsignedLongLong(value);
1182 }
1183 #endif
1184
1185 /* This function not only tests the 'k' getargs code, but also the
1186 PyInt_AsUnsignedLongMask() and PyInt_AsUnsignedLongMask() functions. */
1187 static PyObject *
test_k_code(PyObject * self)1188 test_k_code(PyObject *self)
1189 {
1190 PyObject *tuple, *num;
1191 unsigned long value;
1192
1193 tuple = PyTuple_New(1);
1194 if (tuple == NULL)
1195 return NULL;
1196
1197 /* a number larger than ULONG_MAX even on 64-bit platforms */
1198 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
1199 if (num == NULL)
1200 return NULL;
1201
1202 value = PyInt_AsUnsignedLongMask(num);
1203 if (value != ULONG_MAX)
1204 return raiseTestError("test_k_code",
1205 "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
1206
1207 PyTuple_SET_ITEM(tuple, 0, num);
1208
1209 value = 0;
1210 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
1211 return NULL;
1212 }
1213 if (value != ULONG_MAX)
1214 return raiseTestError("test_k_code",
1215 "k code returned wrong value for long 0xFFF...FFF");
1216
1217 Py_DECREF(num);
1218 num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
1219 if (num == NULL)
1220 return NULL;
1221
1222 value = PyInt_AsUnsignedLongMask(num);
1223 if (value != (unsigned long)-0x42)
1224 return raiseTestError("test_k_code",
1225 "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
1226
1227 PyTuple_SET_ITEM(tuple, 0, num);
1228
1229 value = 0;
1230 if (!PyArg_ParseTuple(tuple, "k:test_k_code", &value)) {
1231 return NULL;
1232 }
1233 if (value != (unsigned long)-0x42)
1234 return raiseTestError("test_k_code",
1235 "k code returned wrong value for long -0xFFF..000042");
1236
1237 Py_DECREF(tuple);
1238 Py_INCREF(Py_None);
1239 return Py_None;
1240 }
1241
1242 static PyObject *
getargs_f(PyObject * self,PyObject * args)1243 getargs_f(PyObject *self, PyObject *args)
1244 {
1245 float f;
1246 if (!PyArg_ParseTuple(args, "f", &f))
1247 return NULL;
1248 return PyFloat_FromDouble(f);
1249 }
1250
1251 static PyObject *
getargs_d(PyObject * self,PyObject * args)1252 getargs_d(PyObject *self, PyObject *args)
1253 {
1254 double d;
1255 if (!PyArg_ParseTuple(args, "d", &d))
1256 return NULL;
1257 return PyFloat_FromDouble(d);
1258 }
1259
1260 static PyObject *
getargs_D(PyObject * self,PyObject * args)1261 getargs_D(PyObject *self, PyObject *args)
1262 {
1263 Py_complex cval;
1264 if (!PyArg_ParseTuple(args, "D", &cval))
1265 return NULL;
1266 return PyComplex_FromCComplex(cval);
1267 }
1268
1269 static PyObject *
getargs_S(PyObject * self,PyObject * args)1270 getargs_S(PyObject *self, PyObject *args)
1271 {
1272 PyObject *obj;
1273 if (!PyArg_ParseTuple(args, "S", &obj))
1274 return NULL;
1275 Py_INCREF(obj);
1276 return obj;
1277 }
1278
1279 static PyObject *
getargs_Y(PyObject * self,PyObject * args)1280 getargs_Y(PyObject *self, PyObject *args)
1281 {
1282 PyObject *obj;
1283 if (!PyArg_ParseTuple(args, "Y", &obj))
1284 return NULL;
1285 Py_INCREF(obj);
1286 return obj;
1287 }
1288
1289 #ifdef Py_USING_UNICODE
1290 static PyObject *
getargs_U(PyObject * self,PyObject * args)1291 getargs_U(PyObject *self, PyObject *args)
1292 {
1293 PyObject *obj;
1294 if (!PyArg_ParseTuple(args, "U", &obj))
1295 return NULL;
1296 Py_INCREF(obj);
1297 return obj;
1298 }
1299 #endif
1300
1301 static PyObject *
getargs_c(PyObject * self,PyObject * args)1302 getargs_c(PyObject *self, PyObject *args)
1303 {
1304 char c;
1305 if (!PyArg_ParseTuple(args, "c", &c))
1306 return NULL;
1307 return PyInt_FromLong((unsigned char)c);
1308 }
1309
1310 static PyObject *
getargs_s(PyObject * self,PyObject * args)1311 getargs_s(PyObject *self, PyObject *args)
1312 {
1313 const char *str;
1314 if (!PyArg_ParseTuple(args, "s", &str))
1315 return NULL;
1316 return PyBytes_FromString(str);
1317 }
1318
1319 static PyObject *
getargs_s_star(PyObject * self,PyObject * args)1320 getargs_s_star(PyObject *self, PyObject *args)
1321 {
1322 Py_buffer buffer;
1323 PyObject *bytes;
1324 if (!PyArg_ParseTuple(args, "s*", &buffer))
1325 return NULL;
1326 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1327 PyBuffer_Release(&buffer);
1328 return bytes;
1329 }
1330
1331 static PyObject *
getargs_s_hash(PyObject * self,PyObject * args)1332 getargs_s_hash(PyObject *self, PyObject *args)
1333 {
1334 const char *str;
1335 int size;
1336 if (!PyArg_ParseTuple(args, "s#", &str, &size))
1337 return NULL;
1338 return PyBytes_FromStringAndSize(str, size);
1339 }
1340
1341 static PyObject *
getargs_t_hash(PyObject * self,PyObject * args)1342 getargs_t_hash(PyObject *self, PyObject *args)
1343 {
1344 const char *str;
1345 int size;
1346 if (!PyArg_ParseTuple(args, "t#", &str, &size))
1347 return NULL;
1348 return PyBytes_FromStringAndSize(str, size);
1349 }
1350
1351 static PyObject *
getargs_z(PyObject * self,PyObject * args)1352 getargs_z(PyObject *self, PyObject *args)
1353 {
1354 const char *str;
1355 if (!PyArg_ParseTuple(args, "z", &str))
1356 return NULL;
1357 if (str != NULL)
1358 return PyBytes_FromString(str);
1359 else
1360 Py_RETURN_NONE;
1361 }
1362
1363 static PyObject *
getargs_z_star(PyObject * self,PyObject * args)1364 getargs_z_star(PyObject *self, PyObject *args)
1365 {
1366 Py_buffer buffer;
1367 PyObject *bytes;
1368 if (!PyArg_ParseTuple(args, "z*", &buffer))
1369 return NULL;
1370 if (buffer.buf != NULL)
1371 bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1372 else {
1373 Py_INCREF(Py_None);
1374 bytes = Py_None;
1375 }
1376 PyBuffer_Release(&buffer);
1377 return bytes;
1378 }
1379
1380 static PyObject *
getargs_z_hash(PyObject * self,PyObject * args)1381 getargs_z_hash(PyObject *self, PyObject *args)
1382 {
1383 const char *str;
1384 int size;
1385 if (!PyArg_ParseTuple(args, "z#", &str, &size))
1386 return NULL;
1387 if (str != NULL)
1388 return PyBytes_FromStringAndSize(str, size);
1389 else
1390 Py_RETURN_NONE;
1391 }
1392
1393 static PyObject *
getargs_w(PyObject * self,PyObject * args)1394 getargs_w(PyObject *self, PyObject *args)
1395 {
1396 char *str;
1397 Py_ssize_t size;
1398
1399 if (!PyArg_ParseTuple(args, "wn", &str, &size))
1400 return NULL;
1401
1402 if (2 <= size) {
1403 str[0] = '[';
1404 str[size-1] = ']';
1405 }
1406
1407 return PyBytes_FromStringAndSize(str, size);
1408 }
1409
1410 static PyObject *
getargs_w_hash(PyObject * self,PyObject * args)1411 getargs_w_hash(PyObject *self, PyObject *args)
1412 {
1413 char *str;
1414 int size;
1415
1416 if (!PyArg_ParseTuple(args, "w#", &str, &size))
1417 return NULL;
1418
1419 if (2 <= size) {
1420 str[0] = '[';
1421 str[size-1] = ']';
1422 }
1423
1424 return PyBytes_FromStringAndSize(str, size);
1425 }
1426
1427 static PyObject *
getargs_w_star(PyObject * self,PyObject * args)1428 getargs_w_star(PyObject *self, PyObject *args)
1429 {
1430 Py_buffer buffer;
1431 PyObject *result;
1432 char *str;
1433
1434 if (!PyArg_ParseTuple(args, "w*", &buffer))
1435 return NULL;
1436
1437 if (2 <= buffer.len) {
1438 str = buffer.buf;
1439 str[0] = '[';
1440 str[buffer.len-1] = ']';
1441 }
1442
1443 result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
1444 PyBuffer_Release(&buffer);
1445 return result;
1446 }
1447
1448 #ifdef Py_USING_UNICODE
1449
1450 static int
_ustrlen(const Py_UNICODE * u)1451 _ustrlen(const Py_UNICODE *u)
1452 {
1453 int i = 0;
1454 const Py_UNICODE *v = u;
1455 while (*v != 0) { i++; v++; }
1456 return i;
1457 }
1458
1459 static PyObject *
getargs_u(PyObject * self,PyObject * args)1460 getargs_u(PyObject *self, PyObject *args)
1461 {
1462 const Py_UNICODE *str;
1463 int size;
1464 if (!PyArg_ParseTuple(args, "u", &str))
1465 return NULL;
1466 size = _ustrlen(str);
1467 return PyUnicode_FromUnicode(str, size);
1468 }
1469
1470 static PyObject *
getargs_u_hash(PyObject * self,PyObject * args)1471 getargs_u_hash(PyObject *self, PyObject *args)
1472 {
1473 const Py_UNICODE *str;
1474 int size;
1475 if (!PyArg_ParseTuple(args, "u#", &str, &size))
1476 return NULL;
1477 return PyUnicode_FromUnicode(str, size);
1478 }
1479
1480 #endif
1481
1482 static PyObject *
getargs_es(PyObject * self,PyObject * args)1483 getargs_es(PyObject *self, PyObject *args)
1484 {
1485 PyObject *arg, *result;
1486 const char *encoding = NULL;
1487 char *str;
1488
1489 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1490 return NULL;
1491 if (!PyArg_Parse(arg, "es", encoding, &str))
1492 return NULL;
1493 result = PyBytes_FromString(str);
1494 PyMem_Free(str);
1495 return result;
1496 }
1497
1498 static PyObject *
getargs_et(PyObject * self,PyObject * args)1499 getargs_et(PyObject *self, PyObject *args)
1500 {
1501 PyObject *arg, *result;
1502 const char *encoding = NULL;
1503 char *str;
1504
1505 if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
1506 return NULL;
1507 if (!PyArg_Parse(arg, "et", encoding, &str))
1508 return NULL;
1509 result = PyBytes_FromString(str);
1510 PyMem_Free(str);
1511 return result;
1512 }
1513
1514 static PyObject *
getargs_es_hash(PyObject * self,PyObject * args)1515 getargs_es_hash(PyObject *self, PyObject *args)
1516 {
1517 PyObject *arg, *result;
1518 const char *encoding = NULL;
1519 PyByteArrayObject *buffer = NULL;
1520 char *str = NULL;
1521 int size;
1522
1523 if (!PyArg_ParseTuple(args, "O|sO!",
1524 &arg, &encoding, &PyByteArray_Type, &buffer))
1525 return NULL;
1526 if (buffer != NULL) {
1527 str = PyByteArray_AS_STRING(buffer);
1528 size = PyByteArray_GET_SIZE(buffer);
1529 }
1530 if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
1531 return NULL;
1532 result = PyBytes_FromStringAndSize(str, size);
1533 if (buffer == NULL)
1534 PyMem_Free(str);
1535 return result;
1536 }
1537
1538 static PyObject *
getargs_et_hash(PyObject * self,PyObject * args)1539 getargs_et_hash(PyObject *self, PyObject *args)
1540 {
1541 PyObject *arg, *result;
1542 const char *encoding = NULL;
1543 PyByteArrayObject *buffer = NULL;
1544 char *str = NULL;
1545 int size;
1546
1547 if (!PyArg_ParseTuple(args, "O|sO!",
1548 &arg, &encoding, &PyByteArray_Type, &buffer))
1549 return NULL;
1550 if (buffer != NULL) {
1551 str = PyByteArray_AS_STRING(buffer);
1552 size = PyByteArray_GET_SIZE(buffer);
1553 }
1554 if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
1555 return NULL;
1556 result = PyBytes_FromStringAndSize(str, size);
1557 if (buffer == NULL)
1558 PyMem_Free(str);
1559 return result;
1560 }
1561
1562 static PyObject *
get_indices(PyObject * self,PyObject * args)1563 get_indices(PyObject *self, PyObject *args)
1564 {
1565 int result;
1566 PySliceObject *slice;
1567 Py_ssize_t length, start, stop, step;
1568
1569 if (!PyArg_ParseTuple(args, "On", &slice, &length))
1570 return NULL;
1571
1572 result = PySlice_GetIndices(slice, length, &start, &stop, &step);
1573
1574 if (PyErr_Occurred()) {
1575 assert(result == -1);
1576 return NULL;
1577 }
1578
1579 if (result == -1) {
1580 Py_RETURN_NONE;
1581 }
1582 return Py_BuildValue("innn", result, start, stop, step);
1583 }
1584
1585 static PyObject *
parse_tuple_and_keywords(PyObject * self,PyObject * args)1586 parse_tuple_and_keywords(PyObject *self, PyObject *args)
1587 {
1588 PyObject *sub_args;
1589 PyObject *sub_kwargs;
1590 const char *sub_format;
1591 PyObject *sub_keywords;
1592
1593 Py_ssize_t i, size;
1594 char *keywords[8 + 1]; /* space for NULL at end */
1595 PyObject *o;
1596
1597 int result;
1598 PyObject *return_value = NULL;
1599
1600 double buffers[8][4]; /* double ensures alignment where necessary */
1601
1602 if (!PyArg_ParseTuple(args, "OOsO:parse_tuple_and_keywords",
1603 &sub_args, &sub_kwargs,
1604 &sub_format, &sub_keywords))
1605 return NULL;
1606
1607 if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) {
1608 PyErr_SetString(PyExc_ValueError,
1609 "parse_tuple_and_keywords: sub_keywords must be either list or tuple");
1610 return NULL;
1611 }
1612
1613 memset(buffers, 0, sizeof(buffers));
1614 memset(keywords, 0, sizeof(keywords));
1615
1616 size = PySequence_Fast_GET_SIZE(sub_keywords);
1617 if (size > 8) {
1618 PyErr_SetString(PyExc_ValueError,
1619 "parse_tuple_and_keywords: too many keywords in sub_keywords");
1620 goto exit;
1621 }
1622
1623 for (i = 0; i < size; i++) {
1624 o = PySequence_Fast_GET_ITEM(sub_keywords, i);
1625 keywords[i] = PyString_AsString(o);
1626 if (keywords[i] == NULL) {
1627 goto exit;
1628 }
1629 }
1630
1631 result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs,
1632 sub_format, keywords,
1633 buffers + 0, buffers + 1, buffers + 2, buffers + 3,
1634 buffers + 4, buffers + 5, buffers + 6, buffers + 7);
1635
1636 if (result) {
1637 return_value = Py_None;
1638 Py_INCREF(Py_None);
1639 }
1640
1641 exit:
1642 return return_value;
1643 }
1644
1645 #ifdef Py_USING_UNICODE
1646
1647 static volatile int x;
1648
1649 /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
1650 of an error.
1651 */
1652 static PyObject *
test_u_code(PyObject * self)1653 test_u_code(PyObject *self)
1654 {
1655 PyObject *tuple, *obj;
1656 Py_UNICODE *value;
1657 int len;
1658
1659 /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
1660 /* Just use the macro and check that it compiles */
1661 x = Py_UNICODE_ISSPACE(25);
1662
1663 tuple = PyTuple_New(1);
1664 if (tuple == NULL)
1665 return NULL;
1666
1667 obj = PyUnicode_Decode("test", strlen("test"),
1668 "ascii", NULL);
1669 if (obj == NULL)
1670 return NULL;
1671
1672 PyTuple_SET_ITEM(tuple, 0, obj);
1673
1674 value = 0;
1675 if (!PyArg_ParseTuple(tuple, "u:test_u_code", &value)) {
1676 return NULL;
1677 }
1678 if (value != PyUnicode_AS_UNICODE(obj))
1679 return raiseTestError("test_u_code",
1680 "u code returned wrong value for u'test'");
1681 value = 0;
1682 if (!PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len)) {
1683 return NULL;
1684 }
1685 if (value != PyUnicode_AS_UNICODE(obj) ||
1686 len != PyUnicode_GET_SIZE(obj))
1687 return raiseTestError("test_u_code",
1688 "u# code returned wrong values for u'test'");
1689
1690 Py_DECREF(tuple);
1691 Py_INCREF(Py_None);
1692 return Py_None;
1693 }
1694
1695 static PyObject *
test_widechar(PyObject * self)1696 test_widechar(PyObject *self)
1697 {
1698 #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
1699 const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
1700 size_t wtextlen = 1;
1701 #else
1702 const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
1703 size_t wtextlen = 2;
1704 #endif
1705 PyObject *wide, *utf8;
1706
1707 wide = PyUnicode_FromWideChar(wtext, wtextlen);
1708 if (wide == NULL)
1709 return NULL;
1710
1711 utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
1712 if (utf8 == NULL) {
1713 Py_DECREF(wide);
1714 return NULL;
1715 }
1716
1717 if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
1718 Py_DECREF(wide);
1719 Py_DECREF(utf8);
1720 return raiseTestError("test_widechar",
1721 "wide string and utf8 string have different length");
1722 }
1723 if (PyUnicode_Compare(wide, utf8)) {
1724 Py_DECREF(wide);
1725 Py_DECREF(utf8);
1726 if (PyErr_Occurred())
1727 return NULL;
1728 return raiseTestError("test_widechar",
1729 "wide string and utf8 string are differents");
1730 }
1731
1732 Py_DECREF(wide);
1733 Py_DECREF(utf8);
1734 Py_RETURN_NONE;
1735 }
1736
1737 static PyObject *
unicode_encodedecimal(PyObject * self,PyObject * args)1738 unicode_encodedecimal(PyObject *self, PyObject *args)
1739 {
1740 Py_UNICODE *unicode;
1741 int length;
1742 char *errors = NULL;
1743 PyObject *decimal;
1744 Py_ssize_t decimal_length, new_length;
1745 int res;
1746
1747 if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors))
1748 return NULL;
1749
1750 decimal_length = length * 10; /* len('') */
1751 decimal = PyBytes_FromStringAndSize(NULL, decimal_length);
1752 if (decimal == NULL)
1753 return NULL;
1754
1755 res = PyUnicode_EncodeDecimal(unicode, length,
1756 PyBytes_AS_STRING(decimal),
1757 errors);
1758 if (res < 0) {
1759 Py_DECREF(decimal);
1760 return NULL;
1761 }
1762
1763 new_length = strlen(PyBytes_AS_STRING(decimal));
1764 assert(new_length <= decimal_length);
1765 res = _PyBytes_Resize(&decimal, new_length);
1766 if (res < 0)
1767 return NULL;
1768
1769 return decimal;
1770 }
1771
1772 static PyObject *
test_empty_argparse(PyObject * self)1773 test_empty_argparse(PyObject *self)
1774 {
1775 /* Test that formats can begin with '|'. See issue #4720. */
1776 PyObject *tuple, *dict = NULL;
1777 static char *kwlist[] = {NULL};
1778 int result;
1779 tuple = PyTuple_New(0);
1780 if (!tuple)
1781 return NULL;
1782 if (!(result = PyArg_ParseTuple(tuple, "|:test_empty_argparse"))) {
1783 goto done;
1784 }
1785 dict = PyDict_New();
1786 if (!dict)
1787 goto done;
1788 result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
1789 done:
1790 Py_DECREF(tuple);
1791 Py_XDECREF(dict);
1792 if (!result) {
1793 return NULL;
1794 }
1795 else {
1796 Py_RETURN_NONE;
1797 }
1798 }
1799
1800 static PyObject *
codec_incrementalencoder(PyObject * self,PyObject * args)1801 codec_incrementalencoder(PyObject *self, PyObject *args)
1802 {
1803 const char *encoding, *errors = NULL;
1804 if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
1805 &encoding, &errors))
1806 return NULL;
1807 return PyCodec_IncrementalEncoder(encoding, errors);
1808 }
1809
1810 static PyObject *
codec_incrementaldecoder(PyObject * self,PyObject * args)1811 codec_incrementaldecoder(PyObject *self, PyObject *args)
1812 {
1813 const char *encoding, *errors = NULL;
1814 if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
1815 &encoding, &errors))
1816 return NULL;
1817 return PyCodec_IncrementalDecoder(encoding, errors);
1818 }
1819
1820 #endif
1821
1822 /* Simple test of _PyLong_NumBits and _PyLong_Sign. */
1823 static PyObject *
test_long_numbits(PyObject * self)1824 test_long_numbits(PyObject *self)
1825 {
1826 struct triple {
1827 long input;
1828 size_t nbits;
1829 int sign;
1830 } testcases[] = {{0, 0, 0},
1831 {1L, 1, 1},
1832 {-1L, 1, -1},
1833 {2L, 2, 1},
1834 {-2L, 2, -1},
1835 {3L, 2, 1},
1836 {-3L, 2, -1},
1837 {4L, 3, 1},
1838 {-4L, 3, -1},
1839 {0x7fffL, 15, 1}, /* one Python long digit */
1840 {-0x7fffL, 15, -1},
1841 {0xffffL, 16, 1},
1842 {-0xffffL, 16, -1},
1843 {0xfffffffL, 28, 1},
1844 {-0xfffffffL, 28, -1}};
1845 int i;
1846
1847 for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
1848 PyObject *plong = PyLong_FromLong(testcases[i].input);
1849 size_t nbits = _PyLong_NumBits(plong);
1850 int sign = _PyLong_Sign(plong);
1851
1852 Py_DECREF(plong);
1853 if (nbits != testcases[i].nbits)
1854 return raiseTestError("test_long_numbits",
1855 "wrong result for _PyLong_NumBits");
1856 if (sign != testcases[i].sign)
1857 return raiseTestError("test_long_numbits",
1858 "wrong result for _PyLong_Sign");
1859 }
1860 Py_INCREF(Py_None);
1861 return Py_None;
1862 }
1863
1864 /* Example passing NULLs to PyObject_Str(NULL) and PyObject_Unicode(NULL). */
1865
1866 static PyObject *
test_null_strings(PyObject * self)1867 test_null_strings(PyObject *self)
1868 {
1869 PyObject *o1 = PyObject_Str(NULL);
1870 #ifdef Py_USING_UNICODE
1871 PyObject *o2 = PyObject_Unicode(NULL);
1872 #else
1873 PyObject *o2 = PyObject_Str(NULL);
1874 #endif
1875 PyObject *tuple = PyTuple_Pack(2, o1, o2);
1876 Py_XDECREF(o1);
1877 Py_XDECREF(o2);
1878 return tuple;
1879 }
1880
1881 static PyObject *
raise_exception(PyObject * self,PyObject * args)1882 raise_exception(PyObject *self, PyObject *args)
1883 {
1884 PyObject *exc;
1885 PyObject *exc_args, *v;
1886 int num_args, i;
1887
1888 if (!PyArg_ParseTuple(args, "Oi:raise_exception",
1889 &exc, &num_args))
1890 return NULL;
1891 if (!PyExceptionClass_Check(exc)) {
1892 PyErr_Format(PyExc_TypeError, "an exception class is required");
1893 return NULL;
1894 }
1895
1896 exc_args = PyTuple_New(num_args);
1897 if (exc_args == NULL)
1898 return NULL;
1899 for (i = 0; i < num_args; ++i) {
1900 v = PyInt_FromLong(i);
1901 if (v == NULL) {
1902 Py_DECREF(exc_args);
1903 return NULL;
1904 }
1905 PyTuple_SET_ITEM(exc_args, i, v);
1906 }
1907 PyErr_SetObject(exc, exc_args);
1908 Py_DECREF(exc_args);
1909 return NULL;
1910 }
1911
1912 static PyObject *
set_errno(PyObject * self,PyObject * args)1913 set_errno(PyObject *self, PyObject *args)
1914 {
1915 int new_errno;
1916
1917 if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
1918 return NULL;
1919
1920 errno = new_errno;
1921 Py_RETURN_NONE;
1922 }
1923
1924 #if defined(Py_USING_UNICODE) && !defined(Py_BUILD_CORE)
1925 static int test_run_counter = 0;
1926
1927 static PyObject *
test_datetime_capi(PyObject * self,PyObject * args)1928 test_datetime_capi(PyObject *self, PyObject *args) {
1929 if (PyDateTimeAPI) {
1930 if (test_run_counter) {
1931 /* Probably regrtest.py -R */
1932 Py_RETURN_NONE;
1933 }
1934 else {
1935 PyErr_SetString(PyExc_AssertionError,
1936 "PyDateTime_CAPI somehow initialized");
1937 return NULL;
1938 }
1939 }
1940 test_run_counter++;
1941 PyDateTime_IMPORT;
1942 if (PyDateTimeAPI)
1943 Py_RETURN_NONE;
1944 else
1945 return NULL;
1946 }
1947 #endif
1948
1949
1950 #ifdef WITH_THREAD
1951
1952 /* test_thread_state spawns a thread of its own, and that thread releases
1953 * `thread_done` when it's finished. The driver code has to know when the
1954 * thread finishes, because the thread uses a PyObject (the callable) that
1955 * may go away when the driver finishes. The former lack of this explicit
1956 * synchronization caused rare segfaults, so rare that they were seen only
1957 * on a Mac buildbot (although they were possible on any box).
1958 */
1959 static PyThread_type_lock thread_done = NULL;
1960
1961 static int
_make_call(void * callable)1962 _make_call(void *callable)
1963 {
1964 PyObject *rc;
1965 int success;
1966 PyGILState_STATE s = PyGILState_Ensure();
1967 rc = PyObject_CallFunction((PyObject *)callable, "");
1968 success = (rc != NULL);
1969 Py_XDECREF(rc);
1970 PyGILState_Release(s);
1971 return success;
1972 }
1973
1974 /* Same thing, but releases `thread_done` when it returns. This variant
1975 * should be called only from threads spawned by test_thread_state().
1976 */
1977 static void
_make_call_from_thread(void * callable)1978 _make_call_from_thread(void *callable)
1979 {
1980 _make_call(callable);
1981 PyThread_release_lock(thread_done);
1982 }
1983
1984 static PyObject *
test_thread_state(PyObject * self,PyObject * args)1985 test_thread_state(PyObject *self, PyObject *args)
1986 {
1987 PyObject *fn;
1988 int success = 1;
1989
1990 if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
1991 return NULL;
1992
1993 if (!PyCallable_Check(fn)) {
1994 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
1995 fn->ob_type->tp_name);
1996 return NULL;
1997 }
1998
1999 /* Ensure Python is set up for threading */
2000 PyEval_InitThreads();
2001 thread_done = PyThread_allocate_lock();
2002 if (thread_done == NULL)
2003 return PyErr_NoMemory();
2004 PyThread_acquire_lock(thread_done, 1);
2005
2006 /* Start a new thread with our callback. */
2007 PyThread_start_new_thread(_make_call_from_thread, fn);
2008 /* Make the callback with the thread lock held by this thread */
2009 success &= _make_call(fn);
2010 /* Do it all again, but this time with the thread-lock released */
2011 Py_BEGIN_ALLOW_THREADS
2012 success &= _make_call(fn);
2013 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2014 Py_END_ALLOW_THREADS
2015
2016 /* And once more with and without a thread
2017 XXX - should use a lock and work out exactly what we are trying
2018 to test <wink>
2019 */
2020 Py_BEGIN_ALLOW_THREADS
2021 PyThread_start_new_thread(_make_call_from_thread, fn);
2022 success &= _make_call(fn);
2023 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
2024 Py_END_ALLOW_THREADS
2025
2026 /* Release lock we acquired above. This is required on HP-UX. */
2027 PyThread_release_lock(thread_done);
2028
2029 PyThread_free_lock(thread_done);
2030 if (!success)
2031 return NULL;
2032 Py_RETURN_NONE;
2033 }
2034
2035 /* test Py_AddPendingCalls using threads */
_pending_callback(void * arg)2036 static int _pending_callback(void *arg)
2037 {
2038 /* we assume the argument is callable object to which we own a reference */
2039 PyObject *callable = (PyObject *)arg;
2040 PyObject *r = PyObject_CallObject(callable, NULL);
2041 Py_DECREF(callable);
2042 Py_XDECREF(r);
2043 return r != NULL ? 0 : -1;
2044 }
2045
2046 /* The following requests n callbacks to _pending_callback. It can be
2047 * run from any python thread.
2048 */
2049 static PyObject *
pending_threadfunc(PyObject * self,PyObject * arg)2050 pending_threadfunc(PyObject *self, PyObject *arg)
2051 {
2052 PyObject *callable;
2053 int r;
2054 if (PyArg_ParseTuple(arg, "O", &callable) == 0)
2055 return NULL;
2056
2057 /* create the reference for the callbackwhile we hold the lock */
2058 Py_INCREF(callable);
2059
2060 Py_BEGIN_ALLOW_THREADS
2061 r = Py_AddPendingCall(&_pending_callback, callable);
2062 Py_END_ALLOW_THREADS
2063
2064 if (r<0) {
2065 Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
2066 Py_INCREF(Py_False);
2067 return Py_False;
2068 }
2069 Py_INCREF(Py_True);
2070 return Py_True;
2071 }
2072 #endif
2073
2074 /* Some tests of PyString_FromFormat(). This needs more tests. */
2075 static PyObject *
test_string_from_format(PyObject * self,PyObject * args)2076 test_string_from_format(PyObject *self, PyObject *args)
2077 {
2078 PyObject *result;
2079 char *msg;
2080
2081 #define CHECK_1_FORMAT(FORMAT, TYPE) \
2082 result = PyString_FromFormat(FORMAT, (TYPE)1); \
2083 if (result == NULL) \
2084 return NULL; \
2085 if (strcmp(PyString_AsString(result), "1")) { \
2086 msg = FORMAT " failed at 1"; \
2087 goto Fail; \
2088 } \
2089 Py_DECREF(result)
2090
2091 CHECK_1_FORMAT("%d", int);
2092 CHECK_1_FORMAT("%ld", long);
2093 /* The z width modifier was added in Python 2.5. */
2094 CHECK_1_FORMAT("%zd", Py_ssize_t);
2095
2096 /* The u type code was added in Python 2.5. */
2097 CHECK_1_FORMAT("%u", unsigned int);
2098 CHECK_1_FORMAT("%lu", unsigned long);
2099 CHECK_1_FORMAT("%zu", size_t);
2100
2101 /* "%lld" and "%llu" support added in Python 2.7. */
2102 #ifdef HAVE_LONG_LONG
2103 CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
2104 CHECK_1_FORMAT("%lld", PY_LONG_LONG);
2105 #endif
2106
2107 Py_RETURN_NONE;
2108
2109 Fail:
2110 Py_XDECREF(result);
2111 return raiseTestError("test_string_from_format", msg);
2112
2113 #undef CHECK_1_FORMAT
2114 }
2115
2116 /* Coverage testing of capsule objects. */
2117
2118 static const char *capsule_name = "capsule name";
2119 static char *capsule_pointer = "capsule pointer";
2120 static char *capsule_context = "capsule context";
2121 static const char *capsule_error = NULL;
2122 static int
2123 capsule_destructor_call_count = 0;
2124
2125 static void
capsule_destructor(PyObject * o)2126 capsule_destructor(PyObject *o) {
2127 capsule_destructor_call_count++;
2128 if (PyCapsule_GetContext(o) != capsule_context) {
2129 capsule_error = "context did not match in destructor!";
2130 } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
2131 capsule_error = "destructor did not match in destructor! (woah!)";
2132 } else if (PyCapsule_GetName(o) != capsule_name) {
2133 capsule_error = "name did not match in destructor!";
2134 } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
2135 capsule_error = "pointer did not match in destructor!";
2136 }
2137 }
2138
2139 typedef struct {
2140 char *name;
2141 char *module;
2142 char *attribute;
2143 } known_capsule;
2144
2145 static PyObject *
test_capsule(PyObject * self,PyObject * args)2146 test_capsule(PyObject *self, PyObject *args)
2147 {
2148 PyObject *object;
2149 const char *error = NULL;
2150 void *pointer;
2151 void *pointer2;
2152 known_capsule known_capsules[] = {
2153 #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
2154 KNOWN_CAPSULE("_socket", "CAPI"),
2155 KNOWN_CAPSULE("_curses", "_C_API"),
2156 KNOWN_CAPSULE("datetime", "datetime_CAPI"),
2157 { NULL, NULL },
2158 };
2159 known_capsule *known = &known_capsules[0];
2160
2161 #define FAIL(x) { error = (x); goto exit; }
2162
2163 #define CHECK_DESTRUCTOR \
2164 if (capsule_error) { \
2165 FAIL(capsule_error); \
2166 } \
2167 else if (!capsule_destructor_call_count) { \
2168 FAIL("destructor not called!"); \
2169 } \
2170 capsule_destructor_call_count = 0; \
2171
2172 object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
2173 PyCapsule_SetContext(object, capsule_context);
2174 capsule_destructor(object);
2175 CHECK_DESTRUCTOR;
2176 Py_DECREF(object);
2177 CHECK_DESTRUCTOR;
2178
2179 object = PyCapsule_New(known, "ignored", NULL);
2180 PyCapsule_SetPointer(object, capsule_pointer);
2181 PyCapsule_SetName(object, capsule_name);
2182 PyCapsule_SetDestructor(object, capsule_destructor);
2183 PyCapsule_SetContext(object, capsule_context);
2184 capsule_destructor(object);
2185 CHECK_DESTRUCTOR;
2186 /* intentionally access using the wrong name */
2187 pointer2 = PyCapsule_GetPointer(object, "the wrong name");
2188 if (!PyErr_Occurred()) {
2189 FAIL("PyCapsule_GetPointer should have failed but did not!");
2190 }
2191 PyErr_Clear();
2192 if (pointer2) {
2193 if (pointer2 == capsule_pointer) {
2194 FAIL("PyCapsule_GetPointer should not have"
2195 " returned the internal pointer!");
2196 } else {
2197 FAIL("PyCapsule_GetPointer should have "
2198 "returned NULL pointer but did not!");
2199 }
2200 }
2201 PyCapsule_SetDestructor(object, NULL);
2202 Py_DECREF(object);
2203 if (capsule_destructor_call_count) {
2204 FAIL("destructor called when it should not have been!");
2205 }
2206
2207 for (known = &known_capsules[0]; known->module != NULL; known++) {
2208 /* yeah, ordinarily I wouldn't do this either,
2209 but it's fine for this test harness.
2210 */
2211 static char buffer[256];
2212 #undef FAIL
2213 #define FAIL(x) \
2214 { \
2215 sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
2216 x, known->module, known->attribute); \
2217 error = buffer; \
2218 goto exit; \
2219 } \
2220
2221 PyObject *module = PyImport_ImportModule(known->module);
2222 if (module) {
2223 pointer = PyCapsule_Import(known->name, 0);
2224 if (!pointer) {
2225 Py_DECREF(module);
2226 FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
2227 }
2228 object = PyObject_GetAttrString(module, known->attribute);
2229 if (!object) {
2230 Py_DECREF(module);
2231 return NULL;
2232 }
2233 pointer2 = PyCapsule_GetPointer(object,
2234 "weebles wobble but they don't fall down");
2235 if (!PyErr_Occurred()) {
2236 Py_DECREF(object);
2237 Py_DECREF(module);
2238 FAIL("PyCapsule_GetPointer should have failed but did not!");
2239 }
2240 PyErr_Clear();
2241 if (pointer2) {
2242 Py_DECREF(module);
2243 Py_DECREF(object);
2244 if (pointer2 == pointer) {
2245 FAIL("PyCapsule_GetPointer should not have"
2246 " returned its internal pointer!");
2247 } else {
2248 FAIL("PyCapsule_GetPointer should have"
2249 " returned NULL pointer but did not!");
2250 }
2251 }
2252 Py_DECREF(object);
2253 Py_DECREF(module);
2254 }
2255 else
2256 PyErr_Clear();
2257 }
2258
2259 exit:
2260 if (error) {
2261 return raiseTestError("test_capsule", error);
2262 }
2263 Py_RETURN_NONE;
2264 #undef FAIL
2265 }
2266
2267 /* This is here to provide a docstring for test_descr. */
2268 static PyObject *
test_with_docstring(PyObject * self)2269 test_with_docstring(PyObject *self)
2270 {
2271 Py_RETURN_NONE;
2272 }
2273
2274 /* To test the format of tracebacks as printed out. */
2275 static PyObject *
traceback_print(PyObject * self,PyObject * args)2276 traceback_print(PyObject *self, PyObject *args)
2277 {
2278 PyObject *file;
2279 PyObject *traceback;
2280 int result;
2281
2282 if (!PyArg_ParseTuple(args, "OO:traceback_print",
2283 &traceback, &file))
2284 return NULL;
2285
2286 result = PyTraceBack_Print(traceback, file);
2287 if (result < 0)
2288 return NULL;
2289 Py_RETURN_NONE;
2290 }
2291
2292 /* To test that the result of PyCode_NewEmpty has the right members. */
2293 static PyObject *
code_newempty(PyObject * self,PyObject * args)2294 code_newempty(PyObject *self, PyObject *args)
2295 {
2296 const char *filename;
2297 const char *funcname;
2298 int firstlineno;
2299
2300 if (!PyArg_ParseTuple(args, "ssi:code_newempty",
2301 &filename, &funcname, &firstlineno))
2302 return NULL;
2303
2304 return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
2305 }
2306
2307 /* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
2308 Run via Lib/test/test_exceptions.py */
2309 static PyObject *
make_exception_with_doc(PyObject * self,PyObject * args,PyObject * kwargs)2310 make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
2311 {
2312 char *name;
2313 char *doc = NULL;
2314 PyObject *base = NULL;
2315 PyObject *dict = NULL;
2316
2317 static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
2318
2319 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2320 "s|sOO:make_exception_with_doc", kwlist,
2321 &name, &doc, &base, &dict))
2322 return NULL;
2323
2324 return PyErr_NewExceptionWithDoc(name, doc, base, dict);
2325 }
2326
2327 static PyObject *
sequence_delitem(PyObject * self,PyObject * args)2328 sequence_delitem(PyObject *self, PyObject *args)
2329 {
2330 PyObject *seq;
2331 Py_ssize_t i;
2332
2333 if (!PyArg_ParseTuple(args, "On", &seq, &i))
2334 return NULL;
2335 if (PySequence_DelItem(seq, i) < 0)
2336 return NULL;
2337 Py_RETURN_NONE;
2338 }
2339
2340 #ifdef WITH_THREAD
2341 typedef struct {
2342 PyThread_type_lock start_event;
2343 PyThread_type_lock exit_event;
2344 PyObject *callback;
2345 } test_c_thread_t;
2346
2347 static void
temporary_c_thread(void * data)2348 temporary_c_thread(void *data)
2349 {
2350 test_c_thread_t *test_c_thread = data;
2351 PyGILState_STATE state;
2352 PyObject *res;
2353
2354 PyThread_release_lock(test_c_thread->start_event);
2355
2356 /* Allocate a Python thread state for this thread */
2357 state = PyGILState_Ensure();
2358
2359 res = PyObject_CallFunction(test_c_thread->callback, "", NULL);
2360 Py_CLEAR(test_c_thread->callback);
2361
2362 if (res == NULL) {
2363 PyErr_Print();
2364 }
2365 else {
2366 Py_DECREF(res);
2367 }
2368
2369 /* Destroy the Python thread state for this thread */
2370 PyGILState_Release(state);
2371
2372 PyThread_release_lock(test_c_thread->exit_event);
2373
2374 PyThread_exit_thread();
2375 }
2376
2377 static PyObject *
call_in_temporary_c_thread(PyObject * self,PyObject * callback)2378 call_in_temporary_c_thread(PyObject *self, PyObject *callback)
2379 {
2380 PyObject *res = NULL;
2381 test_c_thread_t test_c_thread;
2382 long thread;
2383
2384 PyEval_InitThreads();
2385
2386 test_c_thread.start_event = PyThread_allocate_lock();
2387 test_c_thread.exit_event = PyThread_allocate_lock();
2388 test_c_thread.callback = NULL;
2389 if (!test_c_thread.start_event || !test_c_thread.exit_event) {
2390 PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
2391 goto exit;
2392 }
2393
2394 Py_INCREF(callback);
2395 test_c_thread.callback = callback;
2396
2397 PyThread_acquire_lock(test_c_thread.start_event, 1);
2398 PyThread_acquire_lock(test_c_thread.exit_event, 1);
2399
2400 thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
2401 if (thread == -1) {
2402 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
2403 PyThread_release_lock(test_c_thread.start_event);
2404 PyThread_release_lock(test_c_thread.exit_event);
2405 goto exit;
2406 }
2407
2408 PyThread_acquire_lock(test_c_thread.start_event, 1);
2409 PyThread_release_lock(test_c_thread.start_event);
2410
2411 Py_BEGIN_ALLOW_THREADS
2412 PyThread_acquire_lock(test_c_thread.exit_event, 1);
2413 PyThread_release_lock(test_c_thread.exit_event);
2414 Py_END_ALLOW_THREADS
2415
2416 Py_INCREF(Py_None);
2417 res = Py_None;
2418
2419 exit:
2420 Py_CLEAR(test_c_thread.callback);
2421 if (test_c_thread.start_event)
2422 PyThread_free_lock(test_c_thread.start_event);
2423 if (test_c_thread.exit_event)
2424 PyThread_free_lock(test_c_thread.exit_event);
2425 return res;
2426 }
2427 #endif /* WITH_THREAD */
2428
2429 /* marshal */
2430
2431 static PyObject*
pymarshal_write_long_to_file(PyObject * self,PyObject * args)2432 pymarshal_write_long_to_file(PyObject* self, PyObject *args)
2433 {
2434 long value;
2435 char *filename;
2436 int version;
2437 FILE *fp;
2438
2439 if (!PyArg_ParseTuple(args, "lsi:pymarshal_write_long_to_file",
2440 &value, &filename, &version))
2441 return NULL;
2442
2443 fp = fopen(filename, "wb");
2444 if (fp == NULL) {
2445 PyErr_SetFromErrno(PyExc_OSError);
2446 return NULL;
2447 }
2448
2449 PyMarshal_WriteLongToFile(value, fp, version);
2450
2451 fclose(fp);
2452 if (PyErr_Occurred())
2453 return NULL;
2454 Py_RETURN_NONE;
2455 }
2456
2457 static PyObject*
pymarshal_write_object_to_file(PyObject * self,PyObject * args)2458 pymarshal_write_object_to_file(PyObject* self, PyObject *args)
2459 {
2460 PyObject *obj;
2461 char *filename;
2462 int version;
2463 FILE *fp;
2464
2465 if (!PyArg_ParseTuple(args, "Osi:pymarshal_write_object_to_file",
2466 &obj, &filename, &version))
2467 return NULL;
2468
2469 fp = fopen(filename, "wb");
2470 if (fp == NULL) {
2471 PyErr_SetFromErrno(PyExc_OSError);
2472 return NULL;
2473 }
2474
2475 PyMarshal_WriteObjectToFile(obj, fp, version);
2476
2477 fclose(fp);
2478 if (PyErr_Occurred())
2479 return NULL;
2480 Py_RETURN_NONE;
2481 }
2482
2483 static PyObject*
pymarshal_read_short_from_file(PyObject * self,PyObject * args)2484 pymarshal_read_short_from_file(PyObject* self, PyObject *args)
2485 {
2486 int value;
2487 long pos;
2488 char *filename;
2489 FILE *fp;
2490
2491 if (!PyArg_ParseTuple(args, "s:pymarshal_read_short_from_file", &filename))
2492 return NULL;
2493
2494 fp = fopen(filename, "rb");
2495 if (fp == NULL) {
2496 PyErr_SetFromErrno(PyExc_OSError);
2497 return NULL;
2498 }
2499
2500 value = PyMarshal_ReadShortFromFile(fp);
2501 pos = ftell(fp);
2502
2503 fclose(fp);
2504 if (PyErr_Occurred())
2505 return NULL;
2506 return Py_BuildValue("il", value, pos);
2507 }
2508
2509 static PyObject*
pymarshal_read_long_from_file(PyObject * self,PyObject * args)2510 pymarshal_read_long_from_file(PyObject* self, PyObject *args)
2511 {
2512 long value, pos;
2513 char *filename;
2514 FILE *fp;
2515
2516 if (!PyArg_ParseTuple(args, "s:pymarshal_read_long_from_file", &filename))
2517 return NULL;
2518
2519 fp = fopen(filename, "rb");
2520 if (fp == NULL) {
2521 PyErr_SetFromErrno(PyExc_OSError);
2522 return NULL;
2523 }
2524
2525 value = PyMarshal_ReadLongFromFile(fp);
2526 pos = ftell(fp);
2527
2528 fclose(fp);
2529 if (PyErr_Occurred())
2530 return NULL;
2531 return Py_BuildValue("ll", value, pos);
2532 }
2533
2534 static PyObject*
pymarshal_read_last_object_from_file(PyObject * self,PyObject * args)2535 pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
2536 {
2537 PyObject *obj;
2538 long pos;
2539 char *filename;
2540 FILE *fp;
2541
2542 if (!PyArg_ParseTuple(args, "s:pymarshal_read_last_object_from_file", &filename))
2543 return NULL;
2544
2545 fp = fopen(filename, "rb");
2546 if (fp == NULL) {
2547 PyErr_SetFromErrno(PyExc_OSError);
2548 return NULL;
2549 }
2550
2551 obj = PyMarshal_ReadLastObjectFromFile(fp);
2552 pos = ftell(fp);
2553
2554 fclose(fp);
2555 return Py_BuildValue("Nl", obj, pos);
2556 }
2557
2558 static PyObject*
pymarshal_read_object_from_file(PyObject * self,PyObject * args)2559 pymarshal_read_object_from_file(PyObject* self, PyObject *args)
2560 {
2561 PyObject *obj;
2562 long pos;
2563 char *filename;
2564 FILE *fp;
2565
2566 if (!PyArg_ParseTuple(args, "s:pymarshal_read_object_from_file", &filename))
2567 return NULL;
2568
2569 fp = fopen(filename, "rb");
2570 if (fp == NULL) {
2571 PyErr_SetFromErrno(PyExc_OSError);
2572 return NULL;
2573 }
2574
2575 obj = PyMarshal_ReadObjectFromFile(fp);
2576 pos = ftell(fp);
2577
2578 fclose(fp);
2579 return Py_BuildValue("Nl", obj, pos);
2580 }
2581
2582 static PyObject*
test_raise_signal(PyObject * self,PyObject * args)2583 test_raise_signal(PyObject* self, PyObject *args)
2584 {
2585 int signum, err;
2586
2587 if (!PyArg_ParseTuple(args, "i:raise_signal", &signum)) {
2588 return NULL;
2589 }
2590
2591 err = raise(signum);
2592 if (err)
2593 return PyErr_SetFromErrno(PyExc_OSError);
2594
2595 if (PyErr_CheckSignals() < 0)
2596 return NULL;
2597
2598 Py_RETURN_NONE;
2599 }
2600
2601
2602 #ifdef MS_WINDOWS
2603 static PyObject*
msvcrt_CrtSetReportMode(PyObject * self,PyObject * args)2604 msvcrt_CrtSetReportMode(PyObject* self, PyObject *args)
2605 {
2606 int type, mode;
2607 int res;
2608
2609 if (!PyArg_ParseTuple(args, "ii:CrtSetReportMode", &type, &mode)) {
2610 return NULL;
2611 }
2612
2613 res = _CrtSetReportMode(type, mode);
2614 if (res == -1) {
2615 PyErr_SetFromErrno(PyExc_OSError);
2616 return NULL;
2617 }
2618 return PyInt_FromLong(res);
2619 }
2620
2621
2622 static PyObject*
msvcrt_CrtSetReportFile(PyObject * self,PyObject * args)2623 msvcrt_CrtSetReportFile(PyObject* self, PyObject *args)
2624 {
2625 int type, file;
2626 long res;
2627
2628 if (!PyArg_ParseTuple(args, "ii:CrtSetReportFile", &type, &file)) {
2629 return NULL;
2630 }
2631
2632 res = (long)_CrtSetReportFile(type, (_HFILE)file);
2633
2634 return PyInt_FromLong(res);
2635 }
2636 #endif
2637
2638
2639 #ifdef W_STOPCODE
2640 static PyObject*
py_w_stopcode(PyObject * self,PyObject * args)2641 py_w_stopcode(PyObject *self, PyObject *args)
2642 {
2643 int sig, status;
2644 if (!PyArg_ParseTuple(args, "i", &sig)) {
2645 return NULL;
2646 }
2647 status = W_STOPCODE(sig);
2648 return PyLong_FromLong(status);
2649 }
2650 #endif
2651
2652
2653 /* Read memory from NULL (address 0) to raise a SIGSEGV or SIGBUS signal
2654 depending on the platform. This function is used by
2655 test.support._crash_python() to "crash" Python. */
2656 static PyObject *
read_null(PyObject * self,PyObject * args)2657 read_null(PyObject *self, PyObject *args)
2658 {
2659 volatile int *x;
2660 volatile int y;
2661
2662 x = NULL;
2663 y = *x;
2664 return PyLong_FromLong(y);
2665
2666 }
2667
2668
2669 static PyMethodDef TestMethods[] = {
2670 {"raise_exception", raise_exception, METH_VARARGS},
2671 {"set_errno", set_errno, METH_VARARGS},
2672 {"test_config", (PyCFunction)test_config, METH_NOARGS},
2673 #if defined(Py_USING_UNICODE) && !defined(Py_BUILD_CORE)
2674 {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
2675 #endif
2676 {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
2677 {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
2678 {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
2679 {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
2680 {"test_to_contiguous", (PyCFunction)test_to_contiguous, METH_NOARGS},
2681 {"test_from_contiguous", (PyCFunction)test_from_contiguous, METH_NOARGS},
2682 {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
2683 {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
2684 METH_NOARGS},
2685 {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
2686 {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
2687 #ifdef Py_USING_UNICODE
2688 {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
2689 #endif
2690 {"get_indices", get_indices, METH_VARARGS},
2691 {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS},
2692 {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
2693 {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
2694 {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
2695 PyDoc_STR("This is a pretty normal docstring.")},
2696
2697 {"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
2698 {"get_args", get_args, METH_VARARGS},
2699 {"get_kwargs", (PyCFunction)get_kwargs, METH_VARARGS|METH_KEYWORDS},
2700 {"getargs_tuple", getargs_tuple, METH_VARARGS},
2701 {"getargs_keywords", (PyCFunction)getargs_keywords,
2702 METH_VARARGS|METH_KEYWORDS},
2703 {"getargs_b", getargs_b, METH_VARARGS},
2704 {"getargs_B", getargs_B, METH_VARARGS},
2705 {"getargs_h", getargs_h, METH_VARARGS},
2706 {"getargs_H", getargs_H, METH_VARARGS},
2707 {"getargs_I", getargs_I, METH_VARARGS},
2708 {"getargs_k", getargs_k, METH_VARARGS},
2709 {"getargs_i", getargs_i, METH_VARARGS},
2710 {"getargs_l", getargs_l, METH_VARARGS},
2711 {"getargs_n", getargs_n, METH_VARARGS},
2712 #ifdef HAVE_LONG_LONG
2713 {"getargs_L", getargs_L, METH_VARARGS},
2714 {"getargs_K", getargs_K, METH_VARARGS},
2715 {"test_longlong_api", test_longlong_api, METH_NOARGS},
2716 {"test_long_long_and_overflow",
2717 (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
2718 {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
2719 #endif
2720 {"getargs_f", getargs_f, METH_VARARGS},
2721 {"getargs_d", getargs_d, METH_VARARGS},
2722 {"getargs_D", getargs_D, METH_VARARGS},
2723 {"getargs_S", getargs_S, METH_VARARGS},
2724 {"getargs_Y", getargs_Y, METH_VARARGS},
2725 #ifdef Py_USING_UNICODE
2726 {"getargs_U", getargs_U, METH_VARARGS},
2727 #endif
2728 {"getargs_c", getargs_c, METH_VARARGS},
2729 {"getargs_s", getargs_s, METH_VARARGS},
2730 {"getargs_s_star", getargs_s_star, METH_VARARGS},
2731 {"getargs_s_hash", getargs_s_hash, METH_VARARGS},
2732 {"getargs_t_hash", getargs_t_hash, METH_VARARGS},
2733 {"getargs_z", getargs_z, METH_VARARGS},
2734 {"getargs_z_star", getargs_z_star, METH_VARARGS},
2735 {"getargs_z_hash", getargs_z_hash, METH_VARARGS},
2736 {"getargs_w", getargs_w, METH_VARARGS},
2737 {"getargs_w_star", getargs_w_star, METH_VARARGS},
2738 {"getargs_w_hash", getargs_w_hash, METH_VARARGS},
2739 #ifdef Py_USING_UNICODE
2740 {"getargs_u", getargs_u, METH_VARARGS},
2741 {"getargs_u_hash", getargs_u_hash, METH_VARARGS},
2742 #endif
2743 {"getargs_es", getargs_es, METH_VARARGS},
2744 {"getargs_et", getargs_et, METH_VARARGS},
2745 {"getargs_es_hash", getargs_es_hash, METH_VARARGS},
2746 {"getargs_et_hash", getargs_et_hash, METH_VARARGS},
2747 #ifdef Py_USING_UNICODE
2748 {"codec_incrementalencoder",
2749 (PyCFunction)codec_incrementalencoder, METH_VARARGS},
2750 {"codec_incrementaldecoder",
2751 (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
2752 {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
2753 {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
2754 {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS},
2755 #endif
2756 #ifdef WITH_THREAD
2757 {"_test_thread_state", test_thread_state, METH_VARARGS},
2758 {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
2759 #endif
2760 {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
2761 {"traceback_print", traceback_print, METH_VARARGS},
2762 {"code_newempty", code_newempty, METH_VARARGS},
2763 {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
2764 METH_VARARGS | METH_KEYWORDS},
2765 {"sequence_delitem", (PyCFunction)sequence_delitem, METH_VARARGS},
2766 #ifdef WITH_THREAD
2767 {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O,
2768 PyDoc_STR("set_error_class(error_class) -> None")},
2769 #endif
2770 {"pymarshal_write_long_to_file",
2771 pymarshal_write_long_to_file, METH_VARARGS},
2772 {"pymarshal_write_object_to_file",
2773 pymarshal_write_object_to_file, METH_VARARGS},
2774 {"pymarshal_read_short_from_file",
2775 pymarshal_read_short_from_file, METH_VARARGS},
2776 {"pymarshal_read_long_from_file",
2777 pymarshal_read_long_from_file, METH_VARARGS},
2778 {"pymarshal_read_last_object_from_file",
2779 pymarshal_read_last_object_from_file, METH_VARARGS},
2780 {"pymarshal_read_object_from_file",
2781 pymarshal_read_object_from_file, METH_VARARGS},
2782 {"raise_signal", (PyCFunction)test_raise_signal, METH_VARARGS},
2783 #ifdef MS_WINDOWS
2784 {"CrtSetReportMode", (PyCFunction)msvcrt_CrtSetReportMode, METH_VARARGS},
2785 {"CrtSetReportFile", (PyCFunction)msvcrt_CrtSetReportFile, METH_VARARGS},
2786 #endif
2787 #ifdef W_STOPCODE
2788 {"W_STOPCODE", py_w_stopcode, METH_VARARGS},
2789 #endif
2790 {"_read_null", (PyCFunction)read_null, METH_NOARGS},
2791 {NULL, NULL} /* sentinel */
2792 };
2793
2794 #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
2795
2796 typedef struct {
2797 char bool_member;
2798 char byte_member;
2799 unsigned char ubyte_member;
2800 short short_member;
2801 unsigned short ushort_member;
2802 int int_member;
2803 unsigned int uint_member;
2804 long long_member;
2805 unsigned long ulong_member;
2806 float float_member;
2807 double double_member;
2808 char inplace_member[6];
2809 #ifdef HAVE_LONG_LONG
2810 PY_LONG_LONG longlong_member;
2811 unsigned PY_LONG_LONG ulonglong_member;
2812 #endif
2813 } all_structmembers;
2814
2815 typedef struct {
2816 PyObject_HEAD
2817 all_structmembers structmembers;
2818 } test_structmembers;
2819
2820 static struct PyMemberDef test_members[] = {
2821 {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
2822 {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
2823 {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
2824 {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
2825 {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
2826 {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
2827 {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
2828 {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
2829 {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
2830 {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
2831 {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
2832 {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
2833 #ifdef HAVE_LONG_LONG
2834 {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
2835 {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
2836 #endif
2837 {NULL}
2838 };
2839
2840
2841 static PyObject *
test_structmembers_new(PyTypeObject * type,PyObject * args,PyObject * kwargs)2842 test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2843 {
2844 static char *keywords[] = {
2845 "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
2846 "T_INT", "T_UINT", "T_LONG", "T_ULONG",
2847 "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
2848 #ifdef HAVE_LONG_LONG
2849 "T_LONGLONG", "T_ULONGLONG",
2850 #endif
2851 NULL};
2852 static char *fmt = "|bbBhHiIlkfds#"
2853 #ifdef HAVE_LONG_LONG
2854 "LK"
2855 #endif
2856 ;
2857 test_structmembers *ob;
2858 const char *s = NULL;
2859 int string_len = 0;
2860 ob = PyObject_New(test_structmembers, type);
2861 if (ob == NULL)
2862 return NULL;
2863 memset(&ob->structmembers, 0, sizeof(all_structmembers));
2864 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
2865 &ob->structmembers.bool_member,
2866 &ob->structmembers.byte_member,
2867 &ob->structmembers.ubyte_member,
2868 &ob->structmembers.short_member,
2869 &ob->structmembers.ushort_member,
2870 &ob->structmembers.int_member,
2871 &ob->structmembers.uint_member,
2872 &ob->structmembers.long_member,
2873 &ob->structmembers.ulong_member,
2874 &ob->structmembers.float_member,
2875 &ob->structmembers.double_member,
2876 &s, &string_len
2877 #ifdef HAVE_LONG_LONG
2878 , &ob->structmembers.longlong_member,
2879 &ob->structmembers.ulonglong_member
2880 #endif
2881 )) {
2882 Py_DECREF(ob);
2883 return NULL;
2884 }
2885 if (s != NULL) {
2886 if (string_len > 5) {
2887 Py_DECREF(ob);
2888 PyErr_SetString(PyExc_ValueError, "string too long");
2889 return NULL;
2890 }
2891 strcpy(ob->structmembers.inplace_member, s);
2892 }
2893 else {
2894 strcpy(ob->structmembers.inplace_member, "");
2895 }
2896 return (PyObject *)ob;
2897 }
2898
2899 static void
test_structmembers_free(PyObject * ob)2900 test_structmembers_free(PyObject *ob)
2901 {
2902 PyObject_FREE(ob);
2903 }
2904
2905 static PyTypeObject test_structmembersType = {
2906 PyVarObject_HEAD_INIT(NULL, 0)
2907 "test_structmembersType",
2908 sizeof(test_structmembers), /* tp_basicsize */
2909 0, /* tp_itemsize */
2910 test_structmembers_free, /* destructor tp_dealloc */
2911 0, /* tp_print */
2912 0, /* tp_getattr */
2913 0, /* tp_setattr */
2914 0, /* tp_compare */
2915 0, /* tp_repr */
2916 0, /* tp_as_number */
2917 0, /* tp_as_sequence */
2918 0, /* tp_as_mapping */
2919 0, /* tp_hash */
2920 0, /* tp_call */
2921 0, /* tp_str */
2922 PyObject_GenericGetAttr, /* tp_getattro */
2923 PyObject_GenericSetAttr, /* tp_setattro */
2924 0, /* tp_as_buffer */
2925 0, /* tp_flags */
2926 "Type containing all structmember types",
2927 0, /* traverseproc tp_traverse */
2928 0, /* tp_clear */
2929 0, /* tp_richcompare */
2930 0, /* tp_weaklistoffset */
2931 0, /* tp_iter */
2932 0, /* tp_iternext */
2933 0, /* tp_methods */
2934 test_members, /* tp_members */
2935 0,
2936 0,
2937 0,
2938 0,
2939 0,
2940 0,
2941 0,
2942 0,
2943 test_structmembers_new, /* tp_new */
2944 };
2945
2946
2947 PyMODINIT_FUNC
init_testcapi(void)2948 init_testcapi(void)
2949 {
2950 PyObject *m;
2951
2952 m = Py_InitModule("_testcapi", TestMethods);
2953 if (m == NULL)
2954 return;
2955
2956 Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
2957
2958 Py_TYPE(&test_structmembersType)=&PyType_Type;
2959 Py_INCREF(&test_structmembersType);
2960 /* don't use a name starting with "test", since we don't want
2961 test_capi to automatically call this */
2962 PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
2963
2964 PyModule_AddObject(m, "CHAR_MAX", PyInt_FromLong(CHAR_MAX));
2965 PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
2966 PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
2967 PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
2968 PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
2969 PyModule_AddObject(m, "USHRT_MAX", PyInt_FromLong(USHRT_MAX));
2970 PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
2971 PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
2972 PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
2973 PyModule_AddObject(m, "LONG_MAX", PyInt_FromLong(LONG_MAX));
2974 PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN));
2975 PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
2976 PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
2977 PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
2978 PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
2979 PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
2980 PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
2981 PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
2982 PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
2983 PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
2984 PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
2985 PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
2986
2987 #ifdef MS_WINDOWS
2988 PyModule_AddIntConstant(m, "CRT_WARN", _CRT_WARN);
2989 PyModule_AddIntConstant(m, "CRT_ERROR", _CRT_ERROR);
2990 PyModule_AddIntConstant(m, "CRT_ASSERT", _CRT_ASSERT);
2991 PyModule_AddIntConstant(m, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE);
2992 PyModule_AddIntConstant(m, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR);
2993 #endif
2994
2995 TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
2996 Py_INCREF(TestError);
2997 PyModule_AddObject(m, "error", TestError);
2998 }
2999