forked from python-greenlet/greenlet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
greenlet.c
1711 lines (1536 loc) · 45 KB
/
greenlet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim:set noet ts=8 sw=8 : */
#define GREENLET_MODULE
#include "greenlet.h"
#include "structmember.h"
/***********************************************************
A PyGreenlet is a range of C stack addresses that must be
saved and restored in such a way that the full range of the
stack contains valid data when we switch to it.
Stack layout for a greenlet:
| ^^^ |
| older data |
| |
stack_stop . |_______________|
. | |
. | greenlet data |
. | in stack |
. * |_______________| . . _____________ stack_copy + stack_saved
. | | | |
. | data | |greenlet data|
. | unrelated | | saved |
. | to | | in heap |
stack_start . | this | . . |_____________| stack_copy
| greenlet |
| |
| newer data |
| vvv |
Note that a greenlet's stack data is typically partly at its correct
place in the stack, and partly saved away in the heap, but always in
the above configuration: two blocks, the more recent one in the heap
and the older one still in the stack (either block may be empty).
Greenlets are chained: each points to the previous greenlet, which is
the one that owns the data currently in the C stack above my
stack_stop. The currently running greenlet is the first element of
this chain. The main (initial) greenlet is the last one. Greenlets
whose stack is entirely in the heap can be skipped from the chain.
The chain is not related to execution order, but only to the order
in which bits of C stack happen to belong to greenlets at a particular
point in time.
The main greenlet doesn't have a stack_stop: it is responsible for the
complete rest of the C stack, and we don't know where it begins. We
use (char*) -1, the largest possible address.
States:
stack_stop == NULL && stack_start == NULL: did not start yet
stack_stop != NULL && stack_start == NULL: already finished
stack_stop != NULL && stack_start != NULL: active
The running greenlet's stack_start is undefined but not NULL.
***********************************************************/
/*** global state ***/
/* In the presence of multithreading, this is a bit tricky:
- ts_current always store a reference to a greenlet, but it is
not really the current greenlet after a thread switch occurred.
- each *running* greenlet uses its run_info field to know which
thread it is attached to. A greenlet can only run in the thread
where it was created. This run_info is a ref to tstate->dict.
- the thread state dict is used to save and restore ts_current,
using the dictionary key 'ts_curkey'.
*/
/* Python 2.3 support */
#ifndef Py_VISIT
#define Py_VISIT(o) \
if (o) { \
int err; \
if ((err = visit((PyObject *)(o), arg))) { \
return err; \
} \
}
#endif /* !Py_VISIT */
#ifndef Py_CLEAR
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(tmp); \
} \
} while (0)
#endif /* !Py_CLEAR */
/* Python <= 2.5 support */
#if PY_MAJOR_VERSION < 3
#ifndef Py_REFCNT
# define Py_REFCNT(ob) (((PyObject *) (ob))->ob_refcnt)
#endif
#ifndef Py_TYPE
# define Py_TYPE(ob) (((PyObject *) (ob))->ob_type)
#endif
#endif
#if PY_VERSION_HEX < 0x02050000
typedef int Py_ssize_t;
#endif
extern PyTypeObject PyGreenlet_Type;
/* Defines that customize greenlet module behaviour */
#ifndef GREENLET_USE_GC
#define GREENLET_USE_GC 1
#endif
#ifndef GREENLET_USE_TRACING
#define GREENLET_USE_TRACING 1
#endif
/* Weak reference to the switching-to greenlet during the slp switch */
static PyGreenlet* volatile ts_target = NULL;
/* Strong reference to the switching from greenlet after the switch */
static PyGreenlet* volatile ts_origin = NULL;
/* Strong reference to the current greenlet in this thread state */
static PyGreenlet* volatile ts_current = NULL;
/* NULL if error, otherwise args tuple to pass around during slp switch */
static PyObject* volatile ts_passaround_args = NULL;
static PyObject* volatile ts_passaround_kwargs = NULL;
/***********************************************************/
/* Thread-aware routines, switching global variables when needed */
#define STATE_OK (ts_current->run_info == PyThreadState_GET()->dict \
|| !green_updatecurrent())
static PyObject* ts_curkey;
static PyObject* ts_delkey;
#if GREENLET_USE_TRACING
static PyObject* ts_tracekey;
static PyObject* ts_event_switch;
static PyObject* ts_event_throw;
#endif
static PyObject* PyExc_GreenletError;
static PyObject* PyExc_GreenletExit;
#if GREENLET_USE_GC
#define GREENLET_GC_FLAGS Py_TPFLAGS_HAVE_GC
#define GREENLET_tp_alloc PyType_GenericAlloc
#define GREENLET_tp_free PyObject_GC_Del
#define GREENLET_tp_traverse green_traverse
#define GREENLET_tp_clear green_clear
#define GREENLET_tp_is_gc green_is_gc
#else /* GREENLET_USE_GC */
#define GREENLET_GC_FLAGS 0
#define GREENLET_tp_alloc 0
#define GREENLET_tp_free 0
#define GREENLET_tp_traverse 0
#define GREENLET_tp_clear 0
#define GREENLET_tp_is_gc 0
#endif /* !GREENLET_USE_GC */
static PyGreenlet* green_create_main(void)
{
PyGreenlet* gmain;
PyObject* dict = PyThreadState_GetDict();
if (dict == NULL) {
if (!PyErr_Occurred())
PyErr_NoMemory();
return NULL;
}
/* create the main greenlet for this thread */
gmain = (PyGreenlet*) PyType_GenericAlloc(&PyGreenlet_Type, 0);
if (gmain == NULL)
return NULL;
gmain->stack_start = (char*) 1;
gmain->stack_stop = (char*) -1;
gmain->run_info = dict;
Py_INCREF(dict);
return gmain;
}
static int green_updatecurrent(void)
{
PyObject *exc, *val, *tb;
PyThreadState* tstate;
PyGreenlet* current;
PyGreenlet* previous;
PyObject* deleteme;
green_updatecurrent_restart:
/* save current exception */
PyErr_Fetch(&exc, &val, &tb);
/* get ts_current from the active tstate */
tstate = PyThreadState_GET();
if (tstate->dict && (current =
(PyGreenlet*) PyDict_GetItem(tstate->dict, ts_curkey))) {
/* found -- remove it, to avoid keeping a ref */
Py_INCREF(current);
PyDict_DelItem(tstate->dict, ts_curkey);
}
else {
/* first time we see this tstate */
current = green_create_main();
if (current == NULL) {
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(tb);
return -1;
}
}
assert(current->run_info == tstate->dict);
green_updatecurrent_retry:
/* update ts_current as soon as possible, in case of nested switches */
Py_INCREF(current);
previous = ts_current;
ts_current = current;
/* save ts_current as the current greenlet of its own thread */
if (PyDict_SetItem(previous->run_info, ts_curkey, (PyObject*) previous)) {
Py_DECREF(previous);
Py_DECREF(current);
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(tb);
return -1;
}
Py_DECREF(previous);
/* green_dealloc() cannot delete greenlets from other threads, so
it stores them in the thread dict; delete them now. */
deleteme = PyDict_GetItem(tstate->dict, ts_delkey);
if (deleteme != NULL) {
PyList_SetSlice(deleteme, 0, INT_MAX, NULL);
}
if (ts_current != current) {
/* some Python code executed above and there was a thread switch,
* so ts_current points to some other thread again. We need to
* delete ts_curkey (it's likely there) and retry. */
PyDict_DelItem(tstate->dict, ts_curkey);
goto green_updatecurrent_retry;
}
/* release an extra reference */
Py_DECREF(current);
/* restore current exception */
PyErr_Restore(exc, val, tb);
/* thread switch could happen during PyErr_Restore, in that
case there's nothing to do except restart from scratch. */
if (ts_current->run_info != tstate->dict)
goto green_updatecurrent_restart;
return 0;
}
static PyObject* green_statedict(PyGreenlet* g)
{
while (!PyGreenlet_STARTED(g)) {
g = g->parent;
if (g == NULL) {
/* garbage collected greenlet in chain */
return NULL;
}
}
return g->run_info;
}
/***********************************************************/
/* Some functions must not be inlined:
* slp_restore_state, when inlined into slp_switch might cause
it to restore stack over its own local variables
* slp_save_state, when inlined would add its own local
variables to the saved stack, wasting space
* slp_switch, cannot be inlined for obvious reasons
* g_initialstub, when inlined would receive a pointer into its
own stack frame, leading to incomplete stack save/restore
*/
#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
#define GREENLET_NOINLINE_SUPPORTED
#define GREENLET_NOINLINE(name) __attribute__((noinline)) name
#elif defined(_MSC_VER) && (_MSC_VER >= 1300)
#define GREENLET_NOINLINE_SUPPORTED
#define GREENLET_NOINLINE(name) __declspec(noinline) name
#endif
#ifdef GREENLET_NOINLINE_SUPPORTED
/* add forward declarations */
static void GREENLET_NOINLINE(slp_restore_state)(void);
static int GREENLET_NOINLINE(slp_save_state)(char*);
#if !(defined(MS_WIN64) && defined(_M_X64))
static int GREENLET_NOINLINE(slp_switch)(void);
#endif
static int GREENLET_NOINLINE(g_initialstub)(void*);
#define GREENLET_NOINLINE_INIT() do {} while(0)
#else
/* force compiler to call functions via pointers */
static void (*slp_restore_state)(void);
static int (*slp_save_state)(char*);
static int (*slp_switch)(void);
static int (*g_initialstub)(void*);
#define GREENLET_NOINLINE(name) cannot_inline_ ## name
#define GREENLET_NOINLINE_INIT() do { \
slp_restore_state = GREENLET_NOINLINE(slp_restore_state); \
slp_save_state = GREENLET_NOINLINE(slp_save_state); \
slp_switch = GREENLET_NOINLINE(slp_switch); \
g_initialstub = GREENLET_NOINLINE(g_initialstub); \
} while(0)
#endif
/***********************************************************/
static int g_save(PyGreenlet* g, char* stop)
{
/* Save more of g's stack into the heap -- at least up to 'stop'
g->stack_stop |________|
| |
| __ stop . . . . .
| | ==> . .
|________| _______
| | | |
| | | |
g->stack_start | | |_______| g->stack_copy
*/
intptr_t sz1 = g->stack_saved;
intptr_t sz2 = stop - g->stack_start;
assert(g->stack_start != NULL);
if (sz2 > sz1) {
char* c = (char*)PyMem_Realloc(g->stack_copy, sz2);
if (!c) {
PyErr_NoMemory();
return -1;
}
memcpy(c+sz1, g->stack_start+sz1, sz2-sz1);
g->stack_copy = c;
g->stack_saved = sz2;
}
return 0;
}
static void GREENLET_NOINLINE(slp_restore_state)(void)
{
PyGreenlet* g = ts_target;
PyGreenlet* owner = ts_current;
/* Restore the heap copy back into the C stack */
if (g->stack_saved != 0) {
memcpy(g->stack_start, g->stack_copy, g->stack_saved);
PyMem_Free(g->stack_copy);
g->stack_copy = NULL;
g->stack_saved = 0;
}
if (owner->stack_start == NULL)
owner = owner->stack_prev; /* greenlet is dying, skip it */
while (owner && owner->stack_stop <= g->stack_stop)
owner = owner->stack_prev; /* find greenlet with more stack */
g->stack_prev = owner;
}
static int GREENLET_NOINLINE(slp_save_state)(char* stackref)
{
/* must free all the C stack up to target_stop */
char* target_stop = ts_target->stack_stop;
PyGreenlet* owner = ts_current;
assert(owner->stack_saved == 0);
if (owner->stack_start == NULL)
owner = owner->stack_prev; /* not saved if dying */
else
owner->stack_start = stackref;
while (owner->stack_stop < target_stop) {
/* ts_current is entierely within the area to free */
if (g_save(owner, owner->stack_stop))
return -1; /* XXX */
owner = owner->stack_prev;
}
if (owner != ts_target) {
if (g_save(owner, target_stop))
return -1; /* XXX */
}
return 0;
}
/*
* the following macros are spliced into the OS/compiler
* specific code, in order to simplify maintenance.
*/
#define SLP_SAVE_STATE(stackref, stsizediff) \
stackref += STACK_MAGIC; \
if (slp_save_state((char*)stackref)) return -1; \
if (!PyGreenlet_ACTIVE(ts_target)) return 1; \
stsizediff = ts_target->stack_start - (char*)stackref
#define SLP_RESTORE_STATE() \
slp_restore_state()
#define SLP_EVAL
#define slp_switch GREENLET_NOINLINE(slp_switch)
#include "slp_platformselect.h"
#undef slp_switch
#ifndef STACK_MAGIC
#error "greenlet needs to be ported to this platform,\
or teached how to detect your compiler properly."
#endif /* !STACK_MAGIC */
#ifdef EXTERNAL_ASM
/* CCP addition: Make these functions, to be called from assembler.
* The token include file for the given platform should enable the
* EXTERNAL_ASM define so that this is included.
*/
intptr_t slp_save_state_asm(intptr_t *ref) {
intptr_t diff;
SLP_SAVE_STATE(ref, diff);
return diff;
}
void slp_restore_state_asm(void) {
SLP_RESTORE_STATE();
}
extern int slp_switch(void);
#endif
static int g_switchstack(void)
{
/* Perform a stack switch according to some global variables
that must be set before:
- ts_current: current greenlet (holds a reference)
- ts_target: greenlet to switch to (weak reference)
- ts_passaround_args: NULL if PyErr_Occurred(),
else a tuple of args sent to ts_target (holds a reference)
- ts_passaround_kwargs: switch kwargs (holds a reference)
On return results are passed via global variables as well:
- ts_origin: originating greenlet (holds a reference)
- ts_current: current greenlet (holds a reference)
- ts_passaround_args: NULL if PyErr_Occurred(),
else a tuple of args sent to ts_current (holds a reference)
- ts_passaround_kwargs: switch kwargs (holds a reference)
It is very important that stack switch is 'atomic', i.e. no
calls into other Python code allowed (except very few that
are safe), because global variables are very fragile.
*/
int err;
{ /* save state */
PyGreenlet* current = ts_current;
PyThreadState* tstate = PyThreadState_GET();
current->recursion_depth = tstate->recursion_depth;
current->top_frame = tstate->frame;
current->exc_type = tstate->exc_type;
current->exc_value = tstate->exc_value;
current->exc_traceback = tstate->exc_traceback;
}
err = slp_switch();
if (err < 0) { /* error */
PyGreenlet* current = ts_current;
current->top_frame = NULL;
current->exc_type = NULL;
current->exc_value = NULL;
current->exc_traceback = NULL;
assert(ts_origin == NULL);
ts_target = NULL;
}
else {
PyGreenlet* target = ts_target;
PyGreenlet* origin = ts_current;
PyThreadState* tstate = PyThreadState_GET();
tstate->recursion_depth = target->recursion_depth;
tstate->frame = target->top_frame;
target->top_frame = NULL;
tstate->exc_type = target->exc_type;
target->exc_type = NULL;
tstate->exc_value = target->exc_value;
target->exc_value = NULL;
tstate->exc_traceback = target->exc_traceback;
target->exc_traceback = NULL;
assert(ts_origin == NULL);
Py_INCREF(target);
ts_current = target;
ts_origin = origin;
ts_target = NULL;
}
return err;
}
#if GREENLET_USE_TRACING
static int
g_calltrace(PyObject* tracefunc, PyObject* event, PyGreenlet* origin, PyGreenlet* target)
{
PyObject *retval;
PyObject *exc_type, *exc_val, *exc_tb;
PyThreadState *tstate;
PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
tstate = PyThreadState_GET();
tstate->tracing++;
tstate->use_tracing = 0;
retval = PyObject_CallFunction(tracefunc, "O(OO)", event, origin, target);
tstate->tracing--;
tstate->use_tracing = (tstate->tracing <= 0 &&
((tstate->c_tracefunc != NULL) ||
(tstate->c_profilefunc != NULL)));
if (retval == NULL) {
/* In case of exceptions trace function is removed */
if (PyDict_GetItem(tstate->dict, ts_tracekey))
PyDict_DelItem(tstate->dict, ts_tracekey);
Py_XDECREF(exc_type);
Py_XDECREF(exc_val);
Py_XDECREF(exc_tb);
return -1;
} else
Py_DECREF(retval);
PyErr_Restore(exc_type, exc_val, exc_tb);
return 0;
}
#endif
static PyObject *
g_switch(PyGreenlet* target, PyObject* args, PyObject* kwargs)
{
/* _consumes_ a reference to the args tuple and kwargs dict,
and return a new tuple reference */
int err;
PyObject* run_info;
/* check ts_current */
if (!STATE_OK) {
Py_XDECREF(args);
Py_XDECREF(kwargs);
return NULL;
}
run_info = green_statedict(target);
if (run_info == NULL || run_info != ts_current->run_info) {
Py_XDECREF(args);
Py_XDECREF(kwargs);
PyErr_SetString(PyExc_GreenletError, run_info
? "cannot switch to a different thread"
: "cannot switch to a garbage collected greenlet");
return NULL;
}
ts_passaround_args = args;
ts_passaround_kwargs = kwargs;
/* find the real target by ignoring dead greenlets,
and if necessary starting a greenlet. */
while (target) {
if (PyGreenlet_ACTIVE(target)) {
ts_target = target;
err = g_switchstack();
break;
}
if (!PyGreenlet_STARTED(target)) {
void* dummymarker;
ts_target = target;
err = g_initialstub(&dummymarker);
if (err == 1) {
continue; /* retry the switch */
}
break;
}
target = target->parent;
}
/* For a very short time, immediately after the 'atomic'
g_switchstack() call, global variables are in a known state.
We need to save everything we need, before it is destroyed
by calls into arbitrary Python code. */
args = ts_passaround_args;
ts_passaround_args = NULL;
kwargs = ts_passaround_kwargs;
ts_passaround_kwargs = NULL;
if (err < 0) {
/* Turn switch errors into switch throws */
assert(ts_origin == NULL);
Py_CLEAR(kwargs);
Py_CLEAR(args);
} else {
PyGreenlet *origin;
#if GREENLET_USE_TRACING
PyGreenlet *current;
PyObject *tracefunc;
#endif
origin = ts_origin;
ts_origin = NULL;
#if GREENLET_USE_TRACING
current = ts_current;
if ((tracefunc = PyDict_GetItem(current->run_info, ts_tracekey)) != NULL) {
Py_INCREF(tracefunc);
if (g_calltrace(tracefunc, args ? ts_event_switch : ts_event_throw, origin, current) < 0) {
/* Turn trace errors into switch throws */
Py_CLEAR(kwargs);
Py_CLEAR(args);
}
Py_DECREF(tracefunc);
}
#endif
Py_DECREF(origin);
}
/* We need to figure out what values to pass to the target greenlet
based on the arguments that have been passed to greenlet.switch(). If
switch() was just passed an arg tuple, then we'll just return that.
If only keyword arguments were passed, then we'll pass the keyword
argument dict. Otherwise, we'll create a tuple of (args, kwargs) and
return both. */
if (kwargs == NULL)
{
return args;
}
else if (PyDict_Size(kwargs) == 0)
{
Py_DECREF(kwargs);
return args;
}
else if (PySequence_Length(args) == 0)
{
Py_DECREF(args);
return kwargs;
}
else
{
PyObject *tuple = PyTuple_New(2);
if (tuple == NULL) {
Py_DECREF(args);
Py_DECREF(kwargs);
return NULL;
}
PyTuple_SET_ITEM(tuple, 0, args);
PyTuple_SET_ITEM(tuple, 1, kwargs);
return tuple;
}
}
static PyObject *
g_handle_exit(PyObject *result)
{
if (result == NULL && PyErr_ExceptionMatches(PyExc_GreenletExit))
{
/* catch and ignore GreenletExit */
PyObject *exc, *val, *tb;
PyErr_Fetch(&exc, &val, &tb);
if (val == NULL)
{
Py_INCREF(Py_None);
val = Py_None;
}
result = val;
Py_DECREF(exc);
Py_XDECREF(tb);
}
if (result != NULL)
{
/* package the result into a 1-tuple */
PyObject *r = result;
result = PyTuple_New(1);
if (result)
{
PyTuple_SET_ITEM(result, 0, r);
}
else
{
Py_DECREF(r);
}
}
return result;
}
static int GREENLET_NOINLINE(g_initialstub)(void* mark)
{
int err;
PyObject *o, *run;
PyObject *exc, *val, *tb;
PyObject *run_info;
PyGreenlet* self = ts_target;
PyObject* args = ts_passaround_args;
PyObject* kwargs = ts_passaround_kwargs;
/* save exception in case getattr clears it */
PyErr_Fetch(&exc, &val, &tb);
/* self.run is the object to call in the new greenlet */
run = PyObject_GetAttrString((PyObject*) self, "run");
if (run == NULL) {
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(tb);
return -1;
}
/* restore saved exception */
PyErr_Restore(exc, val, tb);
/* recheck the state in case getattr caused thread switches */
if (!STATE_OK) {
Py_DECREF(run);
return -1;
}
/* recheck run_info in case greenlet reparented anywhere above */
run_info = green_statedict(self);
if (run_info == NULL || run_info != ts_current->run_info) {
Py_DECREF(run);
PyErr_SetString(PyExc_GreenletError, run_info
? "cannot switch to a different thread"
: "cannot switch to a garbage collected greenlet");
return -1;
}
/* by the time we got here another start could happen elsewhere,
* that means it should now be a regular switch
*/
if (PyGreenlet_STARTED(self)) {
Py_DECREF(run);
ts_passaround_args = args;
ts_passaround_kwargs = kwargs;
return 1;
}
/* start the greenlet */
self->stack_start = NULL;
self->stack_stop = (char*) mark;
if (ts_current->stack_start == NULL) {
/* ts_current is dying */
self->stack_prev = ts_current->stack_prev;
}
else {
self->stack_prev = ts_current;
}
self->top_frame = NULL;
self->exc_type = NULL;
self->exc_value = NULL;
self->exc_traceback = NULL;
self->recursion_depth = PyThreadState_GET()->recursion_depth;
/* restore arguments in case they are clobbered */
ts_target = self;
ts_passaround_args = args;
ts_passaround_kwargs = kwargs;
/* perform the initial switch */
err = g_switchstack();
/* returns twice!
The 1st time with err=1: we are in the new greenlet
The 2nd time with err=0: back in the caller's greenlet
*/
if (err == 1) {
/* in the new greenlet */
PyGreenlet* origin;
#if GREENLET_USE_TRACING
PyObject* tracefunc;
#endif
PyObject* result;
PyGreenlet* parent;
self->stack_start = (char*) 1; /* running */
/* grab origin while we still can */
origin = ts_origin;
ts_origin = NULL;
/* now use run_info to store the statedict */
o = self->run_info;
self->run_info = green_statedict(self->parent);
Py_INCREF(self->run_info);
Py_XDECREF(o);
#if GREENLET_USE_TRACING
if ((tracefunc = PyDict_GetItem(self->run_info, ts_tracekey)) != NULL) {
Py_INCREF(tracefunc);
if (g_calltrace(tracefunc, args ? ts_event_switch : ts_event_throw, origin, self) < 0) {
/* Turn trace errors into switch throws */
Py_CLEAR(kwargs);
Py_CLEAR(args);
}
Py_DECREF(tracefunc);
}
#endif
Py_DECREF(origin);
if (args == NULL) {
/* pending exception */
result = NULL;
} else {
/* call g.run(*args, **kwargs) */
result = PyEval_CallObjectWithKeywords(
run, args, kwargs);
Py_DECREF(args);
Py_XDECREF(kwargs);
}
Py_DECREF(run);
result = g_handle_exit(result);
/* jump back to parent */
self->stack_start = NULL; /* dead */
for (parent = self->parent; parent != NULL; parent = parent->parent) {
result = g_switch(parent, result, NULL);
/* Return here means switch to parent failed,
* in which case we throw *current* exception
* to the next parent in chain.
*/
assert(result == NULL);
}
/* We ran out of parents, cannot continue */
PyErr_WriteUnraisable((PyObject *) self);
Py_FatalError("greenlets cannot continue");
}
/* back in the parent */
if (err < 0) {
/* start failed badly, restore greenlet state */
self->stack_start = NULL;
self->stack_stop = NULL;
self->stack_prev = NULL;
}
return err;
}
/***********************************************************/
static PyObject* green_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject* o;
if (!STATE_OK)
return NULL;
o = type->tp_alloc(type, 0);
if (o != NULL) {
Py_INCREF(ts_current);
((PyGreenlet*) o)->parent = ts_current;
}
return o;
}
static int green_setrun(PyGreenlet* self, PyObject* nparent, void* c);
static int green_setparent(PyGreenlet* self, PyObject* nparent, void* c);
static int green_init(PyGreenlet *self, PyObject *args, PyObject *kwargs)
{
PyObject *run = NULL;
PyObject* nparent = NULL;
static char *kwlist[] = {"run", "parent", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO:green", kwlist,
&run, &nparent))
return -1;
if (run != NULL) {
if (green_setrun(self, run, NULL))
return -1;
}
if (nparent != NULL && nparent != Py_None)
return green_setparent(self, nparent, NULL);
return 0;
}
static int kill_greenlet(PyGreenlet* self)
{
/* Cannot raise an exception to kill the greenlet if
it is not running in the same thread! */
if (self->run_info == PyThreadState_GET()->dict) {
/* The dying greenlet cannot be a parent of ts_current
because the 'parent' field chain would hold a
reference */
PyObject* result;
PyGreenlet* oldparent;
PyGreenlet* tmp;
if (!STATE_OK) {
return -1;
}
oldparent = self->parent;
self->parent = ts_current;
Py_INCREF(self->parent);
/* Send the greenlet a GreenletExit exception. */
PyErr_SetNone(PyExc_GreenletExit);
result = g_switch(self, NULL, NULL);
tmp = self->parent;
self->parent = oldparent;
Py_XDECREF(tmp);
if (result == NULL)
return -1;
Py_DECREF(result);
return 0;
}
else {
/* Not the same thread! Temporarily save the greenlet
into its thread's ts_delkey list. */
PyObject* lst;
lst = PyDict_GetItem(self->run_info, ts_delkey);
if (lst == NULL) {
lst = PyList_New(0);
if (lst == NULL || PyDict_SetItem(self->run_info,
ts_delkey, lst) < 0)
return -1;
}
if (PyList_Append(lst, (PyObject*) self) < 0)
return -1;
if (!STATE_OK) /* to force ts_delkey to be reconsidered */
return -1;
return 0;
}
}
#if GREENLET_USE_GC
static int
green_traverse(PyGreenlet *self, visitproc visit, void *arg)
{
/* We must only visit referenced objects, i.e. only objects
Py_INCREF'ed by this greenlet (directly or indirectly):
- stack_prev is not visited: holds previous stack pointer, but it's not referenced
- frames are not visited: alive greenlets are not garbage collected anyway */
Py_VISIT((PyObject*)self->parent);
Py_VISIT(self->run_info);
Py_VISIT(self->exc_type);
Py_VISIT(self->exc_value);
Py_VISIT(self->exc_traceback);
Py_VISIT(self->dict);
return 0;
}
static int green_is_gc(PyGreenlet* self)
{
/* Main greenlet can be garbage collected since it can only
become unreachable if the underlying thread exited.
Active greenlet cannot be garbage collected, however. */
if (PyGreenlet_MAIN(self) || !PyGreenlet_ACTIVE(self))
return 1;
return 0;
}
static int green_clear(PyGreenlet* self)
{
/* Greenlet is only cleared if it is about to be collected.
Since active greenlets are not garbage collectable, we can
be sure that, even if they are deallocated during clear,
nothing they reference is in unreachable or finalizers,
so even if it switches we are relatively safe. */
Py_CLEAR(self->parent);
Py_CLEAR(self->run_info);
Py_CLEAR(self->exc_type);
Py_CLEAR(self->exc_value);
Py_CLEAR(self->exc_traceback);
Py_CLEAR(self->dict);
return 0;
}
#endif
static void green_dealloc(PyGreenlet* self)
{
PyObject *error_type, *error_value, *error_traceback;
#if GREENLET_USE_GC
PyObject_GC_UnTrack((PyObject *)self);
Py_TRASHCAN_SAFE_BEGIN(self);
#endif /* GREENLET_USE_GC */
if (PyGreenlet_ACTIVE(self) && self->run_info != NULL && !PyGreenlet_MAIN(self)) {
/* Hacks hacks hacks copied from instance_dealloc() */
/* Temporarily resurrect the greenlet. */
assert(Py_REFCNT(self) == 0);
Py_REFCNT(self) = 1;
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
if (kill_greenlet(self) < 0) {
PyErr_WriteUnraisable((PyObject*) self);
/* XXX what else should we do? */
}
/* Check for no resurrection must be done while we keep
* our internal reference, otherwise PyFile_WriteObject
* causes recursion if using Py_INCREF/Py_DECREF
*/
if (Py_REFCNT(self) == 1 && PyGreenlet_ACTIVE(self)) {
/* Not resurrected, but still not dead!
XXX what else should we do? we complain. */
PyObject* f = PySys_GetObject("stderr");
Py_INCREF(self); /* leak! */
if (f != NULL) {
PyFile_WriteString("GreenletExit did not kill ",
f);
PyFile_WriteObject((PyObject*) self, f, 0);
PyFile_WriteString("\n", f);
}
}