1 /*
2 * C Extension module to test Python internal C APIs (Include/internal).
3 */
4
5 #ifndef Py_BUILD_CORE_BUILTIN
6 # define Py_BUILD_CORE_MODULE 1
7 #endif
8
9 /* Always enable assertions */
10 #undef NDEBUG
11
12 #include "Python.h"
13 #include "pycore_backoff.h" // JUMP_BACKWARD_INITIAL_VALUE
14 #include "pycore_bitutils.h" // _Py_bswap32()
15 #include "pycore_bytesobject.h" // _PyBytes_Find()
16 #include "pycore_ceval.h" // _PyEval_AddPendingCall()
17 #include "pycore_compile.h" // _PyCompile_CodeGen()
18 #include "pycore_context.h" // _PyContext_NewHamtForTests()
19 #include "pycore_dict.h" // _PyManagedDictPointer_GetValues()
20 #include "pycore_fileutils.h" // _Py_normpath()
21 #include "pycore_frame.h" // _PyInterpreterFrame
22 #include "pycore_gc.h" // PyGC_Head
23 #include "pycore_hashtable.h" // _Py_hashtable_new()
24 #include "pycore_initconfig.h" // _Py_GetConfigsAsDict()
25 #include "pycore_instruction_sequence.h" // _PyInstructionSequence_New()
26 #include "pycore_interp.h" // _PyInterpreterState_GetConfigCopy()
27 #include "pycore_long.h" // _PyLong_Sign()
28 #include "pycore_object.h" // _PyObject_IsFreed()
29 #include "pycore_optimizer.h" // _Py_UopsSymbol, etc.
30 #include "pycore_pathconfig.h" // _PyPathConfig_ClearGlobal()
31 #include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
32 #include "pycore_pylifecycle.h" // _PyInterpreterConfig_AsDict()
33 #include "pycore_pystate.h" // _PyThreadState_GET()
34
35 #include "clinic/_testinternalcapi.c.h"
36
37 // Include test definitions from _testinternalcapi/
38 #include "_testinternalcapi/parts.h"
39
40
41 #define MODULE_NAME "_testinternalcapi"
42
43
44 static PyObject *
_get_current_module(void)45 _get_current_module(void)
46 {
47 // We ensured it was imported in _run_script().
48 PyObject *name = PyUnicode_FromString(MODULE_NAME);
49 if (name == NULL) {
50 return NULL;
51 }
52 PyObject *mod = PyImport_GetModule(name);
53 Py_DECREF(name);
54 if (mod == NULL) {
55 return NULL;
56 }
57 assert(mod != Py_None);
58 return mod;
59 }
60
61
62 /* module state *************************************************************/
63
64 typedef struct {
65 PyObject *record_list;
66 } module_state;
67
68 static inline module_state *
get_module_state(PyObject * mod)69 get_module_state(PyObject *mod)
70 {
71 assert(mod != NULL);
72 module_state *state = PyModule_GetState(mod);
73 assert(state != NULL);
74 return state;
75 }
76
77 static int
traverse_module_state(module_state * state,visitproc visit,void * arg)78 traverse_module_state(module_state *state, visitproc visit, void *arg)
79 {
80 Py_VISIT(state->record_list);
81 return 0;
82 }
83
84 static int
clear_module_state(module_state * state)85 clear_module_state(module_state *state)
86 {
87 Py_CLEAR(state->record_list);
88 return 0;
89 }
90
91
92 /* module functions *********************************************************/
93
94 /*[clinic input]
95 module _testinternalcapi
96 [clinic start generated code]*/
97 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bb583d8c9eb9a78]*/
98 static PyObject *
get_configs(PyObject * self,PyObject * Py_UNUSED (args))99 get_configs(PyObject *self, PyObject *Py_UNUSED(args))
100 {
101 return _Py_GetConfigsAsDict();
102 }
103
104
105 static PyObject*
get_recursion_depth(PyObject * self,PyObject * Py_UNUSED (args))106 get_recursion_depth(PyObject *self, PyObject *Py_UNUSED(args))
107 {
108 PyThreadState *tstate = _PyThreadState_GET();
109
110 return PyLong_FromLong(tstate->py_recursion_limit - tstate->py_recursion_remaining);
111 }
112
113
114 static PyObject*
get_c_recursion_remaining(PyObject * self,PyObject * Py_UNUSED (args))115 get_c_recursion_remaining(PyObject *self, PyObject *Py_UNUSED(args))
116 {
117 PyThreadState *tstate = _PyThreadState_GET();
118 return PyLong_FromLong(tstate->c_recursion_remaining);
119 }
120
121
122 static PyObject*
test_bswap(PyObject * self,PyObject * Py_UNUSED (args))123 test_bswap(PyObject *self, PyObject *Py_UNUSED(args))
124 {
125 uint16_t u16 = _Py_bswap16(UINT16_C(0x3412));
126 if (u16 != UINT16_C(0x1234)) {
127 PyErr_Format(PyExc_AssertionError,
128 "_Py_bswap16(0x3412) returns %u", u16);
129 return NULL;
130 }
131
132 uint32_t u32 = _Py_bswap32(UINT32_C(0x78563412));
133 if (u32 != UINT32_C(0x12345678)) {
134 PyErr_Format(PyExc_AssertionError,
135 "_Py_bswap32(0x78563412) returns %lu", u32);
136 return NULL;
137 }
138
139 uint64_t u64 = _Py_bswap64(UINT64_C(0xEFCDAB9078563412));
140 if (u64 != UINT64_C(0x1234567890ABCDEF)) {
141 PyErr_Format(PyExc_AssertionError,
142 "_Py_bswap64(0xEFCDAB9078563412) returns %llu", u64);
143 return NULL;
144 }
145
146 Py_RETURN_NONE;
147 }
148
149
150 static int
check_popcount(uint32_t x,int expected)151 check_popcount(uint32_t x, int expected)
152 {
153 // Use volatile to prevent the compiler to optimize out the whole test
154 volatile uint32_t u = x;
155 int bits = _Py_popcount32(u);
156 if (bits != expected) {
157 PyErr_Format(PyExc_AssertionError,
158 "_Py_popcount32(%lu) returns %i, expected %i",
159 (unsigned long)x, bits, expected);
160 return -1;
161 }
162 return 0;
163 }
164
165
166 static PyObject*
test_popcount(PyObject * self,PyObject * Py_UNUSED (args))167 test_popcount(PyObject *self, PyObject *Py_UNUSED(args))
168 {
169 #define CHECK(X, RESULT) \
170 do { \
171 if (check_popcount(X, RESULT) < 0) { \
172 return NULL; \
173 } \
174 } while (0)
175
176 CHECK(0, 0);
177 CHECK(1, 1);
178 CHECK(0x08080808, 4);
179 CHECK(0x10000001, 2);
180 CHECK(0x10101010, 4);
181 CHECK(0x10204080, 4);
182 CHECK(0xDEADCAFE, 22);
183 CHECK(0xFFFFFFFF, 32);
184 Py_RETURN_NONE;
185
186 #undef CHECK
187 }
188
189
190 static int
check_bit_length(unsigned long x,int expected)191 check_bit_length(unsigned long x, int expected)
192 {
193 // Use volatile to prevent the compiler to optimize out the whole test
194 volatile unsigned long u = x;
195 int len = _Py_bit_length(u);
196 if (len != expected) {
197 PyErr_Format(PyExc_AssertionError,
198 "_Py_bit_length(%lu) returns %i, expected %i",
199 x, len, expected);
200 return -1;
201 }
202 return 0;
203 }
204
205
206 static PyObject*
test_bit_length(PyObject * self,PyObject * Py_UNUSED (args))207 test_bit_length(PyObject *self, PyObject *Py_UNUSED(args))
208 {
209 #define CHECK(X, RESULT) \
210 do { \
211 if (check_bit_length(X, RESULT) < 0) { \
212 return NULL; \
213 } \
214 } while (0)
215
216 CHECK(0, 0);
217 CHECK(1, 1);
218 CHECK(0x1000, 13);
219 CHECK(0x1234, 13);
220 CHECK(0x54321, 19);
221 CHECK(0x7FFFFFFF, 31);
222 CHECK(0xFFFFFFFF, 32);
223 Py_RETURN_NONE;
224
225 #undef CHECK
226 }
227
228
229 #define TO_PTR(ch) ((void*)(uintptr_t)ch)
230 #define FROM_PTR(ptr) ((uintptr_t)ptr)
231 #define VALUE(key) (1 + ((int)(key) - 'a'))
232
233 static Py_uhash_t
hash_char(const void * key)234 hash_char(const void *key)
235 {
236 char ch = (char)FROM_PTR(key);
237 return ch;
238 }
239
240
241 static int
hashtable_cb(_Py_hashtable_t * table,const void * key_ptr,const void * value_ptr,void * user_data)242 hashtable_cb(_Py_hashtable_t *table,
243 const void *key_ptr, const void *value_ptr,
244 void *user_data)
245 {
246 int *count = (int *)user_data;
247 char key = (char)FROM_PTR(key_ptr);
248 int value = (int)FROM_PTR(value_ptr);
249 assert(value == VALUE(key));
250 *count += 1;
251 return 0;
252 }
253
254
255 static PyObject*
test_hashtable(PyObject * self,PyObject * Py_UNUSED (args))256 test_hashtable(PyObject *self, PyObject *Py_UNUSED(args))
257 {
258 _Py_hashtable_t *table = _Py_hashtable_new(hash_char,
259 _Py_hashtable_compare_direct);
260 if (table == NULL) {
261 return PyErr_NoMemory();
262 }
263
264 // Using an newly allocated table must not crash
265 assert(table->nentries == 0);
266 assert(table->nbuckets > 0);
267 assert(_Py_hashtable_get(table, TO_PTR('x')) == NULL);
268
269 // Test _Py_hashtable_set()
270 char key;
271 for (key='a'; key <= 'z'; key++) {
272 int value = VALUE(key);
273 if (_Py_hashtable_set(table, TO_PTR(key), TO_PTR(value)) < 0) {
274 _Py_hashtable_destroy(table);
275 return PyErr_NoMemory();
276 }
277 }
278 assert(table->nentries == 26);
279 assert(table->nbuckets > table->nentries);
280
281 // Test _Py_hashtable_get_entry()
282 for (key='a'; key <= 'z'; key++) {
283 _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(table, TO_PTR(key));
284 assert(entry != NULL);
285 assert(entry->key == TO_PTR(key));
286 assert(entry->value == TO_PTR(VALUE(key)));
287 }
288
289 // Test _Py_hashtable_get()
290 for (key='a'; key <= 'z'; key++) {
291 void *value_ptr = _Py_hashtable_get(table, TO_PTR(key));
292 assert((int)FROM_PTR(value_ptr) == VALUE(key));
293 }
294
295 // Test _Py_hashtable_steal()
296 key = 'p';
297 void *value_ptr = _Py_hashtable_steal(table, TO_PTR(key));
298 assert((int)FROM_PTR(value_ptr) == VALUE(key));
299 assert(table->nentries == 25);
300 assert(_Py_hashtable_get_entry(table, TO_PTR(key)) == NULL);
301
302 // Test _Py_hashtable_foreach()
303 int count = 0;
304 int res = _Py_hashtable_foreach(table, hashtable_cb, &count);
305 assert(res == 0);
306 assert(count == 25);
307
308 // Test _Py_hashtable_clear()
309 _Py_hashtable_clear(table);
310 assert(table->nentries == 0);
311 assert(table->nbuckets > 0);
312 assert(_Py_hashtable_get(table, TO_PTR('x')) == NULL);
313
314 _Py_hashtable_destroy(table);
315 Py_RETURN_NONE;
316 }
317
318
319 static PyObject *
test_get_config(PyObject * Py_UNUSED (self),PyObject * Py_UNUSED (args))320 test_get_config(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args))
321 {
322 PyConfig config;
323 PyConfig_InitIsolatedConfig(&config);
324 if (_PyInterpreterState_GetConfigCopy(&config) < 0) {
325 PyConfig_Clear(&config);
326 return NULL;
327 }
328 PyObject *dict = _PyConfig_AsDict(&config);
329 PyConfig_Clear(&config);
330 return dict;
331 }
332
333
334 static PyObject *
test_set_config(PyObject * Py_UNUSED (self),PyObject * dict)335 test_set_config(PyObject *Py_UNUSED(self), PyObject *dict)
336 {
337 PyConfig config;
338 PyConfig_InitIsolatedConfig(&config);
339 if (_PyConfig_FromDict(&config, dict) < 0) {
340 goto error;
341 }
342 if (_PyInterpreterState_SetConfig(&config) < 0) {
343 goto error;
344 }
345 PyConfig_Clear(&config);
346 Py_RETURN_NONE;
347
348 error:
349 PyConfig_Clear(&config);
350 return NULL;
351 }
352
353
354 static PyObject *
test_reset_path_config(PyObject * Py_UNUSED (self),PyObject * Py_UNUSED (arg))355 test_reset_path_config(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(arg))
356 {
357 _PyPathConfig_ClearGlobal();
358 Py_RETURN_NONE;
359 }
360
361
362 static int
check_edit_cost(const char * a,const char * b,Py_ssize_t expected)363 check_edit_cost(const char *a, const char *b, Py_ssize_t expected)
364 {
365 int ret = -1;
366 PyObject *a_obj = NULL;
367 PyObject *b_obj = NULL;
368
369 a_obj = PyUnicode_FromString(a);
370 if (a_obj == NULL) {
371 goto exit;
372 }
373 b_obj = PyUnicode_FromString(b);
374 if (b_obj == NULL) {
375 goto exit;
376 }
377 Py_ssize_t result = _Py_UTF8_Edit_Cost(a_obj, b_obj, -1);
378 if (result != expected) {
379 PyErr_Format(PyExc_AssertionError,
380 "Edit cost from '%s' to '%s' returns %zd, expected %zd",
381 a, b, result, expected);
382 goto exit;
383 }
384 // Check that smaller max_edits thresholds are exceeded.
385 Py_ssize_t max_edits = result;
386 while (max_edits > 0) {
387 max_edits /= 2;
388 Py_ssize_t result2 = _Py_UTF8_Edit_Cost(a_obj, b_obj, max_edits);
389 if (result2 <= max_edits) {
390 PyErr_Format(PyExc_AssertionError,
391 "Edit cost from '%s' to '%s' (threshold %zd) "
392 "returns %zd, expected greater than %zd",
393 a, b, max_edits, result2, max_edits);
394 goto exit;
395 }
396 }
397 // Check that bigger max_edits thresholds don't change anything
398 Py_ssize_t result3 = _Py_UTF8_Edit_Cost(a_obj, b_obj, result * 2 + 1);
399 if (result3 != result) {
400 PyErr_Format(PyExc_AssertionError,
401 "Edit cost from '%s' to '%s' (threshold %zd) "
402 "returns %zd, expected %zd",
403 a, b, result * 2, result3, result);
404 goto exit;
405 }
406 ret = 0;
407 exit:
408 Py_XDECREF(a_obj);
409 Py_XDECREF(b_obj);
410 return ret;
411 }
412
413 static PyObject *
test_edit_cost(PyObject * self,PyObject * Py_UNUSED (args))414 test_edit_cost(PyObject *self, PyObject *Py_UNUSED(args))
415 {
416 #define CHECK(a, b, n) do { \
417 if (check_edit_cost(a, b, n) < 0) { \
418 return NULL; \
419 } \
420 } while (0) \
421
422 CHECK("", "", 0);
423 CHECK("", "a", 2);
424 CHECK("a", "A", 1);
425 CHECK("Apple", "Aple", 2);
426 CHECK("Banana", "B@n@n@", 6);
427 CHECK("Cherry", "Cherry!", 2);
428 CHECK("---0---", "------", 2);
429 CHECK("abc", "y", 6);
430 CHECK("aa", "bb", 4);
431 CHECK("aaaaa", "AAAAA", 5);
432 CHECK("wxyz", "wXyZ", 2);
433 CHECK("wxyz", "wXyZ123", 8);
434 CHECK("Python", "Java", 12);
435 CHECK("Java", "C#", 8);
436 CHECK("AbstractFoobarManager", "abstract_foobar_manager", 3+2*2);
437 CHECK("CPython", "PyPy", 10);
438 CHECK("CPython", "pypy", 11);
439 CHECK("AttributeError", "AttributeErrop", 2);
440 CHECK("AttributeError", "AttributeErrorTests", 10);
441
442 #undef CHECK
443 Py_RETURN_NONE;
444 }
445
446
447 static int
check_bytes_find(const char * haystack0,const char * needle0,int offset,Py_ssize_t expected)448 check_bytes_find(const char *haystack0, const char *needle0,
449 int offset, Py_ssize_t expected)
450 {
451 Py_ssize_t len_haystack = strlen(haystack0);
452 Py_ssize_t len_needle = strlen(needle0);
453 Py_ssize_t result_1 = _PyBytes_Find(haystack0, len_haystack,
454 needle0, len_needle, offset);
455 if (result_1 != expected) {
456 PyErr_Format(PyExc_AssertionError,
457 "Incorrect result_1: '%s' in '%s' (offset=%zd)",
458 needle0, haystack0, offset);
459 return -1;
460 }
461 // Allocate new buffer with no NULL terminator.
462 char *haystack = PyMem_Malloc(len_haystack);
463 if (haystack == NULL) {
464 PyErr_NoMemory();
465 return -1;
466 }
467 char *needle = PyMem_Malloc(len_needle);
468 if (needle == NULL) {
469 PyMem_Free(haystack);
470 PyErr_NoMemory();
471 return -1;
472 }
473 memcpy(haystack, haystack0, len_haystack);
474 memcpy(needle, needle0, len_needle);
475 Py_ssize_t result_2 = _PyBytes_Find(haystack, len_haystack,
476 needle, len_needle, offset);
477 PyMem_Free(haystack);
478 PyMem_Free(needle);
479 if (result_2 != expected) {
480 PyErr_Format(PyExc_AssertionError,
481 "Incorrect result_2: '%s' in '%s' (offset=%zd)",
482 needle0, haystack0, offset);
483 return -1;
484 }
485 return 0;
486 }
487
488 static int
check_bytes_find_large(Py_ssize_t len_haystack,Py_ssize_t len_needle,const char * needle)489 check_bytes_find_large(Py_ssize_t len_haystack, Py_ssize_t len_needle,
490 const char *needle)
491 {
492 char *zeros = PyMem_RawCalloc(len_haystack, 1);
493 if (zeros == NULL) {
494 PyErr_NoMemory();
495 return -1;
496 }
497 Py_ssize_t res = _PyBytes_Find(zeros, len_haystack, needle, len_needle, 0);
498 PyMem_RawFree(zeros);
499 if (res != -1) {
500 PyErr_Format(PyExc_AssertionError,
501 "check_bytes_find_large(%zd, %zd) found %zd",
502 len_haystack, len_needle, res);
503 return -1;
504 }
505 return 0;
506 }
507
508 static PyObject *
test_bytes_find(PyObject * self,PyObject * Py_UNUSED (args))509 test_bytes_find(PyObject *self, PyObject *Py_UNUSED(args))
510 {
511 #define CHECK(H, N, O, E) do { \
512 if (check_bytes_find(H, N, O, E) < 0) { \
513 return NULL; \
514 } \
515 } while (0)
516
517 CHECK("", "", 0, 0);
518 CHECK("Python", "", 0, 0);
519 CHECK("Python", "", 3, 3);
520 CHECK("Python", "", 6, 6);
521 CHECK("Python", "yth", 0, 1);
522 CHECK("ython", "yth", 1, 1);
523 CHECK("thon", "yth", 2, -1);
524 CHECK("Python", "thon", 0, 2);
525 CHECK("ython", "thon", 1, 2);
526 CHECK("thon", "thon", 2, 2);
527 CHECK("hon", "thon", 3, -1);
528 CHECK("Pytho", "zz", 0, -1);
529 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "ab", 0, -1);
530 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "ba", 0, -1);
531 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bb", 0, -1);
532 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", "ab", 0, 30);
533 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaba", "ba", 0, 30);
534 CHECK("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabb", "bb", 0, 30);
535 #undef CHECK
536
537 // Hunt for segfaults
538 // n, m chosen here so that (n - m) % (m + 1) == 0
539 // This would make default_find in fastsearch.h access haystack[n].
540 if (check_bytes_find_large(2048, 2, "ab") < 0) {
541 return NULL;
542 }
543 if (check_bytes_find_large(4096, 16, "0123456789abcdef") < 0) {
544 return NULL;
545 }
546 if (check_bytes_find_large(8192, 2, "ab") < 0) {
547 return NULL;
548 }
549 if (check_bytes_find_large(16384, 4, "abcd") < 0) {
550 return NULL;
551 }
552 if (check_bytes_find_large(32768, 2, "ab") < 0) {
553 return NULL;
554 }
555 Py_RETURN_NONE;
556 }
557
558
559 static PyObject *
normalize_path(PyObject * self,PyObject * filename)560 normalize_path(PyObject *self, PyObject *filename)
561 {
562 Py_ssize_t size = -1;
563 wchar_t *encoded = PyUnicode_AsWideCharString(filename, &size);
564 if (encoded == NULL) {
565 return NULL;
566 }
567
568 PyObject *result = PyUnicode_FromWideChar(_Py_normpath(encoded, size), -1);
569 PyMem_Free(encoded);
570
571 return result;
572 }
573
574 static PyObject *
get_getpath_codeobject(PyObject * self,PyObject * Py_UNUSED (args))575 get_getpath_codeobject(PyObject *self, PyObject *Py_UNUSED(args)) {
576 return _Py_Get_Getpath_CodeObject();
577 }
578
579
580 static PyObject *
encode_locale_ex(PyObject * self,PyObject * args)581 encode_locale_ex(PyObject *self, PyObject *args)
582 {
583 PyObject *unicode;
584 int current_locale = 0;
585 wchar_t *wstr;
586 PyObject *res = NULL;
587 const char *errors = NULL;
588
589 if (!PyArg_ParseTuple(args, "U|is", &unicode, ¤t_locale, &errors)) {
590 return NULL;
591 }
592 wstr = PyUnicode_AsWideCharString(unicode, NULL);
593 if (wstr == NULL) {
594 return NULL;
595 }
596 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
597
598 char *str = NULL;
599 size_t error_pos;
600 const char *reason = NULL;
601 int ret = _Py_EncodeLocaleEx(wstr,
602 &str, &error_pos, &reason,
603 current_locale, error_handler);
604 PyMem_Free(wstr);
605
606 switch(ret) {
607 case 0:
608 res = PyBytes_FromString(str);
609 PyMem_RawFree(str);
610 break;
611 case -1:
612 PyErr_NoMemory();
613 break;
614 case -2:
615 PyErr_Format(PyExc_RuntimeError, "encode error: pos=%zu, reason=%s",
616 error_pos, reason);
617 break;
618 case -3:
619 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
620 break;
621 default:
622 PyErr_SetString(PyExc_ValueError, "unknown error code");
623 break;
624 }
625 return res;
626 }
627
628
629 static PyObject *
decode_locale_ex(PyObject * self,PyObject * args)630 decode_locale_ex(PyObject *self, PyObject *args)
631 {
632 char *str;
633 int current_locale = 0;
634 PyObject *res = NULL;
635 const char *errors = NULL;
636
637 if (!PyArg_ParseTuple(args, "y|is", &str, ¤t_locale, &errors)) {
638 return NULL;
639 }
640 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
641
642 wchar_t *wstr = NULL;
643 size_t wlen = 0;
644 const char *reason = NULL;
645 int ret = _Py_DecodeLocaleEx(str,
646 &wstr, &wlen, &reason,
647 current_locale, error_handler);
648
649 switch(ret) {
650 case 0:
651 res = PyUnicode_FromWideChar(wstr, wlen);
652 PyMem_RawFree(wstr);
653 break;
654 case -1:
655 PyErr_NoMemory();
656 break;
657 case -2:
658 PyErr_Format(PyExc_RuntimeError, "decode error: pos=%zu, reason=%s",
659 wlen, reason);
660 break;
661 case -3:
662 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
663 break;
664 default:
665 PyErr_SetString(PyExc_ValueError, "unknown error code");
666 break;
667 }
668 return res;
669 }
670
671 static PyObject *
set_eval_frame_default(PyObject * self,PyObject * Py_UNUSED (args))672 set_eval_frame_default(PyObject *self, PyObject *Py_UNUSED(args))
673 {
674 module_state *state = get_module_state(self);
675 _PyInterpreterState_SetEvalFrameFunc(_PyInterpreterState_GET(), _PyEval_EvalFrameDefault);
676 Py_CLEAR(state->record_list);
677 Py_RETURN_NONE;
678 }
679
680 static PyObject *
record_eval(PyThreadState * tstate,struct _PyInterpreterFrame * f,int exc)681 record_eval(PyThreadState *tstate, struct _PyInterpreterFrame *f, int exc)
682 {
683 if (PyFunction_Check(f->f_funcobj)) {
684 PyObject *module = _get_current_module();
685 assert(module != NULL);
686 module_state *state = get_module_state(module);
687 Py_DECREF(module);
688 int res = PyList_Append(state->record_list,
689 ((PyFunctionObject *)f->f_funcobj)->func_name);
690 if (res < 0) {
691 return NULL;
692 }
693 }
694 return _PyEval_EvalFrameDefault(tstate, f, exc);
695 }
696
697
698 static PyObject *
set_eval_frame_record(PyObject * self,PyObject * list)699 set_eval_frame_record(PyObject *self, PyObject *list)
700 {
701 module_state *state = get_module_state(self);
702 if (!PyList_Check(list)) {
703 PyErr_SetString(PyExc_TypeError, "argument must be a list");
704 return NULL;
705 }
706 Py_XSETREF(state->record_list, Py_NewRef(list));
707 _PyInterpreterState_SetEvalFrameFunc(_PyInterpreterState_GET(), record_eval);
708 Py_RETURN_NONE;
709 }
710
711 /*[clinic input]
712
713 _testinternalcapi.compiler_cleandoc -> object
714
715 doc: unicode
716
717 C implementation of inspect.cleandoc().
718 [clinic start generated code]*/
719
720 static PyObject *
_testinternalcapi_compiler_cleandoc_impl(PyObject * module,PyObject * doc)721 _testinternalcapi_compiler_cleandoc_impl(PyObject *module, PyObject *doc)
722 /*[clinic end generated code: output=2dd203a80feff5bc input=2de03fab931d9cdc]*/
723 {
724 return _PyCompile_CleanDoc(doc);
725 }
726
727 /*[clinic input]
728
729 _testinternalcapi.new_instruction_sequence -> object
730
731 Return a new, empty InstructionSequence.
732 [clinic start generated code]*/
733
734 static PyObject *
_testinternalcapi_new_instruction_sequence_impl(PyObject * module)735 _testinternalcapi_new_instruction_sequence_impl(PyObject *module)
736 /*[clinic end generated code: output=ea4243fddb9057fd input=1dec2591b173be83]*/
737 {
738 return _PyInstructionSequence_New();
739 }
740
741 /*[clinic input]
742
743 _testinternalcapi.compiler_codegen -> object
744
745 ast: object
746 filename: object
747 optimize: int
748 compile_mode: int = 0
749
750 Apply compiler code generation to an AST.
751 [clinic start generated code]*/
752
753 static PyObject *
_testinternalcapi_compiler_codegen_impl(PyObject * module,PyObject * ast,PyObject * filename,int optimize,int compile_mode)754 _testinternalcapi_compiler_codegen_impl(PyObject *module, PyObject *ast,
755 PyObject *filename, int optimize,
756 int compile_mode)
757 /*[clinic end generated code: output=40a68f6e13951cc8 input=a0e00784f1517cd7]*/
758 {
759 PyCompilerFlags *flags = NULL;
760 return _PyCompile_CodeGen(ast, filename, flags, optimize, compile_mode);
761 }
762
763
764 /*[clinic input]
765
766 _testinternalcapi.optimize_cfg -> object
767
768 instructions: object
769 consts: object
770 nlocals: int
771
772 Apply compiler optimizations to an instruction list.
773 [clinic start generated code]*/
774
775 static PyObject *
_testinternalcapi_optimize_cfg_impl(PyObject * module,PyObject * instructions,PyObject * consts,int nlocals)776 _testinternalcapi_optimize_cfg_impl(PyObject *module, PyObject *instructions,
777 PyObject *consts, int nlocals)
778 /*[clinic end generated code: output=57c53c3a3dfd1df0 input=6a96d1926d58d7e5]*/
779 {
780 return _PyCompile_OptimizeCfg(instructions, consts, nlocals);
781 }
782
783 static int
get_nonnegative_int_from_dict(PyObject * dict,const char * key)784 get_nonnegative_int_from_dict(PyObject *dict, const char *key) {
785 PyObject *obj = PyDict_GetItemString(dict, key);
786 if (obj == NULL) {
787 return -1;
788 }
789 return PyLong_AsLong(obj);
790 }
791
792 /*[clinic input]
793
794 _testinternalcapi.assemble_code_object -> object
795
796 filename: object
797 instructions: object
798 metadata: object
799
800 Create a code object for the given instructions.
801 [clinic start generated code]*/
802
803 static PyObject *
_testinternalcapi_assemble_code_object_impl(PyObject * module,PyObject * filename,PyObject * instructions,PyObject * metadata)804 _testinternalcapi_assemble_code_object_impl(PyObject *module,
805 PyObject *filename,
806 PyObject *instructions,
807 PyObject *metadata)
808 /*[clinic end generated code: output=38003dc16a930f48 input=e713ad77f08fb3a8]*/
809
810 {
811 assert(PyDict_Check(metadata));
812 _PyCompile_CodeUnitMetadata umd;
813
814 umd.u_name = PyDict_GetItemString(metadata, "name");
815 umd.u_qualname = PyDict_GetItemString(metadata, "qualname");
816
817 assert(PyUnicode_Check(umd.u_name));
818 assert(PyUnicode_Check(umd.u_qualname));
819
820 umd.u_consts = PyDict_GetItemString(metadata, "consts");
821 umd.u_names = PyDict_GetItemString(metadata, "names");
822 umd.u_varnames = PyDict_GetItemString(metadata, "varnames");
823 umd.u_cellvars = PyDict_GetItemString(metadata, "cellvars");
824 umd.u_freevars = PyDict_GetItemString(metadata, "freevars");
825 umd.u_fasthidden = PyDict_GetItemString(metadata, "fasthidden");
826
827 assert(PyDict_Check(umd.u_consts));
828 assert(PyDict_Check(umd.u_names));
829 assert(PyDict_Check(umd.u_varnames));
830 assert(PyDict_Check(umd.u_cellvars));
831 assert(PyDict_Check(umd.u_freevars));
832 assert(PyDict_Check(umd.u_fasthidden));
833
834 umd.u_argcount = get_nonnegative_int_from_dict(metadata, "argcount");
835 umd.u_posonlyargcount = get_nonnegative_int_from_dict(metadata, "posonlyargcount");
836 umd.u_kwonlyargcount = get_nonnegative_int_from_dict(metadata, "kwonlyargcount");
837 umd.u_firstlineno = get_nonnegative_int_from_dict(metadata, "firstlineno");
838
839 assert(umd.u_argcount >= 0);
840 assert(umd.u_posonlyargcount >= 0);
841 assert(umd.u_kwonlyargcount >= 0);
842 assert(umd.u_firstlineno >= 0);
843
844 return (PyObject*)_PyCompile_Assemble(&umd, filename, instructions);
845 }
846
847
848 // Maybe this could be replaced by get_interpreter_config()?
849 static PyObject *
get_interp_settings(PyObject * self,PyObject * args)850 get_interp_settings(PyObject *self, PyObject *args)
851 {
852 int interpid = -1;
853 if (!PyArg_ParseTuple(args, "|i:get_interp_settings", &interpid)) {
854 return NULL;
855 }
856
857 PyInterpreterState *interp = NULL;
858 if (interpid < 0) {
859 PyThreadState *tstate = _PyThreadState_GET();
860 interp = tstate ? tstate->interp : _PyInterpreterState_Main();
861 }
862 else if (interpid == 0) {
863 interp = _PyInterpreterState_Main();
864 }
865 else {
866 PyErr_Format(PyExc_NotImplementedError,
867 "%zd", interpid);
868 return NULL;
869 }
870 assert(interp != NULL);
871
872 PyObject *settings = PyDict_New();
873 if (settings == NULL) {
874 return NULL;
875 }
876
877 /* Add the feature flags. */
878 PyObject *flags = PyLong_FromUnsignedLong(interp->feature_flags);
879 if (flags == NULL) {
880 Py_DECREF(settings);
881 return NULL;
882 }
883 int res = PyDict_SetItemString(settings, "feature_flags", flags);
884 Py_DECREF(flags);
885 if (res != 0) {
886 Py_DECREF(settings);
887 return NULL;
888 }
889
890 /* "own GIL" */
891 PyObject *own_gil = interp->ceval.own_gil ? Py_True : Py_False;
892 if (PyDict_SetItemString(settings, "own_gil", own_gil) != 0) {
893 Py_DECREF(settings);
894 return NULL;
895 }
896
897 return settings;
898 }
899
900
901 static PyObject *
clear_extension(PyObject * self,PyObject * args)902 clear_extension(PyObject *self, PyObject *args)
903 {
904 PyObject *name = NULL, *filename = NULL;
905 if (!PyArg_ParseTuple(args, "OO:clear_extension", &name, &filename)) {
906 return NULL;
907 }
908 if (_PyImport_ClearExtension(name, filename) < 0) {
909 return NULL;
910 }
911 Py_RETURN_NONE;
912 }
913
914 static PyObject *
write_perf_map_entry(PyObject * self,PyObject * args)915 write_perf_map_entry(PyObject *self, PyObject *args)
916 {
917 PyObject *code_addr_v;
918 const void *code_addr;
919 unsigned int code_size;
920 const char *entry_name;
921
922 if (!PyArg_ParseTuple(args, "OIs", &code_addr_v, &code_size, &entry_name))
923 return NULL;
924 code_addr = PyLong_AsVoidPtr(code_addr_v);
925 if (code_addr == NULL) {
926 return NULL;
927 }
928
929 int ret = PyUnstable_WritePerfMapEntry(code_addr, code_size, entry_name);
930 if (ret < 0) {
931 PyErr_SetFromErrno(PyExc_OSError);
932 return NULL;
933 }
934 return PyLong_FromLong(ret);
935 }
936
937 static PyObject *
perf_map_state_teardown(PyObject * Py_UNUSED (self),PyObject * Py_UNUSED (ignored))938 perf_map_state_teardown(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(ignored))
939 {
940 PyUnstable_PerfMapState_Fini();
941 Py_RETURN_NONE;
942 }
943
944 static PyObject *
iframe_getcode(PyObject * self,PyObject * frame)945 iframe_getcode(PyObject *self, PyObject *frame)
946 {
947 if (!PyFrame_Check(frame)) {
948 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
949 return NULL;
950 }
951 struct _PyInterpreterFrame *f = ((PyFrameObject *)frame)->f_frame;
952 return PyUnstable_InterpreterFrame_GetCode(f);
953 }
954
955 static PyObject *
iframe_getline(PyObject * self,PyObject * frame)956 iframe_getline(PyObject *self, PyObject *frame)
957 {
958 if (!PyFrame_Check(frame)) {
959 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
960 return NULL;
961 }
962 struct _PyInterpreterFrame *f = ((PyFrameObject *)frame)->f_frame;
963 return PyLong_FromLong(PyUnstable_InterpreterFrame_GetLine(f));
964 }
965
966 static PyObject *
iframe_getlasti(PyObject * self,PyObject * frame)967 iframe_getlasti(PyObject *self, PyObject *frame)
968 {
969 if (!PyFrame_Check(frame)) {
970 PyErr_SetString(PyExc_TypeError, "argument must be a frame");
971 return NULL;
972 }
973 struct _PyInterpreterFrame *f = ((PyFrameObject *)frame)->f_frame;
974 return PyLong_FromLong(PyUnstable_InterpreterFrame_GetLasti(f));
975 }
976
977 static PyObject *
get_co_framesize(PyObject * self,PyObject * arg)978 get_co_framesize(PyObject *self, PyObject *arg)
979 {
980 if (!PyCode_Check(arg)) {
981 PyErr_SetString(PyExc_TypeError, "argument must be a code object");
982 return NULL;
983 }
984 PyCodeObject *code = (PyCodeObject *)arg;
985 return PyLong_FromLong(code->co_framesize);
986 }
987
988 #ifdef _Py_TIER2
989
990 static PyObject *
new_counter_optimizer(PyObject * self,PyObject * arg)991 new_counter_optimizer(PyObject *self, PyObject *arg)
992 {
993 return _PyOptimizer_NewCounter();
994 }
995
996 static PyObject *
new_uop_optimizer(PyObject * self,PyObject * arg)997 new_uop_optimizer(PyObject *self, PyObject *arg)
998 {
999 return _PyOptimizer_NewUOpOptimizer();
1000 }
1001
1002 static PyObject *
set_optimizer(PyObject * self,PyObject * opt)1003 set_optimizer(PyObject *self, PyObject *opt)
1004 {
1005 if (opt == Py_None) {
1006 opt = NULL;
1007 }
1008 if (_Py_SetTier2Optimizer((_PyOptimizerObject*)opt) < 0) {
1009 return NULL;
1010 }
1011 Py_RETURN_NONE;
1012 }
1013
1014 static PyObject *
get_optimizer(PyObject * self,PyObject * Py_UNUSED (ignored))1015 get_optimizer(PyObject *self, PyObject *Py_UNUSED(ignored))
1016 {
1017 PyObject *opt = NULL;
1018 #ifdef _Py_TIER2
1019 opt = (PyObject *)_Py_GetOptimizer();
1020 #endif
1021 if (opt == NULL) {
1022 Py_RETURN_NONE;
1023 }
1024 return opt;
1025 }
1026
1027 static PyObject *
add_executor_dependency(PyObject * self,PyObject * args)1028 add_executor_dependency(PyObject *self, PyObject *args)
1029 {
1030 PyObject *exec;
1031 PyObject *obj;
1032 if (!PyArg_ParseTuple(args, "OO", &exec, &obj)) {
1033 return NULL;
1034 }
1035 /* No way to tell in general if exec is an executor, so we only accept
1036 * counting_executor */
1037 if (strcmp(Py_TYPE(exec)->tp_name, "counting_executor")) {
1038 PyErr_SetString(PyExc_TypeError, "argument must be a counting_executor");
1039 return NULL;
1040 }
1041 _Py_Executor_DependsOn((_PyExecutorObject *)exec, obj);
1042 Py_RETURN_NONE;
1043 }
1044
1045 static PyObject *
invalidate_executors(PyObject * self,PyObject * obj)1046 invalidate_executors(PyObject *self, PyObject *obj)
1047 {
1048 PyInterpreterState *interp = PyInterpreterState_Get();
1049 _Py_Executors_InvalidateDependency(interp, obj, 1);
1050 Py_RETURN_NONE;
1051 }
1052
1053 #endif
1054
_pending_callback(void * arg)1055 static int _pending_callback(void *arg)
1056 {
1057 /* we assume the argument is callable object to which we own a reference */
1058 PyObject *callable = (PyObject *)arg;
1059 PyObject *r = PyObject_CallNoArgs(callable);
1060 Py_DECREF(callable);
1061 Py_XDECREF(r);
1062 return r != NULL ? 0 : -1;
1063 }
1064
1065 /* The following requests n callbacks to _pending_callback. It can be
1066 * run from any python thread.
1067 */
1068 static PyObject *
pending_threadfunc(PyObject * self,PyObject * args,PyObject * kwargs)1069 pending_threadfunc(PyObject *self, PyObject *args, PyObject *kwargs)
1070 {
1071 PyObject *callable;
1072 unsigned int num = 1;
1073 int blocking = 0;
1074 int ensure_added = 0;
1075 static char *kwlist[] = {"callback", "num",
1076 "blocking", "ensure_added", NULL};
1077 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1078 "O|I$pp:pending_threadfunc", kwlist,
1079 &callable, &num, &blocking, &ensure_added))
1080 {
1081 return NULL;
1082 }
1083 PyInterpreterState *interp = _PyInterpreterState_GET();
1084
1085 /* create the reference for the callbackwhile we hold the lock */
1086 for (unsigned int i = 0; i < num; i++) {
1087 Py_INCREF(callable);
1088 }
1089
1090 PyThreadState *save_tstate = NULL;
1091 if (!blocking) {
1092 save_tstate = PyEval_SaveThread();
1093 }
1094
1095 unsigned int num_added = 0;
1096 for (; num_added < num; num_added++) {
1097 if (ensure_added) {
1098 _Py_add_pending_call_result r;
1099 do {
1100 r = _PyEval_AddPendingCall(interp, &_pending_callback, callable, 0);
1101 assert(r == _Py_ADD_PENDING_SUCCESS
1102 || r == _Py_ADD_PENDING_FULL);
1103 } while (r == _Py_ADD_PENDING_FULL);
1104 }
1105 else {
1106 if (_PyEval_AddPendingCall(interp, &_pending_callback, callable, 0) < 0) {
1107 break;
1108 }
1109 }
1110 }
1111
1112 if (!blocking) {
1113 PyEval_RestoreThread(save_tstate);
1114 }
1115
1116 for (unsigned int i = num_added; i < num; i++) {
1117 Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
1118 }
1119
1120 /* The callable is decref'ed in _pending_callback() above. */
1121 return PyLong_FromUnsignedLong((unsigned long)num_added);
1122 }
1123
1124
1125 static struct {
1126 int64_t interpid;
1127 } pending_identify_result;
1128
1129 static int
_pending_identify_callback(void * arg)1130 _pending_identify_callback(void *arg)
1131 {
1132 PyThread_type_lock mutex = (PyThread_type_lock)arg;
1133 assert(pending_identify_result.interpid == -1);
1134 PyThreadState *tstate = PyThreadState_Get();
1135 pending_identify_result.interpid = PyInterpreterState_GetID(tstate->interp);
1136 PyThread_release_lock(mutex);
1137 return 0;
1138 }
1139
1140 static PyObject *
pending_identify(PyObject * self,PyObject * args)1141 pending_identify(PyObject *self, PyObject *args)
1142 {
1143 PyObject *interpid;
1144 if (!PyArg_ParseTuple(args, "O:pending_identify", &interpid)) {
1145 return NULL;
1146 }
1147 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(interpid);
1148 if (interp == NULL) {
1149 if (!PyErr_Occurred()) {
1150 PyErr_SetString(PyExc_ValueError, "interpreter not found");
1151 }
1152 return NULL;
1153 }
1154
1155 pending_identify_result.interpid = -1;
1156
1157 PyThread_type_lock mutex = PyThread_allocate_lock();
1158 if (mutex == NULL) {
1159 return NULL;
1160 }
1161 PyThread_acquire_lock(mutex, WAIT_LOCK);
1162 /* It gets released in _pending_identify_callback(). */
1163
1164 _Py_add_pending_call_result r;
1165 do {
1166 Py_BEGIN_ALLOW_THREADS
1167 r = _PyEval_AddPendingCall(interp,
1168 &_pending_identify_callback, (void *)mutex,
1169 0);
1170 Py_END_ALLOW_THREADS
1171 assert(r == _Py_ADD_PENDING_SUCCESS
1172 || r == _Py_ADD_PENDING_FULL);
1173 } while (r == _Py_ADD_PENDING_FULL);
1174
1175 /* Wait for the pending call to complete. */
1176 PyThread_acquire_lock(mutex, WAIT_LOCK);
1177 PyThread_release_lock(mutex);
1178 PyThread_free_lock(mutex);
1179
1180 PyObject *res = PyLong_FromLongLong(pending_identify_result.interpid);
1181 pending_identify_result.interpid = -1;
1182 if (res == NULL) {
1183 return NULL;
1184 }
1185 return res;
1186 }
1187
1188 static PyObject *
tracemalloc_get_traceback(PyObject * self,PyObject * args)1189 tracemalloc_get_traceback(PyObject *self, PyObject *args)
1190 {
1191 unsigned int domain;
1192 PyObject *ptr_obj;
1193
1194 if (!PyArg_ParseTuple(args, "IO", &domain, &ptr_obj)) {
1195 return NULL;
1196 }
1197 void *ptr = PyLong_AsVoidPtr(ptr_obj);
1198 if (PyErr_Occurred()) {
1199 return NULL;
1200 }
1201
1202 return _PyTraceMalloc_GetTraceback(domain, (uintptr_t)ptr);
1203 }
1204
1205
1206 // Test PyThreadState C API
1207 static PyObject *
test_tstate_capi(PyObject * self,PyObject * Py_UNUSED (args))1208 test_tstate_capi(PyObject *self, PyObject *Py_UNUSED(args))
1209 {
1210 // PyThreadState_Get()
1211 PyThreadState *tstate = PyThreadState_Get();
1212 assert(tstate != NULL);
1213
1214 // test _PyThreadState_GetDict()
1215 PyObject *dict = PyThreadState_GetDict();
1216 assert(dict != NULL);
1217 // dict is a borrowed reference
1218
1219 PyObject *dict2 = _PyThreadState_GetDict(tstate);
1220 assert(dict2 == dict);
1221 // dict2 is a borrowed reference
1222
1223 Py_RETURN_NONE;
1224 }
1225
1226
1227 /* Test _PyUnicode_TransformDecimalAndSpaceToASCII() */
1228 static PyObject *
unicode_transformdecimalandspacetoascii(PyObject * self,PyObject * arg)1229 unicode_transformdecimalandspacetoascii(PyObject *self, PyObject *arg)
1230 {
1231 if (arg == Py_None) {
1232 arg = NULL;
1233 }
1234 return _PyUnicode_TransformDecimalAndSpaceToASCII(arg);
1235 }
1236
1237
1238 struct atexit_data {
1239 int called;
1240 };
1241
1242 static void
callback(void * data)1243 callback(void *data)
1244 {
1245 ((struct atexit_data *)data)->called += 1;
1246 }
1247
1248 static PyObject *
test_atexit(PyObject * self,PyObject * Py_UNUSED (args))1249 test_atexit(PyObject *self, PyObject *Py_UNUSED(args))
1250 {
1251 PyThreadState *oldts = PyThreadState_Swap(NULL);
1252 PyThreadState *tstate = Py_NewInterpreter();
1253
1254 struct atexit_data data = {0};
1255 int res = PyUnstable_AtExit(tstate->interp, callback, (void *)&data);
1256 Py_EndInterpreter(tstate);
1257 PyThreadState_Swap(oldts);
1258 if (res < 0) {
1259 return NULL;
1260 }
1261
1262 if (data.called == 0) {
1263 PyErr_SetString(PyExc_RuntimeError, "atexit callback not called");
1264 return NULL;
1265 }
1266 Py_RETURN_NONE;
1267 }
1268
1269
1270 static PyObject *
test_pyobject_is_freed(const char * test_name,PyObject * op)1271 test_pyobject_is_freed(const char *test_name, PyObject *op)
1272 {
1273 if (!_PyObject_IsFreed(op)) {
1274 PyErr_SetString(PyExc_AssertionError,
1275 "object is not seen as freed");
1276 return NULL;
1277 }
1278 Py_RETURN_NONE;
1279 }
1280
1281 static PyObject *
check_pyobject_null_is_freed(PyObject * self,PyObject * Py_UNUSED (args))1282 check_pyobject_null_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
1283 {
1284 PyObject *op = NULL;
1285 return test_pyobject_is_freed("check_pyobject_null_is_freed", op);
1286 }
1287
1288
1289 static PyObject *
check_pyobject_uninitialized_is_freed(PyObject * self,PyObject * Py_UNUSED (args))1290 check_pyobject_uninitialized_is_freed(PyObject *self,
1291 PyObject *Py_UNUSED(args))
1292 {
1293 PyObject *op = (PyObject *)PyObject_Malloc(sizeof(PyObject));
1294 if (op == NULL) {
1295 return NULL;
1296 }
1297 /* Initialize reference count to avoid early crash in ceval or GC */
1298 Py_SET_REFCNT(op, 1);
1299 /* object fields like ob_type are uninitialized! */
1300 return test_pyobject_is_freed("check_pyobject_uninitialized_is_freed", op);
1301 }
1302
1303
1304 static PyObject *
check_pyobject_forbidden_bytes_is_freed(PyObject * self,PyObject * Py_UNUSED (args))1305 check_pyobject_forbidden_bytes_is_freed(PyObject *self,
1306 PyObject *Py_UNUSED(args))
1307 {
1308 /* Allocate an incomplete PyObject structure: truncate 'ob_type' field */
1309 PyObject *op = (PyObject *)PyObject_Malloc(offsetof(PyObject, ob_type));
1310 if (op == NULL) {
1311 return NULL;
1312 }
1313 /* Initialize reference count to avoid early crash in ceval or GC */
1314 Py_SET_REFCNT(op, 1);
1315 /* ob_type field is after the memory block: part of "forbidden bytes"
1316 when using debug hooks on memory allocators! */
1317 return test_pyobject_is_freed("check_pyobject_forbidden_bytes_is_freed", op);
1318 }
1319
1320
1321 static PyObject *
check_pyobject_freed_is_freed(PyObject * self,PyObject * Py_UNUSED (args))1322 check_pyobject_freed_is_freed(PyObject *self, PyObject *Py_UNUSED(args))
1323 {
1324 /* ASan or TSan would report an use-after-free error */
1325 #if defined(_Py_ADDRESS_SANITIZER) || defined(_Py_THREAD_SANITIZER)
1326 Py_RETURN_NONE;
1327 #else
1328 PyObject *op = PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
1329 if (op == NULL) {
1330 return NULL;
1331 }
1332 Py_TYPE(op)->tp_dealloc(op);
1333 /* Reset reference count to avoid early crash in ceval or GC */
1334 Py_SET_REFCNT(op, 1);
1335 /* object memory is freed! */
1336 return test_pyobject_is_freed("check_pyobject_freed_is_freed", op);
1337 #endif
1338 }
1339
1340
1341 static PyObject *
test_pymem_getallocatorsname(PyObject * self,PyObject * args)1342 test_pymem_getallocatorsname(PyObject *self, PyObject *args)
1343 {
1344 const char *name = _PyMem_GetCurrentAllocatorName();
1345 if (name == NULL) {
1346 PyErr_SetString(PyExc_RuntimeError, "cannot get allocators name");
1347 return NULL;
1348 }
1349 return PyUnicode_FromString(name);
1350 }
1351
1352 static PyObject *
get_object_dict_values(PyObject * self,PyObject * obj)1353 get_object_dict_values(PyObject *self, PyObject *obj)
1354 {
1355 PyTypeObject *type = Py_TYPE(obj);
1356 if (!_PyType_HasFeature(type, Py_TPFLAGS_INLINE_VALUES)) {
1357 Py_RETURN_NONE;
1358 }
1359 PyDictValues *values = _PyObject_InlineValues(obj);
1360 if (!values->valid) {
1361 Py_RETURN_NONE;
1362 }
1363 PyDictKeysObject *keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
1364 assert(keys != NULL);
1365 int size = (int)keys->dk_nentries;
1366 assert(size >= 0);
1367 PyObject *res = PyTuple_New(size);
1368 if (res == NULL) {
1369 return NULL;
1370 }
1371 _Py_DECLARE_STR(anon_null, "<NULL>");
1372 for(int i = 0; i < size; i++) {
1373 PyObject *item = values->values[i];
1374 if (item == NULL) {
1375 item = &_Py_STR(anon_null);
1376 }
1377 else {
1378 Py_INCREF(item);
1379 }
1380 PyTuple_SET_ITEM(res, i, item);
1381 }
1382 return res;
1383 }
1384
1385
1386 static PyObject*
new_hamt(PyObject * self,PyObject * args)1387 new_hamt(PyObject *self, PyObject *args)
1388 {
1389 return _PyContext_NewHamtForTests();
1390 }
1391
1392
1393 static PyObject*
dict_getitem_knownhash(PyObject * self,PyObject * args)1394 dict_getitem_knownhash(PyObject *self, PyObject *args)
1395 {
1396 PyObject *mp, *key, *result;
1397 Py_ssize_t hash;
1398
1399 if (!PyArg_ParseTuple(args, "OOn:dict_getitem_knownhash",
1400 &mp, &key, &hash)) {
1401 return NULL;
1402 }
1403
1404 result = _PyDict_GetItem_KnownHash(mp, key, (Py_hash_t)hash);
1405 if (result == NULL && !PyErr_Occurred()) {
1406 _PyErr_SetKeyError(key);
1407 return NULL;
1408 }
1409
1410 return Py_XNewRef(result);
1411 }
1412
1413
1414 static int
_init_interp_config_from_object(PyInterpreterConfig * config,PyObject * obj)1415 _init_interp_config_from_object(PyInterpreterConfig *config, PyObject *obj)
1416 {
1417 if (obj == NULL) {
1418 *config = (PyInterpreterConfig)_PyInterpreterConfig_INIT;
1419 return 0;
1420 }
1421
1422 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
1423 if (dict == NULL) {
1424 PyErr_Format(PyExc_TypeError, "bad config %R", obj);
1425 return -1;
1426 }
1427 int res = _PyInterpreterConfig_InitFromDict(config, dict);
1428 Py_DECREF(dict);
1429 if (res < 0) {
1430 return -1;
1431 }
1432 return 0;
1433 }
1434
1435 static PyInterpreterState *
_new_interpreter(PyInterpreterConfig * config,long whence)1436 _new_interpreter(PyInterpreterConfig *config, long whence)
1437 {
1438 if (whence == _PyInterpreterState_WHENCE_XI) {
1439 return _PyXI_NewInterpreter(config, &whence, NULL, NULL);
1440 }
1441 PyObject *exc = NULL;
1442 PyInterpreterState *interp = NULL;
1443 if (whence == _PyInterpreterState_WHENCE_UNKNOWN) {
1444 assert(config == NULL);
1445 interp = PyInterpreterState_New();
1446 }
1447 else if (whence == _PyInterpreterState_WHENCE_CAPI
1448 || whence == _PyInterpreterState_WHENCE_LEGACY_CAPI)
1449 {
1450 PyThreadState *tstate = NULL;
1451 PyThreadState *save_tstate = PyThreadState_Swap(NULL);
1452 if (whence == _PyInterpreterState_WHENCE_LEGACY_CAPI) {
1453 assert(config == NULL);
1454 tstate = Py_NewInterpreter();
1455 PyThreadState_Swap(save_tstate);
1456 }
1457 else {
1458 PyStatus status = Py_NewInterpreterFromConfig(&tstate, config);
1459 PyThreadState_Swap(save_tstate);
1460 if (PyStatus_Exception(status)) {
1461 assert(tstate == NULL);
1462 _PyErr_SetFromPyStatus(status);
1463 exc = PyErr_GetRaisedException();
1464 }
1465 }
1466 if (tstate != NULL) {
1467 interp = PyThreadState_GetInterpreter(tstate);
1468 // Throw away the initial tstate.
1469 PyThreadState_Swap(tstate);
1470 PyThreadState_Clear(tstate);
1471 PyThreadState_Swap(save_tstate);
1472 PyThreadState_Delete(tstate);
1473 }
1474 }
1475 else {
1476 PyErr_Format(PyExc_ValueError,
1477 "unsupported whence %ld", whence);
1478 return NULL;
1479 }
1480
1481 if (interp == NULL) {
1482 PyErr_SetString(PyExc_InterpreterError,
1483 "sub-interpreter creation failed");
1484 if (exc != NULL) {
1485 _PyErr_ChainExceptions1(exc);
1486 }
1487 }
1488 return interp;
1489 }
1490
1491 // This exists mostly for testing the _interpreters module, as an
1492 // alternative to _interpreters.create()
1493 static PyObject *
create_interpreter(PyObject * self,PyObject * args,PyObject * kwargs)1494 create_interpreter(PyObject *self, PyObject *args, PyObject *kwargs)
1495 {
1496 static char *kwlist[] = {"config", "whence", NULL};
1497 PyObject *configobj = NULL;
1498 long whence = _PyInterpreterState_WHENCE_XI;
1499 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1500 "|O$l:create_interpreter", kwlist,
1501 &configobj, &whence))
1502 {
1503 return NULL;
1504 }
1505 if (configobj == Py_None) {
1506 configobj = NULL;
1507 }
1508
1509 // Resolve the config.
1510 PyInterpreterConfig *config = NULL;
1511 PyInterpreterConfig _config;
1512 if (whence == _PyInterpreterState_WHENCE_UNKNOWN
1513 || whence == _PyInterpreterState_WHENCE_LEGACY_CAPI)
1514 {
1515 if (configobj != NULL) {
1516 PyErr_SetString(PyExc_ValueError, "got unexpected config");
1517 return NULL;
1518 }
1519 }
1520 else {
1521 config = &_config;
1522 if (_init_interp_config_from_object(config, configobj) < 0) {
1523 return NULL;
1524 }
1525 }
1526
1527 // Create the interpreter.
1528 PyInterpreterState *interp = _new_interpreter(config, whence);
1529 if (interp == NULL) {
1530 return NULL;
1531 }
1532
1533 // Return the ID.
1534 PyObject *idobj = _PyInterpreterState_GetIDObject(interp);
1535 if (idobj == NULL) {
1536 _PyXI_EndInterpreter(interp, NULL, NULL);
1537 return NULL;
1538 }
1539
1540 return idobj;
1541 }
1542
1543 // This exists mostly for testing the _interpreters module, as an
1544 // alternative to _interpreters.destroy()
1545 static PyObject *
destroy_interpreter(PyObject * self,PyObject * args,PyObject * kwargs)1546 destroy_interpreter(PyObject *self, PyObject *args, PyObject *kwargs)
1547 {
1548 static char *kwlist[] = {"id", NULL};
1549 PyObject *idobj = NULL;
1550 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1551 "O:destroy_interpreter", kwlist,
1552 &idobj))
1553 {
1554 return NULL;
1555 }
1556
1557 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1558 if (interp == NULL) {
1559 return NULL;
1560 }
1561
1562 _PyXI_EndInterpreter(interp, NULL, NULL);
1563 Py_RETURN_NONE;
1564 }
1565
1566 // This exists mostly for testing the _interpreters module, as an
1567 // alternative to _interpreters.destroy()
1568 static PyObject *
exec_interpreter(PyObject * self,PyObject * args,PyObject * kwargs)1569 exec_interpreter(PyObject *self, PyObject *args, PyObject *kwargs)
1570 {
1571 static char *kwlist[] = {"id", "code", "main", NULL};
1572 PyObject *idobj;
1573 const char *code;
1574 int runningmain = 0;
1575 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1576 "Os|$p:exec_interpreter", kwlist,
1577 &idobj, &code, &runningmain))
1578 {
1579 return NULL;
1580 }
1581
1582 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1583 if (interp == NULL) {
1584 return NULL;
1585 }
1586
1587 PyObject *res = NULL;
1588 PyThreadState *tstate =
1589 _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_EXEC);
1590
1591 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
1592
1593 if (runningmain) {
1594 if (_PyInterpreterState_SetRunningMain(interp) < 0) {
1595 goto finally;
1596 }
1597 }
1598
1599 /* only initialise 'cflags.cf_flags' to test backwards compatibility */
1600 PyCompilerFlags cflags = {0};
1601 int r = PyRun_SimpleStringFlags(code, &cflags);
1602 if (PyErr_Occurred()) {
1603 PyErr_PrintEx(0);
1604 }
1605
1606 if (runningmain) {
1607 _PyInterpreterState_SetNotRunningMain(interp);
1608 }
1609
1610 res = PyLong_FromLong(r);
1611
1612 finally:
1613 PyThreadState_Clear(tstate);
1614 PyThreadState_Swap(save_tstate);
1615 PyThreadState_Delete(tstate);
1616 return res;
1617 }
1618
1619
1620 /* To run some code in a sub-interpreter.
1621
1622 Generally you can use test.support.interpreters,
1623 but we keep this helper as a distinct implementation.
1624 That's especially important for testing test.support.interpreters.
1625 */
1626 static PyObject *
run_in_subinterp_with_config(PyObject * self,PyObject * args,PyObject * kwargs)1627 run_in_subinterp_with_config(PyObject *self, PyObject *args, PyObject *kwargs)
1628 {
1629 const char *code;
1630 PyObject *configobj;
1631 int xi = 0;
1632 static char *kwlist[] = {"code", "config", "xi", NULL};
1633 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1634 "sO|$p:run_in_subinterp_with_config", kwlist,
1635 &code, &configobj, &xi))
1636 {
1637 return NULL;
1638 }
1639
1640 PyInterpreterConfig config;
1641 if (_init_interp_config_from_object(&config, configobj) < 0) {
1642 return NULL;
1643 }
1644
1645 /* only initialise 'cflags.cf_flags' to test backwards compatibility */
1646 PyCompilerFlags cflags = {0};
1647
1648 int r;
1649 if (xi) {
1650 PyThreadState *save_tstate;
1651 PyThreadState *tstate;
1652
1653 /* Create an interpreter, staying switched to it. */
1654 PyInterpreterState *interp = \
1655 _PyXI_NewInterpreter(&config, NULL, &tstate, &save_tstate);
1656 if (interp == NULL) {
1657 return NULL;
1658 }
1659
1660 /* Exec the code in the new interpreter. */
1661 r = PyRun_SimpleStringFlags(code, &cflags);
1662
1663 /* clean up post-exec. */
1664 _PyXI_EndInterpreter(interp, tstate, &save_tstate);
1665 }
1666 else {
1667 PyThreadState *substate;
1668 PyThreadState *mainstate = PyThreadState_Swap(NULL);
1669
1670 /* Create an interpreter, staying switched to it. */
1671 PyStatus status = Py_NewInterpreterFromConfig(&substate, &config);
1672 if (PyStatus_Exception(status)) {
1673 /* Since no new thread state was created, there is no exception to
1674 propagate; raise a fresh one after swapping in the old thread
1675 state. */
1676 PyThreadState_Swap(mainstate);
1677 _PyErr_SetFromPyStatus(status);
1678 PyObject *exc = PyErr_GetRaisedException();
1679 PyErr_SetString(PyExc_InterpreterError,
1680 "sub-interpreter creation failed");
1681 _PyErr_ChainExceptions1(exc);
1682 return NULL;
1683 }
1684
1685 /* Exec the code in the new interpreter. */
1686 r = PyRun_SimpleStringFlags(code, &cflags);
1687
1688 /* clean up post-exec. */
1689 Py_EndInterpreter(substate);
1690 PyThreadState_Swap(mainstate);
1691 }
1692
1693 return PyLong_FromLong(r);
1694 }
1695
1696
1697 static PyObject *
normalize_interp_id(PyObject * self,PyObject * idobj)1698 normalize_interp_id(PyObject *self, PyObject *idobj)
1699 {
1700 int64_t interpid = _PyInterpreterState_ObjectToID(idobj);
1701 if (interpid < 0) {
1702 return NULL;
1703 }
1704 return PyLong_FromLongLong(interpid);
1705 }
1706
1707 static PyObject *
next_interpreter_id(PyObject * self,PyObject * Py_UNUSED (ignored))1708 next_interpreter_id(PyObject *self, PyObject *Py_UNUSED(ignored))
1709 {
1710 int64_t interpid = _PyRuntime.interpreters.next_id;
1711 return PyLong_FromLongLong(interpid);
1712 }
1713
1714 static PyObject *
unused_interpreter_id(PyObject * self,PyObject * Py_UNUSED (ignored))1715 unused_interpreter_id(PyObject *self, PyObject *Py_UNUSED(ignored))
1716 {
1717 int64_t interpid = INT64_MAX;
1718 assert(interpid > _PyRuntime.interpreters.next_id);
1719 return PyLong_FromLongLong(interpid);
1720 }
1721
1722 static PyObject *
interpreter_exists(PyObject * self,PyObject * idobj)1723 interpreter_exists(PyObject *self, PyObject *idobj)
1724 {
1725 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1726 if (interp == NULL) {
1727 if (PyErr_ExceptionMatches(PyExc_InterpreterNotFoundError)) {
1728 PyErr_Clear();
1729 Py_RETURN_FALSE;
1730 }
1731 assert(PyErr_Occurred());
1732 return NULL;
1733 }
1734 Py_RETURN_TRUE;
1735 }
1736
1737 static PyObject *
get_interpreter_refcount(PyObject * self,PyObject * idobj)1738 get_interpreter_refcount(PyObject *self, PyObject *idobj)
1739 {
1740 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1741 if (interp == NULL) {
1742 return NULL;
1743 }
1744 return PyLong_FromLongLong(interp->id_refcount);
1745 }
1746
1747 static PyObject *
link_interpreter_refcount(PyObject * self,PyObject * idobj)1748 link_interpreter_refcount(PyObject *self, PyObject *idobj)
1749 {
1750 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1751 if (interp == NULL) {
1752 assert(PyErr_Occurred());
1753 return NULL;
1754 }
1755 _PyInterpreterState_RequireIDRef(interp, 1);
1756 Py_RETURN_NONE;
1757 }
1758
1759 static PyObject *
unlink_interpreter_refcount(PyObject * self,PyObject * idobj)1760 unlink_interpreter_refcount(PyObject *self, PyObject *idobj)
1761 {
1762 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1763 if (interp == NULL) {
1764 assert(PyErr_Occurred());
1765 return NULL;
1766 }
1767 _PyInterpreterState_RequireIDRef(interp, 0);
1768 Py_RETURN_NONE;
1769 }
1770
1771 static PyObject *
interpreter_refcount_linked(PyObject * self,PyObject * idobj)1772 interpreter_refcount_linked(PyObject *self, PyObject *idobj)
1773 {
1774 PyInterpreterState *interp = _PyInterpreterState_LookUpIDObject(idobj);
1775 if (interp == NULL) {
1776 return NULL;
1777 }
1778 if (_PyInterpreterState_RequiresIDRef(interp)) {
1779 Py_RETURN_TRUE;
1780 }
1781 Py_RETURN_FALSE;
1782 }
1783
1784
1785 static void
_xid_capsule_destructor(PyObject * capsule)1786 _xid_capsule_destructor(PyObject *capsule)
1787 {
1788 _PyCrossInterpreterData *data = \
1789 (_PyCrossInterpreterData *)PyCapsule_GetPointer(capsule, NULL);
1790 if (data != NULL) {
1791 assert(_PyCrossInterpreterData_Release(data) == 0);
1792 _PyCrossInterpreterData_Free(data);
1793 }
1794 }
1795
1796 static PyObject *
get_crossinterp_data(PyObject * self,PyObject * args)1797 get_crossinterp_data(PyObject *self, PyObject *args)
1798 {
1799 PyObject *obj = NULL;
1800 if (!PyArg_ParseTuple(args, "O:get_crossinterp_data", &obj)) {
1801 return NULL;
1802 }
1803
1804 _PyCrossInterpreterData *data = _PyCrossInterpreterData_New();
1805 if (data == NULL) {
1806 return NULL;
1807 }
1808 if (_PyObject_GetCrossInterpreterData(obj, data) != 0) {
1809 _PyCrossInterpreterData_Free(data);
1810 return NULL;
1811 }
1812 PyObject *capsule = PyCapsule_New(data, NULL, _xid_capsule_destructor);
1813 if (capsule == NULL) {
1814 assert(_PyCrossInterpreterData_Release(data) == 0);
1815 _PyCrossInterpreterData_Free(data);
1816 }
1817 return capsule;
1818 }
1819
1820 static PyObject *
restore_crossinterp_data(PyObject * self,PyObject * args)1821 restore_crossinterp_data(PyObject *self, PyObject *args)
1822 {
1823 PyObject *capsule = NULL;
1824 if (!PyArg_ParseTuple(args, "O:restore_crossinterp_data", &capsule)) {
1825 return NULL;
1826 }
1827
1828 _PyCrossInterpreterData *data = \
1829 (_PyCrossInterpreterData *)PyCapsule_GetPointer(capsule, NULL);
1830 if (data == NULL) {
1831 return NULL;
1832 }
1833 return _PyCrossInterpreterData_NewObject(data);
1834 }
1835
1836
1837 static PyObject *
raiseTestError(const char * test_name,const char * msg)1838 raiseTestError(const char* test_name, const char* msg)
1839 {
1840 PyErr_Format(PyExc_AssertionError, "%s: %s", test_name, msg);
1841 return NULL;
1842 }
1843
1844
1845 /*[clinic input]
1846 _testinternalcapi.test_long_numbits
1847 [clinic start generated code]*/
1848
1849 static PyObject *
_testinternalcapi_test_long_numbits_impl(PyObject * module)1850 _testinternalcapi_test_long_numbits_impl(PyObject *module)
1851 /*[clinic end generated code: output=745d62d120359434 input=f14ca6f638e44dad]*/
1852 {
1853 struct triple {
1854 long input;
1855 size_t nbits;
1856 int sign;
1857 } testcases[] = {{0, 0, 0},
1858 {1L, 1, 1},
1859 {-1L, 1, -1},
1860 {2L, 2, 1},
1861 {-2L, 2, -1},
1862 {3L, 2, 1},
1863 {-3L, 2, -1},
1864 {4L, 3, 1},
1865 {-4L, 3, -1},
1866 {0x7fffL, 15, 1}, /* one Python int digit */
1867 {-0x7fffL, 15, -1},
1868 {0xffffL, 16, 1},
1869 {-0xffffL, 16, -1},
1870 {0xfffffffL, 28, 1},
1871 {-0xfffffffL, 28, -1}};
1872 size_t i;
1873
1874 for (i = 0; i < Py_ARRAY_LENGTH(testcases); ++i) {
1875 size_t nbits;
1876 int sign;
1877 PyObject *plong;
1878
1879 plong = PyLong_FromLong(testcases[i].input);
1880 if (plong == NULL)
1881 return NULL;
1882 nbits = _PyLong_NumBits(plong);
1883 sign = _PyLong_Sign(plong);
1884
1885 Py_DECREF(plong);
1886 if (nbits != testcases[i].nbits)
1887 return raiseTestError("test_long_numbits",
1888 "wrong result for _PyLong_NumBits");
1889 if (sign != testcases[i].sign)
1890 return raiseTestError("test_long_numbits",
1891 "wrong result for _PyLong_Sign");
1892 }
1893 Py_RETURN_NONE;
1894 }
1895
1896 static PyObject *
compile_perf_trampoline_entry(PyObject * self,PyObject * args)1897 compile_perf_trampoline_entry(PyObject *self, PyObject *args)
1898 {
1899 PyObject *co;
1900 if (!PyArg_ParseTuple(args, "O!", &PyCode_Type, &co)) {
1901 return NULL;
1902 }
1903 int ret = PyUnstable_PerfTrampoline_CompileCode((PyCodeObject *)co);
1904 if (ret != 0) {
1905 PyErr_SetString(PyExc_AssertionError, "Failed to compile trampoline");
1906 return NULL;
1907 }
1908 return PyLong_FromLong(ret);
1909 }
1910
1911 static PyObject *
perf_trampoline_set_persist_after_fork(PyObject * self,PyObject * args)1912 perf_trampoline_set_persist_after_fork(PyObject *self, PyObject *args)
1913 {
1914 int enable;
1915 if (!PyArg_ParseTuple(args, "i", &enable)) {
1916 return NULL;
1917 }
1918 int ret = PyUnstable_PerfTrampoline_SetPersistAfterFork(enable);
1919 if (ret == 0) {
1920 PyErr_SetString(PyExc_AssertionError, "Failed to set persist_after_fork");
1921 return NULL;
1922 }
1923 return PyLong_FromLong(ret);
1924 }
1925
1926
1927 static PyObject *
get_rare_event_counters(PyObject * self,PyObject * type)1928 get_rare_event_counters(PyObject *self, PyObject *type)
1929 {
1930 PyInterpreterState *interp = PyInterpreterState_Get();
1931
1932 return Py_BuildValue(
1933 "{sksksksksk}",
1934 "set_class", (unsigned long)interp->rare_events.set_class,
1935 "set_bases", (unsigned long)interp->rare_events.set_bases,
1936 "set_eval_frame_func", (unsigned long)interp->rare_events.set_eval_frame_func,
1937 "builtin_dict", (unsigned long)interp->rare_events.builtin_dict,
1938 "func_modification", (unsigned long)interp->rare_events.func_modification
1939 );
1940 }
1941
1942 static PyObject *
reset_rare_event_counters(PyObject * self,PyObject * Py_UNUSED (type))1943 reset_rare_event_counters(PyObject *self, PyObject *Py_UNUSED(type))
1944 {
1945 PyInterpreterState *interp = PyInterpreterState_Get();
1946
1947 interp->rare_events.set_class = 0;
1948 interp->rare_events.set_bases = 0;
1949 interp->rare_events.set_eval_frame_func = 0;
1950 interp->rare_events.builtin_dict = 0;
1951 interp->rare_events.func_modification = 0;
1952
1953 return Py_None;
1954 }
1955
1956
1957 #ifdef Py_GIL_DISABLED
1958 static PyObject *
get_py_thread_id(PyObject * self,PyObject * Py_UNUSED (ignored))1959 get_py_thread_id(PyObject *self, PyObject *Py_UNUSED(ignored))
1960 {
1961 uintptr_t tid = _Py_ThreadId();
1962 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(tid));
1963 return PyLong_FromUnsignedLongLong(tid);
1964 }
1965 #endif
1966
1967 static PyObject *
suppress_immortalization(PyObject * self,PyObject * value)1968 suppress_immortalization(PyObject *self, PyObject *value)
1969 {
1970 #ifdef Py_GIL_DISABLED
1971 int suppress = PyObject_IsTrue(value);
1972 if (suppress < 0) {
1973 return NULL;
1974 }
1975 PyInterpreterState *interp = PyInterpreterState_Get();
1976 // Subtract two to suppress immortalization (so that 1 -> -1)
1977 _Py_atomic_add_int(&interp->gc.immortalize, suppress ? -2 : 2);
1978 #endif
1979 Py_RETURN_NONE;
1980 }
1981
1982 static PyObject *
get_immortalize_deferred(PyObject * self,PyObject * Py_UNUSED (ignored))1983 get_immortalize_deferred(PyObject *self, PyObject *Py_UNUSED(ignored))
1984 {
1985 #ifdef Py_GIL_DISABLED
1986 PyInterpreterState *interp = PyInterpreterState_Get();
1987 return PyBool_FromLong(_Py_atomic_load_int(&interp->gc.immortalize) >= 0);
1988 #else
1989 Py_RETURN_FALSE;
1990 #endif
1991 }
1992
1993 static PyObject *
has_inline_values(PyObject * self,PyObject * obj)1994 has_inline_values(PyObject *self, PyObject *obj)
1995 {
1996 if ((Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1997 _PyObject_InlineValues(obj)->valid) {
1998 Py_RETURN_TRUE;
1999 }
2000 Py_RETURN_FALSE;
2001 }
2002
2003
2004 /*[clinic input]
2005 gh_119213_getargs
2006
2007 spam: object = None
2008
2009 Test _PyArg_Parser.kwtuple
2010 [clinic start generated code]*/
2011
2012 static PyObject *
gh_119213_getargs_impl(PyObject * module,PyObject * spam)2013 gh_119213_getargs_impl(PyObject *module, PyObject *spam)
2014 /*[clinic end generated code: output=d8d9c95d5b446802 input=65ef47511da80fc2]*/
2015 {
2016 // It must never have been called in the main interprer
2017 assert(!_Py_IsMainInterpreter(PyInterpreterState_Get()));
2018 return Py_NewRef(spam);
2019 }
2020
2021
2022 static PyMethodDef module_functions[] = {
2023 {"get_configs", get_configs, METH_NOARGS},
2024 {"get_recursion_depth", get_recursion_depth, METH_NOARGS},
2025 {"get_c_recursion_remaining", get_c_recursion_remaining, METH_NOARGS},
2026 {"test_bswap", test_bswap, METH_NOARGS},
2027 {"test_popcount", test_popcount, METH_NOARGS},
2028 {"test_bit_length", test_bit_length, METH_NOARGS},
2029 {"test_hashtable", test_hashtable, METH_NOARGS},
2030 {"get_config", test_get_config, METH_NOARGS},
2031 {"set_config", test_set_config, METH_O},
2032 {"reset_path_config", test_reset_path_config, METH_NOARGS},
2033 {"test_edit_cost", test_edit_cost, METH_NOARGS},
2034 {"test_bytes_find", test_bytes_find, METH_NOARGS},
2035 {"normalize_path", normalize_path, METH_O, NULL},
2036 {"get_getpath_codeobject", get_getpath_codeobject, METH_NOARGS, NULL},
2037 {"EncodeLocaleEx", encode_locale_ex, METH_VARARGS},
2038 {"DecodeLocaleEx", decode_locale_ex, METH_VARARGS},
2039 {"set_eval_frame_default", set_eval_frame_default, METH_NOARGS, NULL},
2040 {"set_eval_frame_record", set_eval_frame_record, METH_O, NULL},
2041 _TESTINTERNALCAPI_COMPILER_CLEANDOC_METHODDEF
2042 _TESTINTERNALCAPI_NEW_INSTRUCTION_SEQUENCE_METHODDEF
2043 _TESTINTERNALCAPI_COMPILER_CODEGEN_METHODDEF
2044 _TESTINTERNALCAPI_OPTIMIZE_CFG_METHODDEF
2045 _TESTINTERNALCAPI_ASSEMBLE_CODE_OBJECT_METHODDEF
2046 {"get_interp_settings", get_interp_settings, METH_VARARGS, NULL},
2047 {"clear_extension", clear_extension, METH_VARARGS, NULL},
2048 {"write_perf_map_entry", write_perf_map_entry, METH_VARARGS},
2049 {"perf_map_state_teardown", perf_map_state_teardown, METH_NOARGS},
2050 {"iframe_getcode", iframe_getcode, METH_O, NULL},
2051 {"iframe_getline", iframe_getline, METH_O, NULL},
2052 {"iframe_getlasti", iframe_getlasti, METH_O, NULL},
2053 {"get_co_framesize", get_co_framesize, METH_O, NULL},
2054 #ifdef _Py_TIER2
2055 {"get_optimizer", get_optimizer, METH_NOARGS, NULL},
2056 {"set_optimizer", set_optimizer, METH_O, NULL},
2057 {"new_counter_optimizer", new_counter_optimizer, METH_NOARGS, NULL},
2058 {"new_uop_optimizer", new_uop_optimizer, METH_NOARGS, NULL},
2059 {"add_executor_dependency", add_executor_dependency, METH_VARARGS, NULL},
2060 {"invalidate_executors", invalidate_executors, METH_O, NULL},
2061 #endif
2062 {"pending_threadfunc", _PyCFunction_CAST(pending_threadfunc),
2063 METH_VARARGS | METH_KEYWORDS},
2064 {"pending_identify", pending_identify, METH_VARARGS, NULL},
2065 {"_PyTraceMalloc_GetTraceback", tracemalloc_get_traceback, METH_VARARGS},
2066 {"test_tstate_capi", test_tstate_capi, METH_NOARGS, NULL},
2067 {"_PyUnicode_TransformDecimalAndSpaceToASCII", unicode_transformdecimalandspacetoascii, METH_O},
2068 {"test_atexit", test_atexit, METH_NOARGS},
2069 {"check_pyobject_forbidden_bytes_is_freed",
2070 check_pyobject_forbidden_bytes_is_freed, METH_NOARGS},
2071 {"check_pyobject_freed_is_freed", check_pyobject_freed_is_freed, METH_NOARGS},
2072 {"check_pyobject_null_is_freed", check_pyobject_null_is_freed, METH_NOARGS},
2073 {"check_pyobject_uninitialized_is_freed",
2074 check_pyobject_uninitialized_is_freed, METH_NOARGS},
2075 {"pymem_getallocatorsname", test_pymem_getallocatorsname, METH_NOARGS},
2076 {"get_object_dict_values", get_object_dict_values, METH_O},
2077 {"hamt", new_hamt, METH_NOARGS},
2078 {"dict_getitem_knownhash", dict_getitem_knownhash, METH_VARARGS},
2079 {"create_interpreter", _PyCFunction_CAST(create_interpreter),
2080 METH_VARARGS | METH_KEYWORDS},
2081 {"destroy_interpreter", _PyCFunction_CAST(destroy_interpreter),
2082 METH_VARARGS | METH_KEYWORDS},
2083 {"exec_interpreter", _PyCFunction_CAST(exec_interpreter),
2084 METH_VARARGS | METH_KEYWORDS},
2085 {"run_in_subinterp_with_config",
2086 _PyCFunction_CAST(run_in_subinterp_with_config),
2087 METH_VARARGS | METH_KEYWORDS},
2088 {"normalize_interp_id", normalize_interp_id, METH_O},
2089 {"next_interpreter_id", next_interpreter_id, METH_NOARGS},
2090 {"unused_interpreter_id", unused_interpreter_id, METH_NOARGS},
2091 {"interpreter_exists", interpreter_exists, METH_O},
2092 {"get_interpreter_refcount", get_interpreter_refcount, METH_O},
2093 {"link_interpreter_refcount", link_interpreter_refcount, METH_O},
2094 {"unlink_interpreter_refcount", unlink_interpreter_refcount, METH_O},
2095 {"interpreter_refcount_linked", interpreter_refcount_linked, METH_O},
2096 {"compile_perf_trampoline_entry", compile_perf_trampoline_entry, METH_VARARGS},
2097 {"perf_trampoline_set_persist_after_fork", perf_trampoline_set_persist_after_fork, METH_VARARGS},
2098 {"get_crossinterp_data", get_crossinterp_data, METH_VARARGS},
2099 {"restore_crossinterp_data", restore_crossinterp_data, METH_VARARGS},
2100 _TESTINTERNALCAPI_TEST_LONG_NUMBITS_METHODDEF
2101 {"get_rare_event_counters", get_rare_event_counters, METH_NOARGS},
2102 {"reset_rare_event_counters", reset_rare_event_counters, METH_NOARGS},
2103 {"has_inline_values", has_inline_values, METH_O},
2104 #ifdef Py_GIL_DISABLED
2105 {"py_thread_id", get_py_thread_id, METH_NOARGS},
2106 #endif
2107 {"suppress_immortalization", suppress_immortalization, METH_O},
2108 {"get_immortalize_deferred", get_immortalize_deferred, METH_NOARGS},
2109 #ifdef _Py_TIER2
2110 {"uop_symbols_test", _Py_uop_symbols_test, METH_NOARGS},
2111 #endif
2112 GH_119213_GETARGS_METHODDEF
2113 {NULL, NULL} /* sentinel */
2114 };
2115
2116
2117 /* initialization function */
2118
2119 static int
module_exec(PyObject * module)2120 module_exec(PyObject *module)
2121 {
2122 if (_PyTestInternalCapi_Init_Lock(module) < 0) {
2123 return 1;
2124 }
2125 if (_PyTestInternalCapi_Init_PyTime(module) < 0) {
2126 return 1;
2127 }
2128 if (_PyTestInternalCapi_Init_Set(module) < 0) {
2129 return 1;
2130 }
2131 if (_PyTestInternalCapi_Init_CriticalSection(module) < 0) {
2132 return 1;
2133 }
2134
2135 Py_ssize_t sizeof_gc_head = 0;
2136 #ifndef Py_GIL_DISABLED
2137 sizeof_gc_head = sizeof(PyGC_Head);
2138 #endif
2139
2140 if (PyModule_Add(module, "SIZEOF_PYGC_HEAD",
2141 PyLong_FromSsize_t(sizeof_gc_head)) < 0) {
2142 return 1;
2143 }
2144
2145 if (PyModule_Add(module, "SIZEOF_MANAGED_PRE_HEADER",
2146 PyLong_FromSsize_t(2 * sizeof(PyObject*))) < 0) {
2147 return 1;
2148 }
2149
2150 if (PyModule_Add(module, "SIZEOF_PYOBJECT",
2151 PyLong_FromSsize_t(sizeof(PyObject))) < 0) {
2152 return 1;
2153 }
2154
2155 if (PyModule_Add(module, "SIZEOF_TIME_T",
2156 PyLong_FromSsize_t(sizeof(time_t))) < 0) {
2157 return 1;
2158 }
2159
2160 if (PyModule_Add(module, "TIER2_THRESHOLD",
2161 PyLong_FromLong(JUMP_BACKWARD_INITIAL_VALUE)) < 0) {
2162 return 1;
2163 }
2164
2165 return 0;
2166 }
2167
2168 static struct PyModuleDef_Slot module_slots[] = {
2169 {Py_mod_exec, module_exec},
2170 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2171 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
2172 {0, NULL},
2173 };
2174
2175 static int
module_traverse(PyObject * module,visitproc visit,void * arg)2176 module_traverse(PyObject *module, visitproc visit, void *arg)
2177 {
2178 module_state *state = get_module_state(module);
2179 assert(state != NULL);
2180 traverse_module_state(state, visit, arg);
2181 return 0;
2182 }
2183
2184 static int
module_clear(PyObject * module)2185 module_clear(PyObject *module)
2186 {
2187 module_state *state = get_module_state(module);
2188 assert(state != NULL);
2189 (void)clear_module_state(state);
2190 return 0;
2191 }
2192
2193 static void
module_free(void * module)2194 module_free(void *module)
2195 {
2196 module_state *state = get_module_state(module);
2197 assert(state != NULL);
2198 (void)clear_module_state(state);
2199 }
2200
2201 static struct PyModuleDef _testcapimodule = {
2202 .m_base = PyModuleDef_HEAD_INIT,
2203 .m_name = MODULE_NAME,
2204 .m_doc = NULL,
2205 .m_size = sizeof(module_state),
2206 .m_methods = module_functions,
2207 .m_slots = module_slots,
2208 .m_traverse = module_traverse,
2209 .m_clear = module_clear,
2210 .m_free = (freefunc)module_free,
2211 };
2212
2213
2214 PyMODINIT_FUNC
PyInit__testinternalcapi(void)2215 PyInit__testinternalcapi(void)
2216 {
2217 return PyModuleDef_Init(&_testcapimodule);
2218 }
2219