Debian Codegraph @

Modules/_testcapi/watchers.c

raw
1 // clinic/watchers.c.h uses internal pycore_modsupport.h API
2 #define PYTESTCAPI_NEED_INTERNAL_API
3
4 #include "parts.h"
5
6 #include "clinic/watchers.c.h"
7
8 #define Py_BUILD_CORE
9 #include "pycore_function.h" // FUNC_MAX_WATCHERS
10 #include "pycore_interp_structs.h" // CODE_MAX_WATCHERS
11 #include "pycore_context.h" // CONTEXT_MAX_WATCHERS
12 #include "pycore_lock.h" // _PyOnceFlag
13
14 /*[clinic input]
15 module _testcapi
16 [clinic start generated code]*/
17 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=6361033e795369fc]*/
18
19 // Test dict watching
20 static PyObject *g_dict_watch_events = NULL;
21 static int g_dict_watchers_installed = 0;
22 static _PyOnceFlag g_dict_watch_once = {0};
23
24 static int
25 _init_dict_watch_events(void *arg)
26 {
27 g_dict_watch_events = PyList_New(0);
28 return g_dict_watch_events ? 0 : -1;
29 }
30
31 static int
32 dict_watch_callback(PyDict_WatchEvent event,
33 PyObject *dict,
34 PyObject *key,
35 PyObject *new_value)
36 {
37 PyObject *msg;
38 switch (event) {
39 case PyDict_EVENT_CLEARED:
40 msg = PyUnicode_FromString("clear");
41 break;
42 case PyDict_EVENT_DEALLOCATED:
43 msg = PyUnicode_FromString("dealloc");
44 break;
45 case PyDict_EVENT_CLONED:
46 msg = PyUnicode_FromString("clone");
47 break;
48 case PyDict_EVENT_ADDED:
49 msg = PyUnicode_FromFormat("new:%S:%S", key, new_value);
50 break;
51 case PyDict_EVENT_MODIFIED:
52 msg = PyUnicode_FromFormat("mod:%S:%S", key, new_value);
53 break;
54 case PyDict_EVENT_DELETED:
55 msg = PyUnicode_FromFormat("del:%S", key);
56 break;
57 default:
58 msg = PyUnicode_FromString("unknown");
59 }
60 if (msg == NULL) {
61 return -1;
62 }
63 assert(PyList_Check(g_dict_watch_events));
64 if (PyList_Append(g_dict_watch_events, msg) < 0) {
65 Py_DECREF(msg);
66 return -1;
67 }
68 Py_DECREF(msg);
69 return 0;
70 }
71
72 static int
73 dict_watch_callback_second(PyDict_WatchEvent event,
74 PyObject *dict,
75 PyObject *key,
76 PyObject *new_value)
77 {
78 PyObject *msg = PyUnicode_FromString("second");
79 if (msg == NULL) {
80 return -1;
81 }
82 int rc = PyList_Append(g_dict_watch_events, msg);
83 Py_DECREF(msg);
84 if (rc < 0) {
85 return -1;
86 }
87 return 0;
88 }
89
90 static int
91 dict_watch_callback_error(PyDict_WatchEvent event,
92 PyObject *dict,
93 PyObject *key,
94 PyObject *new_value)
95 {
96 PyErr_SetString(PyExc_RuntimeError, "boom!");
97 return -1;
98 }
99
100 static PyObject *
101 add_dict_watcher(PyObject *self, PyObject *kind)
102 {
103 int watcher_id;
104 assert(PyLong_Check(kind));
105 long kind_l = PyLong_AsLong(kind);
106 if (kind_l == 2) {
107 watcher_id = PyDict_AddWatcher(dict_watch_callback_second);
108 }
109 else if (kind_l == 1) {
110 watcher_id = PyDict_AddWatcher(dict_watch_callback_error);
111 }
112 else {
113 watcher_id = PyDict_AddWatcher(dict_watch_callback);
114 }
115 if (watcher_id < 0) {
116 return NULL;
117 }
118 if (_PyOnceFlag_CallOnce(&g_dict_watch_once, _init_dict_watch_events, NULL) < 0) {
119 return NULL;
120 }
121 _Py_atomic_add_int(&g_dict_watchers_installed, 1);
122 return PyLong_FromLong(watcher_id);
123 }
124
125 static PyObject *
126 clear_dict_watcher(PyObject *self, PyObject *watcher_id)
127 {
128 if (PyDict_ClearWatcher(PyLong_AsLong(watcher_id))) {
129 return NULL;
130 }
131 if (_Py_atomic_add_int(&g_dict_watchers_installed, -1) == 1) {
132 PyList_Clear(g_dict_watch_events);
133 }
134 Py_RETURN_NONE;
135 }
136
137 /*[clinic input]
138 _testcapi.watch_dict
139 watcher_id: int
140 dict: object
141 /
142 [clinic start generated code]*/
143
144 static PyObject *
145 _testcapi_watch_dict_impl(PyObject *module, int watcher_id, PyObject *dict)
146 /*[clinic end generated code: output=1426e0273cebe2d8 input=269b006d60c358bd]*/
147 {
148 if (PyDict_Watch(watcher_id, dict)) {
149 return NULL;
150 }
151 Py_RETURN_NONE;
152 }
153
154 /*[clinic input]
155 _testcapi.unwatch_dict = _testcapi.watch_dict
156 [clinic start generated code]*/
157
158 static PyObject *
159 _testcapi_unwatch_dict_impl(PyObject *module, int watcher_id, PyObject *dict)
160 /*[clinic end generated code: output=512b1a71ae33c351 input=cae7dc1b6f7713b8]*/
161 {
162 if (PyDict_Unwatch(watcher_id, dict)) {
163 return NULL;
164 }
165 Py_RETURN_NONE;
166 }
167
168 static PyObject *
169 get_dict_watcher_events(PyObject *self, PyObject *Py_UNUSED(args))
170 {
171 if (_Py_atomic_load_int(&g_dict_watchers_installed) <= 0) {
172 PyErr_SetString(PyExc_RuntimeError, "no watchers active");
173 return NULL;
174 }
175 return Py_NewRef(g_dict_watch_events);
176 }
177
178 // Test type watchers
179 static PyObject *g_type_modified_events;
180 static int g_type_watchers_installed;
181
182 static int
183 type_modified_callback(PyTypeObject *type)
184 {
185 assert(PyList_Check(g_type_modified_events));
186 if(PyList_Append(g_type_modified_events, (PyObject *)type) < 0) {
187 return -1;
188 }
189 return 0;
190 }
191
192 static int
193 type_modified_callback_wrap(PyTypeObject *type)
194 {
195 assert(PyList_Check(g_type_modified_events));
196 PyObject *list = PyList_New(0);
197 if (list == NULL) {
198 return -1;
199 }
200 if (PyList_Append(list, (PyObject *)type) < 0) {
201 Py_DECREF(list);
202 return -1;
203 }
204 if (PyList_Append(g_type_modified_events, list) < 0) {
205 Py_DECREF(list);
206 return -1;
207 }
208 Py_DECREF(list);
209 return 0;
210 }
211
212 static int
213 type_modified_callback_error(PyTypeObject *type)
214 {
215 PyErr_SetString(PyExc_RuntimeError, "boom!");
216 return -1;
217 }
218
219 static PyObject *
220 add_type_watcher(PyObject *self, PyObject *kind)
221 {
222 int watcher_id;
223 assert(PyLong_Check(kind));
224 long kind_l = PyLong_AsLong(kind);
225 if (kind_l == 2) {
226 watcher_id = PyType_AddWatcher(type_modified_callback_wrap);
227 }
228 else if (kind_l == 1) {
229 watcher_id = PyType_AddWatcher(type_modified_callback_error);
230 }
231 else {
232 watcher_id = PyType_AddWatcher(type_modified_callback);
233 }
234 if (watcher_id < 0) {
235 return NULL;
236 }
237 if (!g_type_watchers_installed) {
238 assert(!g_type_modified_events);
239 if (!(g_type_modified_events = PyList_New(0))) {
240 return NULL;
241 }
242 }
243 g_type_watchers_installed++;
244 return PyLong_FromLong(watcher_id);
245 }
246
247 static PyObject *
248 clear_type_watcher(PyObject *self, PyObject *watcher_id)
249 {
250 if (PyType_ClearWatcher(PyLong_AsLong(watcher_id))) {
251 return NULL;
252 }
253 g_type_watchers_installed--;
254 if (!g_type_watchers_installed) {
255 assert(g_type_modified_events);
256 Py_CLEAR(g_type_modified_events);
257 }
258 Py_RETURN_NONE;
259 }
260
261 static PyObject *
262 get_type_modified_events(PyObject *self, PyObject *Py_UNUSED(args))
263 {
264 if (!g_type_modified_events) {
265 PyErr_SetString(PyExc_RuntimeError, "no watchers active");
266 return NULL;
267 }
268 return Py_NewRef(g_type_modified_events);
269 }
270
271 /*[clinic input]
272 _testcapi.watch_type
273 watcher_id: int
274 type: object
275 /
276 [clinic start generated code]*/
277
278 static PyObject *
279 _testcapi_watch_type_impl(PyObject *module, int watcher_id, PyObject *type)
280 /*[clinic end generated code: output=fdf4777126724fc4 input=5a808bf12be7e3ed]*/
281 {
282 if (PyType_Watch(watcher_id, type)) {
283 return NULL;
284 }
285 Py_RETURN_NONE;
286 }
287
288 /*[clinic input]
289 _testcapi.unwatch_type = _testcapi.watch_type
290 [clinic start generated code]*/
291
292 static PyObject *
293 _testcapi_unwatch_type_impl(PyObject *module, int watcher_id, PyObject *type)
294 /*[clinic end generated code: output=0389672d4ad5f68b input=6701911fb45edc9e]*/
295 {
296 if (PyType_Unwatch(watcher_id, type)) {
297 return NULL;
298 }
299 Py_RETURN_NONE;
300 }
301
302
303 // Test code object watching
304
305 #define NUM_CODE_WATCHERS 2
306 static int code_watcher_ids[NUM_CODE_WATCHERS] = {-1, -1};
307 static int num_code_object_created_events[NUM_CODE_WATCHERS] = {0, 0};
308 static int num_code_object_destroyed_events[NUM_CODE_WATCHERS] = {0, 0};
309
310 static int
311 handle_code_object_event(int which_watcher, PyCodeEvent event, PyCodeObject *co) {
312 if (event == PY_CODE_EVENT_CREATE) {
313 num_code_object_created_events[which_watcher]++;
314 }
315 else if (event == PY_CODE_EVENT_DESTROY) {
316 num_code_object_destroyed_events[which_watcher]++;
317 }
318 else {
319 return -1;
320 }
321 return 0;
322 }
323
324 static int
325 first_code_object_callback(PyCodeEvent event, PyCodeObject *co)
326 {
327 return handle_code_object_event(0, event, co);
328 }
329
330 static int
331 second_code_object_callback(PyCodeEvent event, PyCodeObject *co)
332 {
333 return handle_code_object_event(1, event, co);
334 }
335
336 static int
337 noop_code_event_handler(PyCodeEvent event, PyCodeObject *co)
338 {
339 return 0;
340 }
341
342 static int
343 error_code_event_handler(PyCodeEvent event, PyCodeObject *co)
344 {
345 PyErr_SetString(PyExc_RuntimeError, "boom!");
346 return -1;
347 }
348
349 static PyObject *
350 add_code_watcher(PyObject *self, PyObject *which_watcher)
351 {
352 int watcher_id;
353 assert(PyLong_Check(which_watcher));
354 long which_l = PyLong_AsLong(which_watcher);
355 if (which_l == 0) {
356 watcher_id = PyCode_AddWatcher(first_code_object_callback);
357 code_watcher_ids[0] = watcher_id;
358 num_code_object_created_events[0] = 0;
359 num_code_object_destroyed_events[0] = 0;
360 }
361 else if (which_l == 1) {
362 watcher_id = PyCode_AddWatcher(second_code_object_callback);
363 code_watcher_ids[1] = watcher_id;
364 num_code_object_created_events[1] = 0;
365 num_code_object_destroyed_events[1] = 0;
366 }
367 else if (which_l == 2) {
368 watcher_id = PyCode_AddWatcher(error_code_event_handler);
369 }
370 else {
371 PyErr_Format(PyExc_ValueError, "invalid watcher %ld", which_l);
372 return NULL;
373 }
374 if (watcher_id < 0) {
375 return NULL;
376 }
377 return PyLong_FromLong(watcher_id);
378 }
379
380 static PyObject *
381 clear_code_watcher(PyObject *self, PyObject *watcher_id)
382 {
383 assert(PyLong_Check(watcher_id));
384 long watcher_id_l = PyLong_AsLong(watcher_id);
385 if (PyCode_ClearWatcher(watcher_id_l) < 0) {
386 return NULL;
387 }
388 // reset static events counters
389 if (watcher_id_l >= 0) {
390 for (int i = 0; i < NUM_CODE_WATCHERS; i++) {
391 if (watcher_id_l == code_watcher_ids[i]) {
392 code_watcher_ids[i] = -1;
393 num_code_object_created_events[i] = 0;
394 num_code_object_destroyed_events[i] = 0;
395 }
396 }
397 }
398 Py_RETURN_NONE;
399 }
400
401 static PyObject *
402 get_code_watcher_num_created_events(PyObject *self, PyObject *watcher_id)
403 {
404 assert(PyLong_Check(watcher_id));
405 long watcher_id_l = PyLong_AsLong(watcher_id);
406 assert(watcher_id_l >= 0 && watcher_id_l < NUM_CODE_WATCHERS);
407 return PyLong_FromLong(num_code_object_created_events[watcher_id_l]);
408 }
409
410 static PyObject *
411 get_code_watcher_num_destroyed_events(PyObject *self, PyObject *watcher_id)
412 {
413 assert(PyLong_Check(watcher_id));
414 long watcher_id_l = PyLong_AsLong(watcher_id);
415 assert(watcher_id_l >= 0 && watcher_id_l < NUM_CODE_WATCHERS);
416 return PyLong_FromLong(num_code_object_destroyed_events[watcher_id_l]);
417 }
418
419 static PyObject *
420 allocate_too_many_code_watchers(PyObject *self, PyObject *Py_UNUSED(args))
421 {
422 int watcher_ids[CODE_MAX_WATCHERS + 1];
423 int num_watchers = 0;
424 for (unsigned long i = 0; i < sizeof(watcher_ids) / sizeof(int); i++) {
425 int watcher_id = PyCode_AddWatcher(noop_code_event_handler);
426 if (watcher_id == -1) {
427 break;
428 }
429 watcher_ids[i] = watcher_id;
430 num_watchers++;
431 }
432 PyObject *exc = PyErr_GetRaisedException();
433 for (int i = 0; i < num_watchers; i++) {
434 if (PyCode_ClearWatcher(watcher_ids[i]) < 0) {
435 PyErr_FormatUnraisable("Exception ignored while "
436 "clearing code watcher");
437 break;
438 }
439 }
440 if (exc) {
441 PyErr_SetRaisedException(exc);
442 return NULL;
443 }
444 else if (PyErr_Occurred()) {
445 return NULL;
446 }
447 Py_RETURN_NONE;
448 }
449
450 // Test function watchers
451
452 #define NUM_TEST_FUNC_WATCHERS 2
453 static PyObject *pyfunc_watchers[NUM_TEST_FUNC_WATCHERS];
454 static int func_watcher_ids[NUM_TEST_FUNC_WATCHERS] = {-1, -1};
455
456 static PyObject *
457 get_id(PyObject *obj)
458 {
459 PyObject *builtins = PyEval_GetBuiltins(); // borrowed ref.
460 if (builtins == NULL) {
461 return NULL;
462 }
463 PyObject *id_str = PyUnicode_FromString("id");
464 if (id_str == NULL) {
465 return NULL;
466 }
467 PyObject *id_func = PyObject_GetItem(builtins, id_str);
468 Py_DECREF(id_str);
469 if (id_func == NULL) {
470 return NULL;
471 }
472 PyObject *stack[] = {obj};
473 PyObject *id = PyObject_Vectorcall(id_func, stack, 1, NULL);
474 Py_DECREF(id_func);
475 return id;
476 }
477
478 static int
479 call_pyfunc_watcher(PyObject *watcher, PyFunction_WatchEvent event,
480 PyFunctionObject *func, PyObject *new_value)
481 {
482 PyObject *event_obj = PyLong_FromLong(event);
483 if (event_obj == NULL) {
484 return -1;
485 }
486 if (new_value == NULL) {
487 new_value = Py_None;
488 }
489 Py_INCREF(new_value);
490 PyObject *func_or_id = NULL;
491 if (event == PyFunction_EVENT_DESTROY) {
492 /* Don't expose a function that's about to be destroyed to managed code */
493 func_or_id = get_id((PyObject *) func);
494 if (func_or_id == NULL) {
495 Py_DECREF(event_obj);
496 Py_DECREF(new_value);
497 return -1;
498 }
499 }
500 else {
501 Py_INCREF(func);
502 func_or_id = (PyObject *) func;
503 }
504 PyObject *stack[] = {event_obj, func_or_id, new_value};
505 PyObject *res = PyObject_Vectorcall(watcher, stack, 3, NULL);
506 int st = (res == NULL) ? -1 : 0;
507 Py_XDECREF(res);
508 Py_DECREF(new_value);
509 Py_DECREF(event_obj);
510 Py_DECREF(func_or_id);
511 return st;
512 }
513
514 static int
515 first_func_watcher_callback(PyFunction_WatchEvent event, PyFunctionObject *func,
516 PyObject *new_value)
517 {
518 return call_pyfunc_watcher(pyfunc_watchers[0], event, func, new_value);
519 }
520
521 static int
522 second_func_watcher_callback(PyFunction_WatchEvent event,
523 PyFunctionObject *func, PyObject *new_value)
524 {
525 return call_pyfunc_watcher(pyfunc_watchers[1], event, func, new_value);
526 }
527
528 static PyFunction_WatchCallback func_watcher_callbacks[NUM_TEST_FUNC_WATCHERS] = {
529 first_func_watcher_callback,
530 second_func_watcher_callback
531 };
532
533 static int
534 add_func_event(PyObject *module, const char *name, PyFunction_WatchEvent event)
535 {
536 return PyModule_Add(module, name, PyLong_FromLong(event));
537 }
538
539 static PyObject *
540 add_func_watcher(PyObject *self, PyObject *func)
541 {
542 if (!PyFunction_Check(func)) {
543 PyErr_SetString(PyExc_TypeError, "'func' must be a function");
544 return NULL;
545 }
546 int idx = -1;
547 for (int i = 0; i < NUM_TEST_FUNC_WATCHERS; i++) {
548 if (func_watcher_ids[i] == -1) {
549 idx = i;
550 break;
551 }
552 }
553 if (idx == -1) {
554 PyErr_SetString(PyExc_RuntimeError, "no free test watchers");
555 return NULL;
556 }
557 func_watcher_ids[idx] = PyFunction_AddWatcher(func_watcher_callbacks[idx]);
558 if (func_watcher_ids[idx] < 0) {
559 return NULL;
560 }
561 pyfunc_watchers[idx] = Py_NewRef(func);
562 PyObject *result = PyLong_FromLong(func_watcher_ids[idx]);
563 if (result == NULL) {
564 return NULL;
565 }
566 return result;
567 }
568
569 static PyObject *
570 clear_func_watcher(PyObject *self, PyObject *watcher_id_obj)
571 {
572 long watcher_id = PyLong_AsLong(watcher_id_obj);
573 if ((watcher_id < INT_MIN) || (watcher_id > INT_MAX)) {
574 PyErr_SetString(PyExc_ValueError, "invalid watcher ID");
575 return NULL;
576 }
577 int wid = (int) watcher_id;
578 if (PyFunction_ClearWatcher(wid) < 0) {
579 return NULL;
580 }
581 int idx = -1;
582 for (int i = 0; i < NUM_TEST_FUNC_WATCHERS; i++) {
583 if (func_watcher_ids[i] == wid) {
584 idx = i;
585 break;
586 }
587 }
588 assert(idx != -1);
589 Py_CLEAR(pyfunc_watchers[idx]);
590 func_watcher_ids[idx] = -1;
591 Py_RETURN_NONE;
592 }
593
594 static int
595 noop_func_event_handler(PyFunction_WatchEvent event, PyFunctionObject *func,
596 PyObject *new_value)
597 {
598 return 0;
599 }
600
601 static PyObject *
602 allocate_too_many_func_watchers(PyObject *self, PyObject *args)
603 {
604 int watcher_ids[FUNC_MAX_WATCHERS + 1];
605 int num_watchers = 0;
606 for (unsigned long i = 0; i < sizeof(watcher_ids) / sizeof(int); i++) {
607 int watcher_id = PyFunction_AddWatcher(noop_func_event_handler);
608 if (watcher_id == -1) {
609 break;
610 }
611 watcher_ids[i] = watcher_id;
612 num_watchers++;
613 }
614 PyObject *exc = PyErr_GetRaisedException();
615 for (int i = 0; i < num_watchers; i++) {
616 if (PyFunction_ClearWatcher(watcher_ids[i]) < 0) {
617 PyErr_FormatUnraisable("Exception ignored while "
618 "clearing function watcher");
619 break;
620 }
621 }
622 if (exc) {
623 PyErr_SetRaisedException(exc);
624 return NULL;
625 }
626 else if (PyErr_Occurred()) {
627 return NULL;
628 }
629 Py_RETURN_NONE;
630 }
631
632 // Test contexct object watchers
633 #define NUM_CONTEXT_WATCHERS 2
634 static int context_watcher_ids[NUM_CONTEXT_WATCHERS] = {-1, -1};
635 static PyObject *context_switches[NUM_CONTEXT_WATCHERS];
636
637 static int
638 handle_context_watcher_event(int which_watcher, PyContextEvent event, PyObject *ctx) {
639 if (event == Py_CONTEXT_SWITCHED) {
640 PyList_Append(context_switches[which_watcher], ctx);
641 }
642 else {
643 return -1;
644 }
645 return 0;
646 }
647
648 static int
649 first_context_watcher_callback(PyContextEvent event, PyObject *ctx) {
650 return handle_context_watcher_event(0, event, ctx);
651 }
652
653 static int
654 second_context_watcher_callback(PyContextEvent event, PyObject *ctx) {
655 return handle_context_watcher_event(1, event, ctx);
656 }
657
658 static int
659 noop_context_event_handler(PyContextEvent event, PyObject *ctx) {
660 return 0;
661 }
662
663 static int
664 error_context_event_handler(PyContextEvent event, PyObject *ctx) {
665 PyErr_SetString(PyExc_RuntimeError, "boom!");
666 return -1;
667 }
668
669 static PyObject *
670 add_context_watcher(PyObject *self, PyObject *which_watcher)
671 {
672 static const PyContext_WatchCallback callbacks[] = {
673 &first_context_watcher_callback,
674 &second_context_watcher_callback,
675 &error_context_event_handler,
676 };
677 assert(PyLong_Check(which_watcher));
678 long which_l = PyLong_AsLong(which_watcher);
679 if (which_l < 0 || which_l >= (long)Py_ARRAY_LENGTH(callbacks)) {
680 PyErr_Format(PyExc_ValueError, "invalid watcher %ld", which_l);
681 return NULL;
682 }
683 int watcher_id = PyContext_AddWatcher(callbacks[which_l]);
684 if (watcher_id < 0) {
685 return NULL;
686 }
687 if (which_l >= 0 && which_l < NUM_CONTEXT_WATCHERS) {
688 context_watcher_ids[which_l] = watcher_id;
689 Py_XSETREF(context_switches[which_l], PyList_New(0));
690 if (context_switches[which_l] == NULL) {
691 return NULL;
692 }
693 }
694 return PyLong_FromLong(watcher_id);
695 }
696
697 static PyObject *
698 clear_context_watcher(PyObject *self, PyObject *watcher_id)
699 {
700 assert(PyLong_Check(watcher_id));
701 long watcher_id_l = PyLong_AsLong(watcher_id);
702 if (PyContext_ClearWatcher(watcher_id_l) < 0) {
703 return NULL;
704 }
705 // reset static events counters
706 if (watcher_id_l >= 0) {
707 for (int i = 0; i < NUM_CONTEXT_WATCHERS; i++) {
708 if (watcher_id_l == context_watcher_ids[i]) {
709 context_watcher_ids[i] = -1;
710 Py_CLEAR(context_switches[i]);
711 }
712 }
713 }
714 Py_RETURN_NONE;
715 }
716
717 static PyObject *
718 clear_context_stack(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args))
719 {
720 PyThreadState *tstate = PyThreadState_Get();
721 if (tstate->context == NULL) {
722 Py_RETURN_NONE;
723 }
724 if (((PyContext *)tstate->context)->ctx_prev != NULL) {
725 PyErr_SetString(PyExc_RuntimeError,
726 "must first exit all non-base contexts");
727 return NULL;
728 }
729 Py_CLEAR(tstate->context);
730 Py_RETURN_NONE;
731 }
732
733 static PyObject *
734 get_context_switches(PyObject *Py_UNUSED(self), PyObject *watcher_id)
735 {
736 assert(PyLong_Check(watcher_id));
737 long watcher_id_l = PyLong_AsLong(watcher_id);
738 if (watcher_id_l < 0 || watcher_id_l >= NUM_CONTEXT_WATCHERS) {
739 PyErr_Format(PyExc_ValueError, "invalid watcher %ld", watcher_id_l);
740 return NULL;
741 }
742 if (context_switches[watcher_id_l] == NULL) {
743 return PyList_New(0);
744 }
745 return Py_NewRef(context_switches[watcher_id_l]);
746 }
747
748 static PyObject *
749 allocate_too_many_context_watchers(PyObject *self, PyObject *Py_UNUSED(args))
750 {
751 int watcher_ids[CONTEXT_MAX_WATCHERS + 1];
752 int num_watchers = 0;
753 for (unsigned long i = 0; i < sizeof(watcher_ids) / sizeof(int); i++) {
754 int watcher_id = PyContext_AddWatcher(noop_context_event_handler);
755 if (watcher_id == -1) {
756 break;
757 }
758 watcher_ids[i] = watcher_id;
759 num_watchers++;
760 }
761 PyObject *exc = PyErr_GetRaisedException();
762 for (int i = 0; i < num_watchers; i++) {
763 if (PyContext_ClearWatcher(watcher_ids[i]) < 0) {
764 PyErr_FormatUnraisable("Exception ignored while "
765 "clearing context watcher");
766 break;
767 }
768 }
769 if (exc) {
770 PyErr_SetRaisedException(exc);
771 return NULL;
772 }
773 else if (PyErr_Occurred()) {
774 return NULL;
775 }
776 Py_RETURN_NONE;
777 }
778
779 /*[clinic input]
780 _testcapi.set_func_defaults_via_capi
781 func: object
782 defaults: object
783 /
784 [clinic start generated code]*/
785
786 static PyObject *
787 _testcapi_set_func_defaults_via_capi_impl(PyObject *module, PyObject *func,
788 PyObject *defaults)
789 /*[clinic end generated code: output=caf0cb39db31ac24 input=e04a8508ca9d42fc]*/
790 {
791 if (PyFunction_SetDefaults(func, defaults) < 0) {
792 return NULL;
793 }
794 Py_RETURN_NONE;
795 }
796
797 /*[clinic input]
798 _testcapi.set_func_kwdefaults_via_capi = _testcapi.set_func_defaults_via_capi
799 [clinic start generated code]*/
800
801 static PyObject *
802 _testcapi_set_func_kwdefaults_via_capi_impl(PyObject *module, PyObject *func,
803 PyObject *defaults)
804 /*[clinic end generated code: output=9ed3b08177025070 input=f3cd1ca3c18de8ce]*/
805 {
806 if (PyFunction_SetKwDefaults(func, defaults) < 0) {
807 return NULL;
808 }
809 Py_RETURN_NONE;
810 }
811
812 static PyMethodDef test_methods[] = {
813 // Dict watchers.
814 {"add_dict_watcher", add_dict_watcher, METH_O, NULL},
815 {"clear_dict_watcher", clear_dict_watcher, METH_O, NULL},
816 _TESTCAPI_WATCH_DICT_METHODDEF
817 _TESTCAPI_UNWATCH_DICT_METHODDEF
818 {"get_dict_watcher_events", get_dict_watcher_events, METH_NOARGS, NULL},
819
820 // Type watchers.
821 {"add_type_watcher", add_type_watcher, METH_O, NULL},
822 {"clear_type_watcher", clear_type_watcher, METH_O, NULL},
823 _TESTCAPI_WATCH_TYPE_METHODDEF
824 _TESTCAPI_UNWATCH_TYPE_METHODDEF
825 {"get_type_modified_events",
826 get_type_modified_events, METH_NOARGS, NULL},
827
828 // Code object watchers.
829 {"add_code_watcher", add_code_watcher, METH_O, NULL},
830 {"clear_code_watcher", clear_code_watcher, METH_O, NULL},
831 {"get_code_watcher_num_created_events",
832 get_code_watcher_num_created_events, METH_O, NULL},
833 {"get_code_watcher_num_destroyed_events",
834 get_code_watcher_num_destroyed_events, METH_O, NULL},
835 {"allocate_too_many_code_watchers",
836 allocate_too_many_code_watchers, METH_NOARGS, NULL},
837
838 // Function watchers.
839 {"add_func_watcher", add_func_watcher, METH_O, NULL},
840 {"clear_func_watcher", clear_func_watcher, METH_O, NULL},
841 _TESTCAPI_SET_FUNC_DEFAULTS_VIA_CAPI_METHODDEF
842 _TESTCAPI_SET_FUNC_KWDEFAULTS_VIA_CAPI_METHODDEF
843 {"allocate_too_many_func_watchers", allocate_too_many_func_watchers,
844 METH_NOARGS, NULL},
845
846 // Code object watchers.
847 {"add_context_watcher", add_context_watcher, METH_O, NULL},
848 {"clear_context_watcher", clear_context_watcher, METH_O, NULL},
849 {"clear_context_stack", clear_context_stack, METH_NOARGS, NULL},
850 {"get_context_switches", get_context_switches, METH_O, NULL},
851 {"allocate_too_many_context_watchers",
852 allocate_too_many_context_watchers, METH_NOARGS, NULL},
853 {NULL},
854 };
855
856 int
857 _PyTestCapi_Init_Watchers(PyObject *mod)
858 {
859 if (PyModule_AddFunctions(mod, test_methods) < 0) {
860 return -1;
861 }
862
863 /* Expose each event as an attribute on the module */
864 #define ADD_EVENT(event) \
865 if (add_func_event(mod, "PYFUNC_EVENT_" #event, \
866 PyFunction_EVENT_##event)) { \
867 return -1; \
868 }
869 PY_FOREACH_FUNC_EVENT(ADD_EVENT);
870 #undef ADD_EVENT
871
872 return 0;
873 }