This repository was archived by the owner on Feb 13, 2025. It is now read-only.
forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathtaskletobject.c
More file actions
2546 lines (2229 loc) · 77.7 KB
/
taskletobject.c
File metadata and controls
2546 lines (2229 loc) · 77.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************
The Tasklet
******************************************************/
#include "Python.h"
#include "structmember.h"
#ifdef STACKLESS
#include "pycore_stackless.h"
#include "pycore_context.h"
/*[clinic input]
module _stackless
class _stackless.tasklet "PyTaskletObject *" "&PyTasklet_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=81570dcf604e6e6d]*/
#include "clinic/taskletobject.c.h"
/*
* Convert C-bitfield
*/
Py_LOCAL_INLINE(PyTaskletFlagStruc)
tasklet_flags_from_integer(int flags) {
#if defined(SLP_USE_NATIVE_BITFIELD_LAYOUT) && SLP_USE_NATIVE_BITFIELD_LAYOUT
PyTaskletFlagStruc f;
Py_MEMCPY(&f, &flags, sizeof(f));
#else
/* the portable way */
PyTaskletFlagStruc f = {0, };
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, blocked);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, atomic);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, ignore_nesting);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, autoschedule);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, block_trap);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, is_zombie);
SLP_SET_BITFIELD(SLP_TASKLET_FLAGS, f, flags, pending_irq);
#endif
Py_BUILD_ASSERT(sizeof(f) == sizeof(flags));
return f;
}
Py_LOCAL_INLINE(int)
tasklet_flags_as_integer(PyTaskletFlagStruc flags) {
int f;
Py_BUILD_ASSERT(sizeof(f) == sizeof(flags));
#if defined(SLP_USE_NATIVE_BITFIELD_LAYOUT) && SLP_USE_NATIVE_BITFIELD_LAYOUT
Py_MEMCPY(&f, &flags, sizeof(f));
#else
/* the portable way */
f = SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, blocked) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, atomic) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, ignore_nesting) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, autoschedule) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, block_trap) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, is_zombie) |
SLP_GET_BITFIELD(SLP_TASKLET_FLAGS, flags, pending_irq);
#endif
return f;
}
void
slp_current_insert(PyTaskletObject *task)
{
PyThreadState *ts = task->cstate->tstate;
PyTaskletObject **chain = &ts->st.current;
assert(ts);
SLP_CHAIN_INSERT(PyTaskletObject, chain, task, next, prev);
++ts->st.runcount;
}
void
slp_current_insert_after(PyTaskletObject *task)
{
PyThreadState *ts = task->cstate->tstate;
PyTaskletObject *hold = ts->st.current;
PyTaskletObject **chain = &ts->st.current;
assert(ts);
*chain = hold->next;
SLP_CHAIN_INSERT(PyTaskletObject, chain, task, next, prev);
*chain = hold;
++ts->st.runcount;
}
void
slp_current_uninsert(PyTaskletObject *task)
{
slp_current_remove_tasklet(task);
}
PyTaskletObject *
slp_current_remove(void)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject **chain = &ts->st.current, *ret;
/* Make sure that the tasklet belongs to this thread.
* During interpreter shutdown '(*chain)->cstate->tstate' may be already NULL.
* See function slp_kill_tasks_with_stacks() in stacklesseval.c
*/
assert((*chain)->cstate->tstate == ts ||
(*chain)->cstate->tstate == NULL);
--ts->st.runcount;
assert(ts->st.runcount >= 0);
SLP_CHAIN_REMOVE(PyTaskletObject, chain, ret, next, prev);
if (ts->st.runcount == 0)
assert(ts->st.current == NULL);
return ret;
}
void
slp_current_remove_tasklet(PyTaskletObject *task)
{
PyThreadState *ts = task->cstate->tstate;
PyTaskletObject **chain = &ts->st.current, *ret, *hold;
/* Make sure the tasklet is scheduled.
*/
assert(task->next != NULL);
assert(task->prev != NULL);
assert(ts != NULL);
--ts->st.runcount;
assert(ts->st.runcount >= 0);
hold = ts->st.current;
ts->st.current = task;
SLP_CHAIN_REMOVE(PyTaskletObject, chain, ret, next, prev);
if (hold != task)
ts->st.current = hold;
if (ts->st.runcount == 0)
assert(ts->st.current == NULL);
}
void
slp_current_unremove(PyTaskletObject* task)
{
PyThreadState *ts = task->cstate->tstate;
slp_current_insert(task);
ts->st.current = task;
}
/*
* Determine if a tasklet has C stack, and thus needs to
* be switched to (killed) before it can be deleted.
* Tasklets without C stack (in a soft switched state)
* need only be released.
* If a tasklet's thread has been killed, but the
* tasklet still lingers, it has no restorable c state and may
* as well be thrown away. But this may of course cause
* problems elsewhere (why didn't the tasklet die when instructed to?)
*/
static int
tasklet_has_c_stack_and_thread(PyTaskletObject *t)
{
/* The GC may call this function for a current tasklet.
* Therefore we need the complete check. */
return t->f.frame && t->cstate && t->cstate->tstate &&
(t->cstate->tstate->st.current == t ? t->cstate->tstate->st.nesting_level : t->cstate->nesting_level) != 0;
}
static int
tasklet_traverse(PyTaskletObject *t, visitproc visit, void *arg)
{
Py_VISIT(t->f.frame);
Py_VISIT(t->tempval);
Py_VISIT(t->cstate);
Py_VISIT(t->exc_state.exc_type);
Py_VISIT(t->exc_state.exc_value);
Py_VISIT(t->exc_state.exc_traceback);
Py_VISIT(t->context);
Py_VISIT(t->profileobj);
Py_VISIT(t->traceobj);
return 0;
}
static void
tasklet_clear_frames(PyTaskletObject *t)
{
/* release frame chain */
Py_CLEAR(t->f.frame);
}
static inline void
exc_state_clear(_PyErr_StackItem *exc_state)
{
PyObject *t, *v, *tb;
t = exc_state->exc_type;
v = exc_state->exc_value;
tb = exc_state->exc_traceback;
exc_state->exc_type = NULL;
exc_state->exc_value = NULL;
exc_state->exc_traceback = NULL;
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(tb);
}
static int
tasklet_clear(PyTaskletObject *t)
{
tasklet_clear_frames(t);
Py_CLEAR(t->tempval);
Py_CLEAR(t->def_globals);
Py_CLEAR(t->context);
t->profilefunc = t->tracefunc = NULL;
t->tracing = 0;
Py_CLEAR(t->profileobj);
Py_CLEAR(t->traceobj);
/* unlink task from cstate */
if (t->cstate != NULL && t->cstate->task == t)
t->cstate->task = NULL;
Py_CLEAR(t->cstate);
exc_state_clear(&t->exc_state);
/* Assert that the tasklet is at the end of the chain. */
assert(t->exc_state.previous_item == NULL);
/* Unlink the exc_info chain. There is no guarantee, that
* the object t->exc_info points to still exists, because
* the order of calls to tp_clear is undefined.
*/
t->exc_info = &t->exc_state;
return 0;
}
/*
* the following function tries to ensure that a tasklet is
* really killed. It is called in a context where we can't
* afford that it will not be dead afterwards.
* Reason: When clearing or resurrecting and killing, the
* tasklet is in fact already dead, and the only case that
* could revive it was that __del__ was defined.
* But in the context of __del__, we can't do anything but rely
* on proper destruction, since nobody will listen to an exception.
*/
static void
kill_finally (PyObject *ob)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *self = (PyTaskletObject *) ob;
int is_mine = ts == self->cstate->tstate;
int i;
/* this could happen if we have a refcount bug, so catch it here.
assert(self != ts->st.current);
It also gets triggered on interpreter exit when we kill the tasks
with stacks (PyStackless_kill_tasks_with_stacks) and there is no
way to differentiate that case.. so it just gets commented out.
*/
self->flags.is_zombie = 1;
for (i=0; i<10 && self->f.frame != NULL; i++) {
PyTasklet_Kill(self);
if (!is_mine)
return; /* will be killed elsewhere */
}
}
/* destructing a tasklet without destroying it */
static void
tasklet_finalize(PyObject *self)
{
PyTaskletObject *t;
PyObject *error_type, *error_value, *error_traceback;
assert(PyTasklet_Check(self));
t = (PyTaskletObject *)self;
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
if (tasklet_has_c_stack_and_thread(t)) {
/*
* we want to cleanly kill the tasklet in the case it
* was forgotten.
*/
kill_finally(self);
}
/* We must not free a C-stack, that is still somewhat alive. Instead we
* add the current tasklet to gc.garbage. That's perfectly OK, because the
* tasklet is still intact. Of course this grows a new reference to the
* tasklet.
*/
if (t->f.frame && t->cstate && t->cstate->task == t && Py_SIZE(t->cstate) != 0) {
if (Py_VerboseFlag) {
PySys_WriteStderr("# tasklet_finalize: warning: tasklet %p has a non zero C-stack.\n", (void*)t);
}
if (_PyRuntime.gc.garbage == NULL) {
_PyRuntime.gc.garbage = PyList_New(0);
if (_PyRuntime.gc.garbage == NULL)
Py_FatalError("gc couldn't create gc.garbage list");
}
TASKLET_SETVAL(t, Py_None); /* don't keep tempval alive */
if (PyList_Append(_PyRuntime.gc.garbage, self) < 0)
PyErr_WriteUnraisable(self);
}
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
}
static void
tasklet_dealloc(PyTaskletObject *t)
{
if (PyTasklet_CheckExact(t)) {
/* When ob is subclass of stackless.tasklet, finalizer is called from
* subtype_dealloc.
*/
if (PyObject_CallFinalizerFromDealloc((PyObject *)t) < 0) {
// resurrected.
return;
}
}
PyObject_GC_UnTrack(t);
if (t->tsk_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *)t);
tasklet_clear(t);
Py_TYPE(t)->tp_free((PyObject*)t);
}
PyTaskletObject *
PyTasklet_New(PyTypeObject *type, PyObject *func)
{
if (type == NULL) {
type = &PyTasklet_Type;
}
if (!PyType_IsSubtype(type, &PyTasklet_Type)) {
PyErr_SetNone(PyExc_TypeError);
return NULL;
}
if (func && func != Py_None)
return (PyTaskletObject*)PyObject_CallFunctionObjArgs((PyObject*)type, func, NULL);
else
return (PyTaskletObject*)PyObject_CallFunction((PyObject*)type, NULL);
}
Py_LOCAL_INLINE(PyObject *)
_get_tasklet_context(PyTaskletObject *self)
{
PyThreadState *ts = self->cstate->tstate;
PyThreadState *cts = PyThreadState_Get();
PyObject *ctx;
assert(cts);
/* Get the context for the tasklet *self.
* If the tasklet has no context, set a new empty one.
*/
if (ts && self == ts->st.current) {
/* the tasklet *self is current */
ctx = ts->context;
if (NULL == ctx) {
if (ts == cts) {
/* *self belongs to the current thread. Call a C-API function, that
* initializes ts->context as a side effect */
ctx = PyContext_CopyCurrent();
if (NULL == ctx)
return NULL;
Py_DECREF(ctx);
ctx = ts->context;
assert(NULL != ctx);
} else {
slp_runtime_error("The tasklet has no context and you can't set one from a foreign thread.");
}
}
} else {
/* the tasklet *self is not current */
ctx = self->context;
if (NULL == ctx) {
ctx = PyContext_New();
if (NULL == ctx)
return NULL;
self->context = ctx;
}
}
Py_INCREF(ctx);
return ctx;
}
Py_LOCAL_INLINE(int)
_tasklet_init_context(PyTaskletObject *task)
{
PyThreadState *cts = PyThreadState_Get();
assert(cts);
PyObject *ctx = _get_tasklet_context(cts->st.current);
if (NULL == ctx)
return -1;
PyObject *obj = _stackless_tasklet_set_context_impl(task, ctx);
Py_DECREF(ctx);
if (NULL == obj)
return -1;
Py_DECREF(obj);
return 0;
}
static int
impl_tasklet_setup(PyTaskletObject *task, PyObject *args, PyObject *kwds, int insert);
int
PyTasklet_BindEx(PyTaskletObject *task, PyObject *func, PyObject *args, PyObject *kwargs)
{
PyThreadState *ts = task->cstate->tstate;
if (func == Py_None)
func = NULL;
if (args == Py_None)
args = NULL;
if (kwargs == Py_None)
kwargs = NULL;
if (func != NULL && !PyCallable_Check(func))
TYPE_ERROR("tasklet function must be a callable or None", -1);
if (args != NULL && !PyTuple_Check(args))
TYPE_ERROR("tasklet args must be a tuple or None", -1);
if (kwargs != NULL && !PyDict_Check(kwargs))
TYPE_ERROR("tasklet kwargs must be a dictionary or None", -1);
if (ts && ts->st.current == task) {
RUNTIME_ERROR("can't (re)bind the current tasklet", -1);
}
if (PyTasklet_Scheduled(task)) {
RUNTIME_ERROR("tasklet is scheduled", -1);
}
if (PyTasklet_GetNestingLevel(task)) {
RUNTIME_ERROR("tasklet has C state on its stack", -1);
}
if (ts && task == ts->st.main && args == NULL && kwargs == NULL) {
RUNTIME_ERROR("can't unbind the main tasklet", -1);
}
/*
* Set the context to the current context. It can be changed later on.
*/
if (func)
if (_tasklet_init_context(task))
return -1;
tasklet_clear_frames(task);
task->recursion_depth = 0;
assert(task->flags.autoschedule == 0); /* probably unused */
assert(task->flags.blocked == 0);
assert(task->f.frame == NULL);
/* cstate is set by bind_tasklet_to_frame() later on */
if ( args == NULL && kwargs == NULL) {
/* just binding or unbinding the function */
if (func == NULL)
func = Py_None;
TASKLET_SETVAL(task, func);
} else {
/* adding arguments. Absence of func means leave tmpval alone */
PyObject *old = NULL;
int result;
if (func != NULL) {
TASKLET_CLAIMVAL(task, &old);
TASKLET_SETVAL(task, func);
}
if (args == NULL) {
args = PyTuple_New(0);
if (args == NULL)
goto err;
} else
Py_INCREF(args);
if (kwargs == NULL) {
kwargs = PyDict_New();
if (kwargs == NULL) {
Py_DECREF(args);
goto err;
}
} else
Py_INCREF(kwargs);
result = impl_tasklet_setup(task, args, kwargs, 0);
Py_DECREF(args);
Py_DECREF(kwargs);
if (result)
goto err;
Py_XDECREF(old);
return 0;
err:
if (old != NULL)
TASKLET_SETVAL_OWN(task, old);
return -1;
}
return 0;
}
PyTaskletObject *
PyTasklet_Bind(PyTaskletObject *task, PyObject *func)
{
if(PyTasklet_BindEx(task, func, NULL, NULL))
return NULL;
Py_INCREF(task);
return task;
}
PyDoc_STRVAR(tasklet_bind__doc__,
"bind(func=None, args=None, kwargs=None)\n\
Binding a tasklet to a callable object, and arguments.\n\
The callable is usually passed in to the constructor.\n\
In some cases, it makes sense to be able to re-bind a tasklet,\n\
after it has been run, in order to keep its identity.\n\
This function can also be used, in place of setup() or __call__()\n\
to supply arguments to the bound function. The difference is that\n\
this will not cause the tasklet to become runnable.\n\
If all the argument are None, this method unbinds the tasklet.\n\
Note that a tasklet can only be (un)bound if it doesn't have C-state\n\
and is not scheduled and is not the current tasklet.\
");
static PyObject *
tasklet_bind(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *func = Py_None;
PyObject *fargs = Py_None;
PyObject *fkwargs = Py_None;
char *kwds[] = {"func", "args", "kwargs", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOO:bind", kwds,
&func, &fargs, &fkwargs))
return NULL;
if (PyTasklet_BindEx((PyTaskletObject *)self, func, fargs, fkwargs))
return NULL;
Py_INCREF(self);
return self;
}
#define TASKLET_TUPLEFMT "iOiOOOOOiiOO"
static PyObject *
tasklet_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *t;
/* we always need a cstate, so be sure to initialize */
if (ts->st.initial_stub == NULL) {
PyMethodDef def = {"__new__", (PyCFunction)(void(*)(void))tasklet_new, METH_VARARGS|METH_KEYWORDS};
PyObject *retval;
PyObject *func = PyCFunction_New(&def, (PyObject*)type);
if (NULL == func)
return NULL;
if (NULL == args) {
PyObject *arg = PyTuple_New(0);
if (NULL == arg)
retval = NULL;
else {
retval = PyStackless_Call_Main(func, arg, kwds);
Py_DECREF(arg);
}
}
else
retval = PyStackless_Call_Main(func, args, kwds);
Py_DECREF(func);
return retval;
}
if (type == NULL)
type = &PyTasklet_Type;
t = (PyTaskletObject *) type->tp_alloc(type, 0);
if (t == NULL)
return NULL;
memset(&t->flags, 0, sizeof(t->flags));
memset(&t->exc_state, 0, sizeof(t->exc_state));
t->exc_info = &t->exc_state;
t->recursion_depth = 0;
t->next = NULL;
t->prev = NULL;
t->f.frame = NULL;
Py_INCREF(Py_None);
t->tempval = Py_None;
t->tsk_weakreflist = NULL;
t->context = NULL;
Py_INCREF(ts->st.initial_stub);
t->cstate = ts->st.initial_stub;
t->def_globals = PyEval_GetGlobals();
Py_XINCREF(t->def_globals);
if (ts != SLP_INITIAL_TSTATE(ts)) {
/* make sure to kill tasklets with their thread */
if (slp_ensure_linkage(t)) {
Py_DECREF(t);
return NULL;
}
}
return (PyObject*) t;
}
static int
tasklet_init(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *result = tasklet_bind(self, args, kwds);
if (NULL == result)
return -1;
Py_DECREF(result);
return 0;
}
/* tasklet pickling support */
PyDoc_STRVAR(tasklet_reduce__doc__,
"Pickling a tasklet for later re-animation.\n\
Note that a tasklet can always be pickled, unless it is current.\n\
Whether it can be run after unpickling depends on the state of the\n\
involved frames. In general, you cannot run a frame with a C state.\
");
/*
Notes on pickling:
We get into trouble with the normal __reduce__ protocol, since
tasklets tend to have tasklets in tempval, and this creates
infinite recursion on pickling.
We therefore adopt the 3-element protocol of __reduce__, where
the third thing is the argument tuple for __setstate__.
Note that we don't use None as the second tuple.
As explained in 'Pickling and unpickling extension types', this
would call a property __basicnew__. This is more complicated,
since __basicnew__ has no parameters, and we need to track
the tasklet type.
The easiest solution was to just use an empty tuple, which causes
simply the tasklet() call without parameters.
*/
static PyObject *
tasklet_reduce(PyTaskletObject * t, PyObject *value)
{
PyObject *tup = NULL, *lis = NULL;
PyFrameObject *f;
PyThreadState *ts = t->cstate->tstate;
PyObject *exc_type, *exc_value, *exc_traceback, *exc_info;
PyObject *context = NULL;
int tracing, c_functions;
PyObject *profileobj, *traceobj;
if (value && !PyLong_Check(value)) {
PyErr_SetString(PyExc_TypeError, "__reduce_ex__ argument should be an integer");
return NULL;
}
if (ts && t == ts->st.current)
RUNTIME_ERROR("You cannot __reduce__ the tasklet which is"
" current.", NULL);
lis = PyList_New(0);
if (lis == NULL) goto err_exit;
f = t->f.frame;
while (f != NULL) {
int ret;
PyObject * frame_reducer;
if (PySys_Audit("sys._getframe", NULL))
goto err_exit;
frame_reducer = slp_reduce_frame(f);
if (frame_reducer == NULL)
goto err_exit;
ret = PyList_Append(lis, frame_reducer);
Py_DECREF(frame_reducer);
if (ret)
goto err_exit;
f = f->f_back;
}
if (PyList_Reverse(lis)) goto err_exit;
assert(t->cstate != NULL);
if (t->exc_state.previous_item != NULL) {
PyErr_SetString(PyExc_SystemError, "unexpected previous _PyErr_StackItem in tasklet");
goto err_exit;
}
context = _get_tasklet_context(t);
if (NULL == context)
goto err_exit;
if (ts && ts->st.pickleflags & SLP_PICKLEFLAGS_PRESERVE_TRACING_STATE) {
c_functions = slp_encode_ctrace_functions(t->tracefunc, t->profilefunc);
if (-1 == c_functions)
goto err_exit;
tracing = t->tracing;
profileobj = t->profileobj;
if (NULL == profileobj)
profileobj = Py_None;
traceobj = t->traceobj;
if (NULL == traceobj)
traceobj = Py_None;
} else {
c_functions = 0;
tracing = 0;
profileobj = Py_None;
traceobj = Py_None;
}
assert(!ts || t->exc_info != &ts->exc_state);
/* Because of the test a few lines above, it is guaranteed that t is not the current tasklet.
* Therefore we can simplify the line
*
* exc_info = slp_get_obj_for_exc_state(ts && ts->st.current == t ? ts->exc_info : t->exc_info, ts)
*
* to
*/
assert(!(ts && ts->st.current == t));
exc_info = slp_get_obj_for_exc_state(t->exc_info);
if (exc_info == NULL)
goto err_exit;
assert(exc_info != Py_None);
if (exc_info == (PyObject *)t) {
Py_INCREF(Py_None);
Py_SETREF(exc_info, Py_None);
}
assert(!PyTasklet_Check(exc_info)); /* must be a generator, coro, asynccoro, ... */
exc_type = t->exc_state.exc_type;
exc_value = t->exc_state.exc_value;
exc_traceback = t->exc_state.exc_traceback;
if (exc_type == NULL) exc_type = Py_None;
if (exc_value == NULL) exc_value = Py_None;
if (exc_traceback == NULL) exc_traceback = Py_None;
Py_INCREF(exc_type);
Py_INCREF(exc_value);
Py_INCREF(exc_traceback);
tup = Py_BuildValue((ts && (ts->st.pickleflags & SLP_PICKLEFLAGS_PICKLE_CONTEXT)) ?
"(O()(" TASKLET_TUPLEFMT "O))" : "(O()(" TASKLET_TUPLEFMT "))",
Py_TYPE(t),
tasklet_flags_as_integer(t->flags),
t->tempval,
t->cstate->nesting_level,
lis,
exc_type,
exc_value,
exc_traceback,
exc_info,
tracing,
c_functions,
profileobj,
traceobj,
context
);
Py_DECREF(exc_info);
Py_DECREF(exc_type);
Py_DECREF(exc_value);
Py_DECREF(exc_traceback);
err_exit:
Py_XDECREF(lis);
Py_XDECREF(context);
return tup;
}
PyDoc_STRVAR(tasklet_setstate__doc__,
"Tasklets are first created without parameters, and then __setstate__\n\
is called. This was necessary, since pickle has problems pickling\n\
extension types when they reference themselves.\
");
/* note that args is a tuple, although we use METH_O */
static PyObject *
tasklet_setstate(PyObject *self, PyObject *args)
{
PyTaskletObject *t = (PyTaskletObject *) self;
PyObject *tempval, *lis;
int flags, nesting_level;
PyObject *exc_type, *exc_value, *exc_traceback;
PyObject *old_type, *old_value, *old_traceback;
PyObject *exc_info_obj;
int tracing, c_functions;
PyObject *profileobj, *traceobj;
PyObject *context = NULL;
PyFrameObject *f;
Py_ssize_t i, nframes;
int j;
assert(t && PyTasklet_Check(t));
if (PyTasklet_Alive(t))
RUNTIME_ERROR("tasklet is alive", NULL);
if (!PyArg_ParseTuple(args, "iOiO!OOOOiiOO|O:tasklet",
&flags,
&tempval,
&nesting_level,
&PyList_Type, &lis,
&exc_type,
&exc_value,
&exc_traceback,
&exc_info_obj,
&tracing,
&c_functions,
&profileobj,
&traceobj,
&context))
return NULL;
if (Py_None == context)
context = NULL;
if (context != NULL && !PyContext_CheckExact(context))
TYPE_ERROR("tasklet state[8] must be a contextvars.Context or None", NULL);
nframes = PyList_GET_SIZE(lis);
TASKLET_SETVAL(t, tempval);
/* There is an unpickling race condition. While it is rare,
* sometimes tasklets get their setstate call after the
* channel they are blocked on. If this happens and we
* do not account for it, they will be left in a broken
* state where they are on the channels chain, but have
* cleared their blocked flag.
*
* We will assume that the presence of a chain, can only
* mean that the chain is that of a channel, rather than
* that of the main tasklet/scheduler. And therefore
* they can leave their blocked flag in place because the
* channel would have set it.
*/
j = t->flags.blocked;
t->flags = tasklet_flags_from_integer(flags);
if (t->next == NULL) {
t->flags.blocked = 0;
} else {
t->flags.blocked = j;
}
/* t->nesting_level = nesting_level;
XXX how do we handle this?
XXX to be done: pickle the cstate without a ref to the task.
XXX This should make it not runnable in the future.
*/
if (nframes > 0) {
PyFrameObject *back;
f = (PyFrameObject *) PyList_GET_ITEM(lis, 0);
/* slp_ensure_new_frame() returns a new ref */
if ((f = slp_ensure_new_frame(f)) == NULL)
return NULL;
back = f;
for (i=1; i<nframes; ++i) {
f = (PyFrameObject *) PyList_GET_ITEM(lis, i);
if ((f = slp_ensure_new_frame(f)) == NULL) {
Py_DECREF(back);
return NULL;
}
assert(f->f_back == NULL);
f->f_back = back;
back = f;
}
t->f.frame = f;
if(NULL == context && _tasklet_init_context(t))
return NULL;
}
/* profile and tracing */
if ((c_functions & 1) || (Py_None != traceobj)) {
/* trace setting requested */
if (PySys_Audit("sys.settrace", NULL)) {
return NULL;
}
}
if ((c_functions & 2) || (Py_None != profileobj)) {
/* profile setting requested */
if (PySys_Audit("sys.setprofile", NULL)) {
return NULL;
}
}
if (c_functions & 1) {
Py_tracefunc func = slp_get_sys_trace_func();
if (NULL == func)
return NULL;
t->tracefunc = func;
} else {
t->tracefunc = NULL;
}
if (c_functions & 2) {
Py_tracefunc func = slp_get_sys_profile_func();
if (NULL == func)
return NULL;
t->profilefunc = func;
} else {
t->profilefunc = NULL;
}
if (Py_None != profileobj) {
Py_INCREF(profileobj);
Py_XSETREF(t->profileobj, profileobj);
} else {
Py_CLEAR(t->profileobj);
}
if (Py_None != traceobj) {
Py_INCREF(traceobj);
Py_XSETREF(t->traceobj, traceobj);
} else {
Py_CLEAR(t->traceobj);
}
t->tracing = tracing;
/* context */
if (context) {
PyObject *obj = _stackless_tasklet_set_context_impl(t, context);
if (NULL == obj)
return NULL;
Py_DECREF(obj);
}
/* walk frames again and calculate recursion_depth */
for (f = t->f.frame; f != NULL; f = f->f_back) {
if (PyFrame_Check(f) && f->f_executing != SLP_FRAME_EXECUTING_NO) {
/*
* we count running frames which *have* added
* to recursion_depth
*/
++t->recursion_depth;
}
}
old_type = t->exc_state.exc_type;
old_value = t->exc_state.exc_value;
old_traceback = t->exc_state.exc_traceback;
if (exc_type != Py_None) {
Py_INCREF(exc_type);
t->exc_state.exc_type = exc_type;
} else
t->exc_state.exc_type = NULL;
if (exc_value != Py_None) {
Py_INCREF(exc_value);
t->exc_state.exc_value = exc_value;
} else
t->exc_state.exc_value = NULL;
if (exc_traceback != Py_None) {
Py_INCREF(exc_traceback);
t->exc_state.exc_traceback = exc_traceback;
} else
t->exc_state.exc_value = NULL;
assert(t->exc_state.previous_item == NULL);
/* t must not be current, otherwise we would have to assign to ts->exc_info_obj */
assert(t != _PyThreadState_GET()->st.current);
if (exc_info_obj == Py_None) {
t->exc_info = &t->exc_state;
} else {
/* Check the preconditions for the next assignment.
*
* The cast in the assignment is OK, because all possible concrete types of exc_info_obj
* have the exec_state member at the same offset.
*/
assert(PyGen_Check(exc_info_obj) ||
PyObject_TypeCheck(exc_info_obj, &PyCoro_Type) ||
PyObject_TypeCheck(exc_info_obj, &PyAsyncGen_Type));
Py_BUILD_ASSERT(offsetof(PyGenObject, gi_exc_state) == offsetof(PyCoroObject, cr_exc_state));
Py_BUILD_ASSERT(offsetof(PyGenObject, gi_exc_state) == offsetof(PyAsyncGenObject, ag_exc_state));
/* Make sure, that *exc_info_obj stays alive after Py_DECREF(args).
*/
assert(Py_REFCNT(exc_info_obj) > 1);
t->exc_info = &(((PyGenObject *)exc_info_obj)->gi_exc_state);
}
Py_INCREF(self);
Py_XDECREF(old_type);
Py_XDECREF(old_value);
Py_XDECREF(old_traceback);
return self;
}
PyDoc_STRVAR(tasklet_bind_thread__doc__,
"Attempts to re-bind the tasklet to the current thread.\n\
If the tasklet has non-trivial c state, a RuntimeError is\n\
raised.\n\
");
static PyObject *
tasklet_bind_thread(PyObject *self, PyObject *args)
{
PyObject *thread_id = NULL;
unsigned long target_tid = (unsigned long)-1;
assert(PyTasklet_Check(self));
if (!PyArg_ParseTuple(args, "|O!:bind_thread", &PyLong_Type, &thread_id))
return NULL;
if (!slp_parse_thread_id(thread_id, &target_tid))
return NULL;
if (PyTasklet_BindThread((PyTaskletObject *) self, target_tid))
return NULL;
Py_RETURN_NONE;
}
int
PyTasklet_BindThread(PyTaskletObject *task, unsigned long thread_id)
{
PyThreadState *ts = task->cstate->tstate;
PyThreadState *cts = _PyThreadState_GET();
PyObject *old;
assert(PyTasklet_Check(task));
if (thread_id == (unsigned long)-1 && ts == cts)