-
-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
_testcapimodule.c
4207 lines (3682 loc) · 120 KB
/
_testcapimodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* C Extension module to test Python interpreter C APIs.
*
* The 'test_*' functions exported by this module are run as part of the
* standard Python regression test, via Lib/test/test_capi.py.
*/
// Include parts.h first since it takes care of NDEBUG and Py_BUILD_CORE macros
// and including Python.h.
//
// Several parts of this module are broken out into files in _testcapi/.
// Include definitions from there.
#include "_testcapi/parts.h"
#include "frameobject.h" // PyFrame_New()
#include "marshal.h" // PyMarshal_WriteLongToFile()
#include <float.h> // FLT_MAX
#include <signal.h>
#include <stddef.h> // offsetof()
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h> // W_STOPCODE
#endif
#ifdef bool
# error "The public headers should not include <stdbool.h>, see gh-48924"
#endif
#include "_testcapi/util.h"
// Forward declarations
static struct PyModuleDef _testcapimodule;
// Module state
typedef struct {
PyObject *error; // _testcapi.error object
} testcapistate_t;
static testcapistate_t*
get_testcapi_state(PyObject *module)
{
void *state = PyModule_GetState(module);
assert(state != NULL);
return (testcapistate_t *)state;
}
static PyObject *
get_testerror(PyObject *self) {
testcapistate_t *state = get_testcapi_state(self);
return state->error;
}
/* Raise _testcapi.error with test_name + ": " + msg, and return NULL. */
static PyObject *
raiseTestError(PyObject *self, const char* test_name, const char* msg)
{
PyErr_Format(get_testerror(self), "%s: %s", test_name, msg);
return NULL;
}
/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
The ones derived from autoconf on the UNIX-like OSes can be relied
upon (in the absence of sloppy cross-compiling), but the Windows
platforms have these hardcoded. Better safe than sorry.
*/
static PyObject*
sizeof_error(PyObject *self, const char* fatname, const char* typname,
int expected, int got)
{
PyErr_Format(get_testerror(self),
"%s #define == %d but sizeof(%s) == %d",
fatname, expected, typname, got);
return (PyObject*)NULL;
}
static PyObject*
test_config(PyObject *self, PyObject *Py_UNUSED(ignored))
{
#define CHECK_SIZEOF(FATNAME, TYPE) \
do { \
if (FATNAME != sizeof(TYPE)) { \
return sizeof_error(self, #FATNAME, #TYPE, FATNAME, sizeof(TYPE)); \
} \
} while (0)
CHECK_SIZEOF(SIZEOF_SHORT, short);
CHECK_SIZEOF(SIZEOF_INT, int);
CHECK_SIZEOF(SIZEOF_LONG, long);
CHECK_SIZEOF(SIZEOF_VOID_P, void*);
CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
CHECK_SIZEOF(SIZEOF_LONG_LONG, long long);
#undef CHECK_SIZEOF
Py_RETURN_NONE;
}
static PyObject*
test_sizeof_c_types(PyObject *self, PyObject *Py_UNUSED(ignored))
{
#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
#define CHECK_SIZEOF(TYPE, EXPECTED) \
do { \
if (EXPECTED != sizeof(TYPE)) { \
PyErr_Format(get_testerror(self), \
"sizeof(%s) = %u instead of %u", \
#TYPE, sizeof(TYPE), EXPECTED); \
return (PyObject*)NULL; \
} \
} while (0)
#define IS_SIGNED(TYPE) (((TYPE)-1) < (TYPE)0)
#define CHECK_SIGNNESS(TYPE, SIGNED) \
do { \
if (IS_SIGNED(TYPE) != SIGNED) { \
PyErr_Format(get_testerror(self), \
"%s signness is %i, instead of %i", \
#TYPE, IS_SIGNED(TYPE), SIGNED); \
return (PyObject*)NULL; \
} \
} while (0)
/* integer types */
CHECK_SIZEOF(Py_UCS1, 1);
CHECK_SIZEOF(Py_UCS2, 2);
CHECK_SIZEOF(Py_UCS4, 4);
CHECK_SIGNNESS(Py_UCS1, 0);
CHECK_SIGNNESS(Py_UCS2, 0);
CHECK_SIGNNESS(Py_UCS4, 0);
CHECK_SIZEOF(int32_t, 4);
CHECK_SIGNNESS(int32_t, 1);
CHECK_SIZEOF(uint32_t, 4);
CHECK_SIGNNESS(uint32_t, 0);
CHECK_SIZEOF(int64_t, 8);
CHECK_SIGNNESS(int64_t, 1);
CHECK_SIZEOF(uint64_t, 8);
CHECK_SIGNNESS(uint64_t, 0);
/* pointer/size types */
CHECK_SIZEOF(size_t, sizeof(void *));
CHECK_SIGNNESS(size_t, 0);
CHECK_SIZEOF(Py_ssize_t, sizeof(void *));
CHECK_SIGNNESS(Py_ssize_t, 1);
CHECK_SIZEOF(uintptr_t, sizeof(void *));
CHECK_SIGNNESS(uintptr_t, 0);
CHECK_SIZEOF(intptr_t, sizeof(void *));
CHECK_SIGNNESS(intptr_t, 1);
Py_RETURN_NONE;
#undef IS_SIGNED
#undef CHECK_SIGNESS
#undef CHECK_SIZEOF
#if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
#pragma GCC diagnostic pop
#endif
}
static PyObject*
test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject* list;
int i;
/* SF bug 132008: PyList_Reverse segfaults */
#define NLIST 30
list = PyList_New(NLIST);
if (list == (PyObject*)NULL)
return (PyObject*)NULL;
/* list = range(NLIST) */
for (i = 0; i < NLIST; ++i) {
PyObject* anint = PyLong_FromLong(i);
if (anint == (PyObject*)NULL) {
Py_DECREF(list);
return (PyObject*)NULL;
}
PyList_SET_ITEM(list, i, anint);
}
/* list.reverse(), via PyList_Reverse() */
i = PyList_Reverse(list); /* should not blow up! */
if (i != 0) {
Py_DECREF(list);
return (PyObject*)NULL;
}
/* Check that list == range(29, -1, -1) now */
for (i = 0; i < NLIST; ++i) {
PyObject* anint = PyList_GET_ITEM(list, i);
if (PyLong_AS_LONG(anint) != NLIST-1-i) {
PyErr_SetString(get_testerror(self),
"test_list_api: reverse screwed up");
Py_DECREF(list);
return (PyObject*)NULL;
}
}
Py_DECREF(list);
#undef NLIST
Py_RETURN_NONE;
}
static int
test_dict_inner(PyObject *self, int count)
{
Py_ssize_t pos = 0, iterations = 0;
int i;
PyObject *dict = PyDict_New();
PyObject *v, *k;
if (dict == NULL)
return -1;
for (i = 0; i < count; i++) {
v = PyLong_FromLong(i);
if (v == NULL) {
goto error;
}
if (PyDict_SetItem(dict, v, v) < 0) {
Py_DECREF(v);
goto error;
}
Py_DECREF(v);
}
k = v = UNINITIALIZED_PTR;
while (PyDict_Next(dict, &pos, &k, &v)) {
PyObject *o;
iterations++;
assert(k != UNINITIALIZED_PTR);
assert(v != UNINITIALIZED_PTR);
i = PyLong_AS_LONG(v) + 1;
o = PyLong_FromLong(i);
if (o == NULL) {
goto error;
}
if (PyDict_SetItem(dict, k, o) < 0) {
Py_DECREF(o);
goto error;
}
Py_DECREF(o);
k = v = UNINITIALIZED_PTR;
}
assert(k == UNINITIALIZED_PTR);
assert(v == UNINITIALIZED_PTR);
Py_DECREF(dict);
if (iterations != count) {
PyErr_SetString(
get_testerror(self),
"test_dict_iteration: dict iteration went wrong ");
return -1;
} else {
return 0;
}
error:
Py_DECREF(dict);
return -1;
}
static PyObject*
test_dict_iteration(PyObject* self, PyObject *Py_UNUSED(ignored))
{
int i;
for (i = 0; i < 200; i++) {
if (test_dict_inner(self, i) < 0) {
return NULL;
}
}
Py_RETURN_NONE;
}
/* Issue #4701: Check that PyObject_Hash implicitly calls
* PyType_Ready if it hasn't already been called
*/
static PyTypeObject _HashInheritanceTester_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"hashinheritancetester", /* Name of this type */
sizeof(PyObject), /* Basic object size */
0, /* Item size for varobject */
(destructor)PyObject_Free, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject*
pycompilestring(PyObject* self, PyObject *obj) {
if (PyBytes_CheckExact(obj) == 0) {
PyErr_SetString(PyExc_ValueError, "Argument must be a bytes object");
return NULL;
}
const char *the_string = PyBytes_AsString(obj);
if (the_string == NULL) {
return NULL;
}
return Py_CompileString(the_string, "<string>", Py_file_input);
}
static PyObject*
test_lazy_hash_inheritance(PyObject* self, PyObject *Py_UNUSED(ignored))
{
PyTypeObject *type;
PyObject *obj;
Py_hash_t hash;
type = &_HashInheritanceTester_Type;
if (type->tp_dict != NULL)
/* The type has already been initialized. This probably means
-R is being used. */
Py_RETURN_NONE;
obj = PyObject_New(PyObject, type);
if (obj == NULL) {
PyErr_Clear();
PyErr_SetString(
get_testerror(self),
"test_lazy_hash_inheritance: failed to create object");
return NULL;
}
if (type->tp_dict != NULL) {
PyErr_SetString(
get_testerror(self),
"test_lazy_hash_inheritance: type initialised too soon");
Py_DECREF(obj);
return NULL;
}
hash = PyObject_Hash(obj);
if ((hash == -1) && PyErr_Occurred()) {
PyErr_Clear();
PyErr_SetString(
get_testerror(self),
"test_lazy_hash_inheritance: could not hash object");
Py_DECREF(obj);
return NULL;
}
if (type->tp_dict == NULL) {
PyErr_SetString(
get_testerror(self),
"test_lazy_hash_inheritance: type not initialised by hash()");
Py_DECREF(obj);
return NULL;
}
if (type->tp_hash != PyType_Type.tp_hash) {
PyErr_SetString(
get_testerror(self),
"test_lazy_hash_inheritance: unexpected hash function");
Py_DECREF(obj);
return NULL;
}
Py_DECREF(obj);
Py_RETURN_NONE;
}
static PyObject *
return_none(void *unused)
{
Py_RETURN_NONE;
}
static PyObject *
raise_error(void *unused)
{
PyErr_SetNone(PyExc_ValueError);
return NULL;
}
static PyObject *
py_buildvalue(PyObject *self, PyObject *args)
{
const char *fmt;
PyObject *objs[10] = {NULL};
if (!PyArg_ParseTuple(args, "s|OOOOOOOOOO", &fmt,
&objs[0], &objs[1], &objs[2], &objs[3], &objs[4],
&objs[5], &objs[6], &objs[7], &objs[8], &objs[9]))
{
return NULL;
}
for(int i = 0; i < 10; i++) {
NULLABLE(objs[i]);
}
return Py_BuildValue(fmt,
objs[0], objs[1], objs[2], objs[3], objs[4],
objs[5], objs[6], objs[7], objs[8], objs[9]);
}
static PyObject *
py_buildvalue_ints(PyObject *self, PyObject *args)
{
const char *fmt;
unsigned int values[10] = {0};
if (!PyArg_ParseTuple(args, "s|IIIIIIIIII", &fmt,
&values[0], &values[1], &values[2], &values[3], &values[4],
&values[5], &values[6], &values[7], &values[8], &values[9]))
{
return NULL;
}
return Py_BuildValue(fmt,
values[0], values[1], values[2], values[3], values[4],
values[5], values[6], values[7], values[8], values[9]);
}
static int
test_buildvalue_N_error(PyObject *self, const char *fmt)
{
PyObject *arg, *res;
arg = PyList_New(0);
if (arg == NULL) {
return -1;
}
Py_INCREF(arg);
res = Py_BuildValue(fmt, return_none, NULL, arg);
if (res == NULL) {
return -1;
}
Py_DECREF(res);
if (Py_REFCNT(arg) != 1) {
PyErr_Format(get_testerror(self), "test_buildvalue_N: "
"arg was not decrefed in successful "
"Py_BuildValue(\"%s\")", fmt);
return -1;
}
Py_INCREF(arg);
res = Py_BuildValue(fmt, raise_error, NULL, arg);
if (res != NULL || !PyErr_Occurred()) {
PyErr_Format(get_testerror(self), "test_buildvalue_N: "
"Py_BuildValue(\"%s\") didn't complain", fmt);
return -1;
}
PyErr_Clear();
if (Py_REFCNT(arg) != 1) {
PyErr_Format(get_testerror(self), "test_buildvalue_N: "
"arg was not decrefed in failed "
"Py_BuildValue(\"%s\")", fmt);
return -1;
}
Py_DECREF(arg);
return 0;
}
static PyObject *
test_buildvalue_N(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *arg, *res;
arg = PyList_New(0);
if (arg == NULL) {
return NULL;
}
Py_INCREF(arg);
res = Py_BuildValue("N", arg);
if (res == NULL) {
return NULL;
}
if (res != arg) {
return raiseTestError(self, "test_buildvalue_N",
"Py_BuildValue(\"N\") returned wrong result");
}
if (Py_REFCNT(arg) != 2) {
return raiseTestError(self, "test_buildvalue_N",
"arg was not decrefed in Py_BuildValue(\"N\")");
}
Py_DECREF(res);
Py_DECREF(arg);
if (test_buildvalue_N_error(self, "O&N") < 0)
return NULL;
if (test_buildvalue_N_error(self, "(O&N)") < 0)
return NULL;
if (test_buildvalue_N_error(self, "[O&N]") < 0)
return NULL;
if (test_buildvalue_N_error(self, "{O&N}") < 0)
return NULL;
if (test_buildvalue_N_error(self, "{()O&(())N}") < 0)
return NULL;
Py_RETURN_NONE;
}
static PyObject *
test_get_statictype_slots(PyObject *self, PyObject *Py_UNUSED(ignored))
{
newfunc tp_new = PyType_GetSlot(&PyLong_Type, Py_tp_new);
if (PyLong_Type.tp_new != tp_new) {
PyErr_SetString(PyExc_AssertionError, "mismatch: tp_new of long");
return NULL;
}
reprfunc tp_repr = PyType_GetSlot(&PyLong_Type, Py_tp_repr);
if (PyLong_Type.tp_repr != tp_repr) {
PyErr_SetString(PyExc_AssertionError, "mismatch: tp_repr of long");
return NULL;
}
ternaryfunc tp_call = PyType_GetSlot(&PyLong_Type, Py_tp_call);
if (tp_call != NULL) {
PyErr_SetString(PyExc_AssertionError, "mismatch: tp_call of long");
return NULL;
}
binaryfunc nb_add = PyType_GetSlot(&PyLong_Type, Py_nb_add);
if (PyLong_Type.tp_as_number->nb_add != nb_add) {
PyErr_SetString(PyExc_AssertionError, "mismatch: nb_add of long");
return NULL;
}
lenfunc mp_length = PyType_GetSlot(&PyLong_Type, Py_mp_length);
if (mp_length != NULL) {
PyErr_SetString(PyExc_AssertionError, "mismatch: mp_length of long");
return NULL;
}
void *over_value = PyType_GetSlot(&PyLong_Type, Py_bf_releasebuffer + 1);
if (over_value != NULL) {
PyErr_SetString(PyExc_AssertionError, "mismatch: max+1 of long");
return NULL;
}
tp_new = PyType_GetSlot(&PyLong_Type, 0);
if (tp_new != NULL) {
PyErr_SetString(PyExc_AssertionError, "mismatch: slot 0 of long");
return NULL;
}
if (PyErr_ExceptionMatches(PyExc_SystemError)) {
// This is the right exception
PyErr_Clear();
}
else {
return NULL;
}
Py_RETURN_NONE;
}
static PyType_Slot HeapTypeNameType_slots[] = {
{0},
};
static PyType_Spec HeapTypeNameType_Spec = {
.name = "_testcapi.HeapTypeNameType",
.basicsize = sizeof(PyObject),
.flags = Py_TPFLAGS_DEFAULT,
.slots = HeapTypeNameType_slots,
};
static PyObject *
get_heaptype_for_name(PyObject *self, PyObject *Py_UNUSED(ignored))
{
return PyType_FromSpec(&HeapTypeNameType_Spec);
}
static PyObject *
get_type_name(PyObject *self, PyObject *type)
{
assert(PyType_Check(type));
return PyType_GetName((PyTypeObject *)type);
}
static PyObject *
get_type_qualname(PyObject *self, PyObject *type)
{
assert(PyType_Check(type));
return PyType_GetQualName((PyTypeObject *)type);
}
static PyObject *
get_type_fullyqualname(PyObject *self, PyObject *type)
{
assert(PyType_Check(type));
return PyType_GetFullyQualifiedName((PyTypeObject *)type);
}
static PyObject *
get_type_module_name(PyObject *self, PyObject *type)
{
assert(PyType_Check(type));
return PyType_GetModuleName((PyTypeObject *)type);
}
static PyObject *
test_get_type_dict(PyObject *self, PyObject *Py_UNUSED(ignored))
{
/* Test for PyType_GetDict */
// Assert ints have a `to_bytes` method
PyObject *long_dict = PyType_GetDict(&PyLong_Type);
assert(long_dict);
assert(PyDict_GetItemString(long_dict, "to_bytes")); // borrowed ref
Py_DECREF(long_dict);
// Make a new type, add an attribute to it and assert it's there
PyObject *HeapTypeNameType = PyType_FromSpec(&HeapTypeNameType_Spec);
assert(HeapTypeNameType);
assert(PyObject_SetAttrString(
HeapTypeNameType, "new_attr", Py_NewRef(Py_None)) >= 0);
PyObject *type_dict = PyType_GetDict((PyTypeObject*)HeapTypeNameType);
assert(type_dict);
assert(PyDict_GetItemString(type_dict, "new_attr")); // borrowed ref
Py_DECREF(HeapTypeNameType);
Py_DECREF(type_dict);
Py_RETURN_NONE;
}
static PyObject *
pyobject_repr_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
{
return PyObject_Repr(NULL);
}
static PyObject *
pyobject_str_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
{
return PyObject_Str(NULL);
}
static PyObject *
pyobject_bytes_from_null(PyObject *self, PyObject *Py_UNUSED(ignored))
{
return PyObject_Bytes(NULL);
}
static PyObject *
set_errno(PyObject *self, PyObject *args)
{
int new_errno;
if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
return NULL;
errno = new_errno;
Py_RETURN_NONE;
}
/* test_thread_state spawns a thread of its own, and that thread releases
* `thread_done` when it's finished. The driver code has to know when the
* thread finishes, because the thread uses a PyObject (the callable) that
* may go away when the driver finishes. The former lack of this explicit
* synchronization caused rare segfaults, so rare that they were seen only
* on a Mac buildbot (although they were possible on any box).
*/
static PyThread_type_lock thread_done = NULL;
static int
_make_call(void *callable)
{
PyObject *rc;
int success;
PyGILState_STATE s = PyGILState_Ensure();
rc = PyObject_CallNoArgs((PyObject *)callable);
success = (rc != NULL);
Py_XDECREF(rc);
PyGILState_Release(s);
return success;
}
/* Same thing, but releases `thread_done` when it returns. This variant
* should be called only from threads spawned by test_thread_state().
*/
static void
_make_call_from_thread(void *callable)
{
_make_call(callable);
PyThread_release_lock(thread_done);
}
static PyObject *
test_thread_state(PyObject *self, PyObject *args)
{
PyObject *fn;
int success = 1;
if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
return NULL;
if (!PyCallable_Check(fn)) {
PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
Py_TYPE(fn)->tp_name);
return NULL;
}
thread_done = PyThread_allocate_lock();
if (thread_done == NULL)
return PyErr_NoMemory();
PyThread_acquire_lock(thread_done, 1);
/* Start a new thread with our callback. */
PyThread_start_new_thread(_make_call_from_thread, fn);
/* Make the callback with the thread lock held by this thread */
success &= _make_call(fn);
/* Do it all again, but this time with the thread-lock released */
Py_BEGIN_ALLOW_THREADS
success &= _make_call(fn);
PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
Py_END_ALLOW_THREADS
/* And once more with and without a thread
XXX - should use a lock and work out exactly what we are trying
to test <wink>
*/
Py_BEGIN_ALLOW_THREADS
PyThread_start_new_thread(_make_call_from_thread, fn);
success &= _make_call(fn);
PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
Py_END_ALLOW_THREADS
/* Release lock we acquired above. This is required on HP-UX. */
PyThread_release_lock(thread_done);
PyThread_free_lock(thread_done);
if (!success)
return NULL;
Py_RETURN_NONE;
}
static PyObject *
gilstate_ensure_release(PyObject *module, PyObject *Py_UNUSED(ignored))
{
PyGILState_STATE state = PyGILState_Ensure();
PyGILState_Release(state);
Py_RETURN_NONE;
}
#ifndef MS_WINDOWS
static PyThread_type_lock wait_done = NULL;
static void wait_for_lock(void *unused) {
PyThread_acquire_lock(wait_done, 1);
PyThread_release_lock(wait_done);
PyThread_free_lock(wait_done);
wait_done = NULL;
}
// These can be used to test things that care about the existence of another
// thread that the threading module doesn't know about.
static PyObject *
spawn_pthread_waiter(PyObject *self, PyObject *Py_UNUSED(ignored))
{
if (wait_done) {
PyErr_SetString(PyExc_RuntimeError, "thread already running");
return NULL;
}
wait_done = PyThread_allocate_lock();
if (wait_done == NULL)
return PyErr_NoMemory();
PyThread_acquire_lock(wait_done, 1);
PyThread_start_new_thread(wait_for_lock, NULL);
Py_RETURN_NONE;
}
static PyObject *
end_spawned_pthread(PyObject *self, PyObject *Py_UNUSED(ignored))
{
if (!wait_done) {
PyErr_SetString(PyExc_RuntimeError, "call _spawn_pthread_waiter 1st");
return NULL;
}
PyThread_release_lock(wait_done);
Py_RETURN_NONE;
}
#endif // not MS_WINDOWS
/* test Py_AddPendingCalls using threads */
static int _pending_callback(void *arg)
{
/* we assume the argument is callable object to which we own a reference */
PyObject *callable = (PyObject *)arg;
PyObject *r = PyObject_CallNoArgs(callable);
Py_DECREF(callable);
Py_XDECREF(r);
return r != NULL ? 0 : -1;
}
/* The following requests n callbacks to _pending_callback. It can be
* run from any python thread.
*/
static PyObject *
pending_threadfunc(PyObject *self, PyObject *arg, PyObject *kwargs)
{
static char *kwlist[] = {"callback", "num",
"blocking", "ensure_added", NULL};
PyObject *callable;
unsigned int num = 1;
int blocking = 0;
int ensure_added = 0;
if (!PyArg_ParseTupleAndKeywords(arg, kwargs,
"O|I$pp:_pending_threadfunc", kwlist,
&callable, &num, &blocking, &ensure_added))
{
return NULL;
}
/* create the reference for the callbackwhile we hold the lock */
for (unsigned int i = 0; i < num; i++) {
Py_INCREF(callable);
}
PyThreadState *save_tstate = NULL;
if (!blocking) {
save_tstate = PyEval_SaveThread();
}
unsigned int num_added = 0;
for (; num_added < num; num_added++) {
if (ensure_added) {
int r;
do {
r = Py_AddPendingCall(&_pending_callback, callable);
} while (r < 0);
}
else {
if (Py_AddPendingCall(&_pending_callback, callable) < 0) {
break;
}
}
}
if (!blocking) {
PyEval_RestoreThread(save_tstate);
}
for (unsigned int i = num_added; i < num; i++) {
Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
}
/* The callable is decref'ed above in each added _pending_callback(). */
return PyLong_FromUnsignedLong((unsigned long)num_added);
}
/* Test PyOS_string_to_double. */
static PyObject *
test_string_to_double(PyObject *self, PyObject *Py_UNUSED(ignored)) {
double result;
const char *msg;
#define CHECK_STRING(STR, expected) \
do { \
result = PyOS_string_to_double(STR, NULL, NULL); \
if (result == -1.0 && PyErr_Occurred()) { \
return NULL; \
} \
if (result != (double)expected) { \
msg = "conversion of " STR " to float failed"; \
goto fail; \
} \
} while (0)
#define CHECK_INVALID(STR) \
do { \
result = PyOS_string_to_double(STR, NULL, NULL); \
if (result == -1.0 && PyErr_Occurred()) { \
if (PyErr_ExceptionMatches(PyExc_ValueError)) { \
PyErr_Clear(); \
} \
else { \
return NULL; \
} \
} \
else { \
msg = "conversion of " STR " didn't raise ValueError"; \
goto fail; \
} \
} while (0)
CHECK_STRING("0.1", 0.1);
CHECK_STRING("1.234", 1.234);
CHECK_STRING("-1.35", -1.35);
CHECK_STRING(".1e01", 1.0);
CHECK_STRING("2.e-2", 0.02);
CHECK_INVALID(" 0.1");
CHECK_INVALID("\t\n-3");
CHECK_INVALID(".123 ");
CHECK_INVALID("3\n");
CHECK_INVALID("123abc");
Py_RETURN_NONE;
fail:
return raiseTestError(self, "test_string_to_double", msg);
#undef CHECK_STRING
#undef CHECK_INVALID
}
/* Coverage testing of capsule objects. */
static const char *capsule_name = "capsule name";
static char *capsule_pointer = "capsule pointer";
static char *capsule_context = "capsule context";
static const char *capsule_error = NULL;
static int
capsule_destructor_call_count = 0;
static void
capsule_destructor(PyObject *o) {
capsule_destructor_call_count++;
if (PyCapsule_GetContext(o) != capsule_context) {
capsule_error = "context did not match in destructor!";
} else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
capsule_error = "destructor did not match in destructor! (woah!)";
} else if (PyCapsule_GetName(o) != capsule_name) {
capsule_error = "name did not match in destructor!";
} else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
capsule_error = "pointer did not match in destructor!";
}
}
typedef struct {
char *name;
char *module;
char *attribute;
} known_capsule;
static PyObject *
test_capsule(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *object;
const char *error = NULL;
void *pointer;
void *pointer2;
known_capsule known_capsules[] = {
#define KNOWN_CAPSULE(module, name) { module "." name, module, name }
KNOWN_CAPSULE("_socket", "CAPI"),
KNOWN_CAPSULE("_curses", "_C_API"),
KNOWN_CAPSULE("datetime", "datetime_CAPI"),
{ NULL, NULL },
};
known_capsule *known = &known_capsules[0];
#define FAIL(x) \
do { \
error = (x); \
goto exit; \
} while (0)
#define CHECK_DESTRUCTOR \
do { \
if (capsule_error) { \
FAIL(capsule_error); \
} \
else if (!capsule_destructor_call_count) { \
FAIL("destructor not called!"); \