-
Notifications
You must be signed in to change notification settings - Fork 242
/
greenlet.cpp
3245 lines (2837 loc) · 107 KB
/
greenlet.cpp
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
/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
/* Format with:
* clang-format -i --style=file src/greenlet/greenlet.c
*
*
* Fix missing braces with:
* clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
*/
#include <cstdlib>
#include <string>
#include <algorithm>
#include <exception>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h" // PyMemberDef
#include "greenlet_internal.hpp"
#include "greenlet_refs.hpp"
#include "greenlet_slp_switch.hpp"
#include "greenlet_thread_state.hpp"
#include "greenlet_thread_support.hpp"
#include "greenlet_greenlet.hpp"
using greenlet::ThreadState;
using greenlet::Mutex;
using greenlet::LockGuard;
using greenlet::LockInitError;
using greenlet::PyErrOccurred;
using greenlet::Require;
using greenlet::PyFatalError;
using greenlet::ExceptionState;
using greenlet::StackState;
using greenlet::Greenlet;
// Helpers for reference counting.
// XXX: running the test cases for greenlet 1.1.2 under Python 3.10+pydebug
// with zope.testrunner's "report refcounts" option shows a growth of
// over 500 references when running 90 tests at a steady state (10 repeats)
// Running in verbose mode and adding objgraph to report gives us this
// info in a steady state:
// Ran 90 tests with 0 failures, 0 errors and 1 skipped in 2.120 seconds.
// Showing growth
// tuple 2811 +16
// list 1733 +14
// function 6304 +11
// dict 3604 +9
// cell 707 +9
// greenlet 81 +8
// method 103 +5
// Genlet 40 +4
// list_iterator 30 +3
// getset_descriptor 916 +2
// sum detail refcount=341678 sys refcount=379357 change=523
// Leak details, changes in instances and refcounts by type/class:
// type/class insts refs
// ------------------------------------------------------- ----- ----
// builtins.NoneType 0 2
// builtins.cell 9 20
// builtins.code 0 31
// builtins.dict 18 91
// builtins.frame 20 32
// builtins.function 11 28
// builtins.getset_descriptor 2 2
// builtins.int 2 42
// builtins.list 14 37
// builtins.list_iterator 3 3
// builtins.method 5 5
// builtins.method_descriptor 0 9
// builtins.str 11 76
// builtins.traceback 1 2
// builtins.tuple 20 42
// builtins.type 2 28
// builtins.weakref 2 2
// greenlet.GreenletExit 1 1
// greenlet.greenlet 8 26
// greenlet.tests.test_contextvars.NoContextVarsTests 0 1
// greenlet.tests.test_gc.object_with_finalizer 1 1
// greenlet.tests.test_generator_nested.Genlet 4 26
// greenlet.tests.test_greenlet.convoluted 1 2
// ------------------------------------------------------- ----- ----
// total 135 509
//
// As of the commit that adds this comment, we're doing better than
// 1.1.2, but still not perfect:
// Ran 115 tests with 0 failures, 0 errors, 1 skipped in 8.623 seconds.
// tuple 21310 +23
// dict 5428 +18
// frame 183 +17
// list 1760 +14
// function 6359 +11
// cell 698 +8
// method 105 +5
// int 2709 +4
// TheGenlet 40 +4
// list_iterator 30 +3
// sum detail refcount=345051 sys refcount=383043 change=494
// Leak details, changes in instances and refcounts by type/class:
// type/class insts refs
// ------------------------------------------------------- ----- ----
// builtins.NoneType 0 12
// builtins.bool 0 2
// builtins.cell 8 16
// builtins.code 0 28
// builtins.dict 18 74
// builtins.frame 17 28
// builtins.function 11 28
// builtins.getset_descriptor 2 2
// builtins.int 4 44
// builtins.list 14 39
// builtins.list_iterator 3 3
// builtins.method 5 5
// builtins.method_descriptor 0 8
// builtins.str -2 69
// builtins.tuple 23 42
// builtins.type 2 28
// builtins.weakref 2 2
// greenlet.greenlet 1 1
// greenlet.main_greenlet 1 16
// greenlet.tests.test_contextvars.NoContextVarsTests 0 1
// greenlet.tests.test_gc.object_with_finalizer 1 1
// greenlet.tests.test_generator_nested.TheGenlet 4 29
// greenlet.tests.test_greenlet.convoluted 1 2
// greenlet.tests.test_leaks.HasFinalizerTracksInstances 2 2
// ------------------------------------------------------- ----- ----
// total 117 482
using greenlet::refs::BorrowedObject;
using greenlet::refs::BorrowedGreenlet;
using greenlet::refs::BorrowedMainGreenlet;
using greenlet::refs::OwnedObject;
using greenlet::refs::PyErrFetchParam;
using greenlet::refs::PyArgParseParam;
using greenlet::refs::ImmortalString;
using greenlet::refs::ImmortalObject;
using greenlet::refs::CreatedModule;
using greenlet::refs::PyErrPieces;
using greenlet::refs::PyObjectPointer;
using greenlet::Greenlet;
using greenlet::UserGreenlet;
using greenlet::MainGreenlet;
// ******* Implementation of things from included files
template<typename T, greenlet::refs::TypeChecker TC>
greenlet::refs::_BorrowedGreenlet<T, TC>& greenlet::refs::_BorrowedGreenlet<T, TC>::operator=(const greenlet::refs::BorrowedObject& other)
{
this->_set_raw_pointer(static_cast<PyObject*>(other));
return *this;
}
template <typename T, greenlet::refs::TypeChecker TC>
inline greenlet::refs::_BorrowedGreenlet<T, TC>::operator Greenlet*() const G_NOEXCEPT
{
if (!this->p) {
return nullptr;
}
return reinterpret_cast<PyGreenlet*>(this->p)->pimpl;
}
template<typename T, greenlet::refs::TypeChecker TC>
greenlet::refs::_BorrowedGreenlet<T, TC>::_BorrowedGreenlet(const BorrowedObject& p)
: BorrowedReference<T, TC>(nullptr)
{
this->_set_raw_pointer(p.borrow());
}
template <typename T, greenlet::refs::TypeChecker TC>
inline greenlet::refs::_OwnedGreenlet<T, TC>::operator Greenlet*() const G_NOEXCEPT
{
if (!this->p) {
return nullptr;
}
return reinterpret_cast<PyGreenlet*>(this->p)->pimpl;
}
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wmissing-field-initializers"
# pragma clang diagnostic ignored "-Wwritable-strings"
#elif defined(__GNUC__)
# pragma GCC diagnostic push
// warning: ISO C++ forbids converting a string constant to ‘char*’
// (The python APIs aren't const correct and accept writable char*)
# pragma GCC diagnostic ignored "-Wwrite-strings"
#endif
/***********************************************************
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; see
greenlet_thread_state.hpp for details.
*/
static inline OwnedObject
single_result(const OwnedObject& results)
{
if (results
&& PyTuple_Check(results.borrow())
&& PyTuple_GET_SIZE(results.borrow()) == 1) {
PyObject* result = PyTuple_GET_ITEM(results.borrow(), 0);
return OwnedObject::owning(result);
}
return results;
}
class ImmortalEventName : public ImmortalString
{
private:
G_NO_COPIES_OF_CLS(ImmortalEventName);
public:
ImmortalEventName(const char* const str) : ImmortalString(str)
{}
};
class ImmortalException : public ImmortalObject
{
private:
G_NO_COPIES_OF_CLS(ImmortalException);
public:
ImmortalException(const char* const name, PyObject* base=nullptr) :
ImmortalObject(name
// Python 2.7 isn't const correct
? Require(PyErr_NewException((char*)name, base, nullptr))
: nullptr)
{}
inline bool PyExceptionMatches() const
{
return PyErr_ExceptionMatches(this->p) > 0;
}
};
// This encapsulates what were previously module global "constants"
// established at init time.
// This is a step towards Python3 style module state that allows
// reloading.
// We play some tricks with placement new to be able to allocate this
// object statically still, so that references to its members don't
// incur an extra pointer indirection.
class GreenletGlobals
{
public:
const ImmortalEventName event_switch;
const ImmortalEventName event_throw;
const ImmortalException PyExc_GreenletError;
const ImmortalException PyExc_GreenletExit;
const ImmortalObject empty_tuple;
const ImmortalObject empty_dict;
const ImmortalString str_run;
Mutex* const thread_states_to_destroy_lock;
greenlet::cleanup_queue_t thread_states_to_destroy;
GreenletGlobals(const int UNUSED(dummy)) :
event_switch(0),
event_throw(0),
PyExc_GreenletError(0),
PyExc_GreenletExit(0),
empty_tuple(0),
empty_dict(0),
str_run(0),
thread_states_to_destroy_lock(0)
{}
GreenletGlobals() :
event_switch("switch"),
event_throw("throw"),
PyExc_GreenletError("greenlet.error"),
PyExc_GreenletExit("greenlet.GreenletExit", PyExc_BaseException),
empty_tuple(Require(PyTuple_New(0))),
empty_dict(Require(PyDict_New())),
str_run("run"),
thread_states_to_destroy_lock(new Mutex())
{}
~GreenletGlobals()
{
// This object is (currently) effectively immortal, and not
// just because of those placement new tricks; if we try to
// deallocate the static object we allocated, and overwrote,
// we would be doing so at C++ teardown time, which is after
// the final Python GIL is released, and we can't use the API
// then.
// (The members will still be destructed, but they also don't
// do any deallocation.)
}
void queue_to_destroy(ThreadState* ts) const
{
// we're currently accessed through a static const object,
// implicitly marking our members as const, so code can't just
// call push_back (or pop_back) without casting away the
// const.
//
// Do that for callers.
greenlet::cleanup_queue_t& q = const_cast<greenlet::cleanup_queue_t&>(this->thread_states_to_destroy);
q.push_back(ts);
}
ThreadState* take_next_to_destroy() const
{
greenlet::cleanup_queue_t& q = const_cast<greenlet::cleanup_queue_t&>(this->thread_states_to_destroy);
ThreadState* result = q.back();
q.pop_back();
return result;
}
};
static const GreenletGlobals mod_globs(0);
// Protected by the GIL. Incremented when we create a main greenlet,
// in a new thread, decremented when it is destroyed.
static Py_ssize_t total_main_greenlets;
struct ThreadState_DestroyWithGIL
{
ThreadState_DestroyWithGIL(ThreadState* state)
{
if (state && state->has_main_greenlet()) {
DestroyWithGIL(state);
}
}
static int
DestroyWithGIL(ThreadState* state)
{
// Holding the GIL.
// Passed a non-shared pointer to the actual thread state.
// state -> main greenlet
assert(state->has_main_greenlet());
PyGreenlet* main(state->borrow_main_greenlet());
// When we need to do cross-thread operations, we check this.
// A NULL value means the thread died some time ago.
// We do this here, rather than in a Python dealloc function
// for the greenlet, in case there's still a reference out
// there.
static_cast<MainGreenlet*>(main->pimpl)->thread_state(nullptr);
delete state; // Deleting this runs the destructor, DECREFs the main greenlet.
return 0;
}
};
#if (PY_VERSION_HEX >= 0x30800A0 && PY_VERSION_HEX < 0x3090000) && !(defined(_WIN32) || defined(WIN32))
// XXX: From Python 3.8a3 [1] up until Python 3.9a6 [2][3],
// ``Py_AddPendingCall`` would try to produce a Python exception if
// the interpreter was in the beginning of shutting down when this
// function is called. However, ``Py_AddPendingCall`` doesn't require
// the GIL, and we are absolutely not holding it when we make that
// call. That means that trying to create the Python exception is
// using the C API in an undefined state; here the C API detects this
// and aborts the process with an error ("Fatal Python error: Python
// memory allocator called without holding the GIL": Add ->
// PyErr_SetString -> PyUnicode_New -> PyObject_Malloc). This arises
// (obviously) in multi-threaded programs and happens if one thread is
// exiting and cleaning up its thread-local data while the other
// thread is trying to shut down the interpreter. A crash on shutdown
// is still a crash and could result in data loss (e.g., daemon
// threads are still running, pending signal handlers may be present,
// buffers may not be flushed, there may be __del__ that need run,
// etc), so we have to work around it.
//
// Of course, we can (and do) check for whether the interpreter is
// shutting down before calling ``Py_AddPendingCall``, but that's a
// race condition since we don't hold the GIL, and so we may not
// actually get the right answer. Plus, ``Py_FinalizeEx`` actually
// calls ``_Py_FinishPendingCalls`` (which sets the pending->finishing
// flag, which is used to gate creating the exceptioen) *before*
// publishing any other data that would let us detect the shutdown
// (such as runtime->finalizing). So that point is moot.
//
// Our solution for those versions is to inline the same code, without
// the problematic bit that sets the exception. Unfortunately, all of
// the structure definitions are private/opaque, *and* we can't
// actually count on being able to include their definitions from
// ``internal/pycore_*``, because on some platforms those header files
// are incomplete (i.e., on macOS with macports 3.8, the includes are
// fine, but on Ubuntu jammy with 3.8 from ppa:deadsnakes or GitHub
// Actions 3.8 (I think it's Ubuntu 18.04), they con't be used; at
// least, I couldn't get them to work). So we need to define the
// structures and _PyRuntime data member ourself. Yet more
// unfortunately, _PyRuntime won't link on Windows, so we can only do
// this on other platforms.
//
// [1] https://github.com/python/cpython/commit/842a2f07f2f08a935ef470bfdaeef40f87490cfc
// [2] https://github.com/python/cpython/commit/cfc3c2f8b34d3864717ab584c5b6c260014ba55a
// [3] https://github.com/python/cpython/issues/81308
# define GREENLET_BROKEN_PY_ADD_PENDING 1
// When defining these structures, the important thing is to get
// binary compatibility, i.e., structure layout. For that, we only
// need to define fields up to the ones we use; after that they're
// irrelevant UNLESS the structure is included in another structure
// *before* the structure we're interested in --- in that case, it
// must be complete. Ellipsis indicate elided trailing members.
// Pointer types are changed to void* to keep from having to define
// more structures.
// From "internal/pycore_atomic.h"
// There are several different definitions of this, including the
// plain ``int`` version, a ``volatile int`` and an ``_Atomic int``
// I don't think any of those change the size/layout.
typedef struct _Py_atomic_int {
volatile int _value;
} _Py_atomic_int;
// This needs too much infrastructure, so we just do a regular store.
#define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \
(ATOMIC_VAL)->_value = NEW_VAL
// From "internal/pycore_pymem.h"
#define NUM_GENERATIONS 3
struct gc_generation {
PyGC_Head head; // We already have this defined.
int threshold;
int count;
};
struct gc_generation_stats {
Py_ssize_t collections;
Py_ssize_t collected;
Py_ssize_t uncollectable;
};
struct _gc_runtime_state {
void *trash_delete_later;
int trash_delete_nesting;
int enabled;
int debug;
struct gc_generation generations[NUM_GENERATIONS];
void *generation0;
struct gc_generation permanent_generation;
struct gc_generation_stats generation_stats[NUM_GENERATIONS];
int collecting;
void *garbage;
void *callbacks;
Py_ssize_t long_lived_total;
Py_ssize_t long_lived_pending;
};
// From "internal/pycore_pystate.h"
struct _pending_calls {
int finishing;
PyThread_type_lock lock;
_Py_atomic_int calls_to_do;
int async_exc;
#define NPENDINGCALLS 32
struct {
int (*func)(void *);
void *arg;
} calls[NPENDINGCALLS];
int first;
int last;
};
struct _ceval_runtime_state {
int recursion_limit;
int tracing_possible;
_Py_atomic_int eval_breaker;
_Py_atomic_int gil_drop_request;
struct _pending_calls pending;
// ...
};
typedef struct pyruntimestate {
int preinitializing;
int preinitialized;
int core_initialized;
int initialized;
void *finalizing;
struct pyinterpreters {
PyThread_type_lock mutex;
void *head;
void *main;
int64_t next_id;
} interpreters;
// XXX Remove this field once we have a tp_* slot.
struct _xidregistry {
PyThread_type_lock mutex;
void *head;
} xidregistry;
unsigned long main_thread;
#define NEXITFUNCS 32
void (*exitfuncs[NEXITFUNCS])(void);
int nexitfuncs;
struct _gc_runtime_state gc;
struct _ceval_runtime_state ceval;
// ...
} _PyRuntimeState;
#define SIGNAL_PENDING_CALLS(ceval) \
do { \
_Py_atomic_store_relaxed(&(ceval)->pending.calls_to_do, 1); \
_Py_atomic_store_relaxed(&(ceval)->eval_breaker, 1); \
} while (0)
extern _PyRuntimeState _PyRuntime;
#else
# define GREENLET_BROKEN_PY_ADD_PENDING 0
#endif
struct ThreadState_DestroyNoGIL
{
#if GREENLET_BROKEN_PY_ADD_PENDING
static int _push_pending_call(struct _pending_calls *pending,
int (*func)(void *), void *arg)
{
int i = pending->last;
int j = (i + 1) % NPENDINGCALLS;
if (j == pending->first) {
return -1; /* Queue full */
}
pending->calls[i].func = func;
pending->calls[i].arg = arg;
pending->last = j;
return 0;
}
static int AddPendingCall(int (*func)(void *), void *arg)
{
_PyRuntimeState *runtime = &_PyRuntime;
if (!runtime) {
// obviously impossible
return 0;
}
struct _pending_calls *pending = &runtime->ceval.pending;
if (!pending->lock) {
return 0;
}
int result = 0;
PyThread_acquire_lock(pending->lock, WAIT_LOCK);
if (!pending->finishing) {
result = _push_pending_call(pending, func, arg);
}
PyThread_release_lock(pending->lock);
SIGNAL_PENDING_CALLS(&runtime->ceval);
return result;
}
#else
// Python < 3.8 or >= 3.9
static int AddPendingCall(int (*func)(void*), void* arg)
{
return Py_AddPendingCall(func, arg);
}
#endif
ThreadState_DestroyNoGIL(ThreadState* state)
{
// We are *NOT* holding the GIL. Our thread is in the middle
// of its death throes and the Python thread state is already
// gone so we can't use most Python APIs. One that is safe is
// ``Py_AddPendingCall``, unless the interpreter itself has
// been torn down. There is a limited number of calls that can
// be queued: 32 (NPENDINGCALLS) in CPython 3.10, so we
// coalesce these calls using our own queue.
if (state && state->has_main_greenlet()) {
// mark the thread as dead ASAP.
// this is racy! If we try to throw or switch to a
// greenlet from this thread from some other thread before
// we clear the state pointer, it won't realize the state
// is dead which can crash the process.
PyGreenlet* p = state->borrow_main_greenlet();
assert(p->pimpl->thread_state() == state || p->pimpl->thread_state() == nullptr);
static_cast<MainGreenlet*>(p->pimpl)->thread_state(nullptr);
}
// NOTE: Because we're not holding the GIL here, some other
// Python thread could run and call ``os.fork()``, which would
// be bad if that happenend while we are holding the cleanup
// lock (it wouldn't function in the child process).
// Make a best effort to try to keep the duration we hold the
// lock short.
// TODO: On platforms that support it, use ``pthread_atfork`` to
// drop this lock.
LockGuard cleanup_lock(*mod_globs.thread_states_to_destroy_lock);
if (state && state->has_main_greenlet()) {
// Because we don't have the GIL, this is a race condition.
if (!PyInterpreterState_Head()) {
// We have to leak the thread state, if the
// interpreter has shut down when we're getting
// deallocated, we can't run the cleanup code that
// deleting it would imply.
return;
}
mod_globs.queue_to_destroy(state);
if (mod_globs.thread_states_to_destroy.size() == 1) {
// We added the first item to the queue. We need to schedule
// the cleanup.
int result = ThreadState_DestroyNoGIL::AddPendingCall(
ThreadState_DestroyNoGIL::DestroyQueueWithGIL,
NULL);
if (result < 0) {
// Hmm, what can we do here?
fprintf(stderr,
"greenlet: WARNING: failed in call to Py_AddPendingCall; "
"expect a memory leak.\n");
}
}
}
}
static int
DestroyQueueWithGIL(void* UNUSED(arg))
{
// We're holding the GIL here, so no Python code should be able to
// run to call ``os.fork()``.
while (1) {
ThreadState* to_destroy;
{
LockGuard cleanup_lock(*mod_globs.thread_states_to_destroy_lock);
if (mod_globs.thread_states_to_destroy.empty()) {
break;
}
to_destroy = mod_globs.take_next_to_destroy();
}
// Drop the lock while we do the actual deletion.
ThreadState_DestroyWithGIL::DestroyWithGIL(to_destroy);
}
return 0;
}
};
// The intent when GET_THREAD_STATE() is used multiple times in a function is to
// take a reference to it in a local variable, to avoid the
// thread-local indirection. On some platforms (macOS),
// accessing a thread-local involves a function call (plus an initial
// function call in each function that uses a thread local); in
// contrast, static volatile variables are at some pre-computed offset.
#if G_USE_STANDARD_THREADING == 1
typedef greenlet::ThreadStateCreator<ThreadState_DestroyNoGIL> ThreadStateCreator;
static G_THREAD_LOCAL_VAR ThreadStateCreator g_thread_state_global;
#define GET_THREAD_STATE() g_thread_state_global
#else
// if we're not using standard threading, we're using
// the Python thread-local dictionary to perform our cleanup,
// which means we're deallocated when holding the GIL. The
// thread state is valid enough still for us to destroy
// stuff.
typedef greenlet::ThreadStateCreator<ThreadState_DestroyWithGIL> ThreadStateCreator;
#define G_THREAD_STATE_DICT_CLEANUP_TYPE
#include "greenlet_thread_state_dict_cleanup.hpp"
typedef greenlet::refs::OwnedReference<PyGreenletCleanup> OwnedGreenletCleanup;
// RECALL: legacy thread-local objects (__thread on GCC, __declspec(thread) on
// MSVC) can't have constructors or destructors, they have to be
// constant. So we indirect through a pointer and a function.
static G_THREAD_LOCAL_VAR ThreadStateCreator* _g_thread_state_global_ptr = nullptr;
static ThreadStateCreator& GET_THREAD_STATE()
{
if (!_g_thread_state_global_ptr) {
// NOTE: If any of this fails, we'll probably go on to hard
// crash the process, because we're returning a reference to a
// null pointer. we've called Py_FatalError(), but have no way
// to communicate that to the caller. Since these should
// essentially never fail unless the entire process is borked,
// a hard crash with a decent C++ backtrace from the exception
// is much more useful.
_g_thread_state_global_ptr = new ThreadStateCreator();
if (!_g_thread_state_global_ptr) {
throw PyFatalError("greenlet: Failed to create greenlet thread state.");
}
OwnedGreenletCleanup cleanup(OwnedGreenletCleanup::consuming(PyType_GenericAlloc(&PyGreenletCleanup_Type, 0)));
if (!cleanup) {
throw PyFatalError("greenlet: Failed to create greenlet thread state cleanup.");
}
cleanup->thread_state_creator = _g_thread_state_global_ptr;
assert(PyObject_GC_IsTracked(cleanup.borrow_o()));
PyObject* ts_dict_w = PyThreadState_GetDict();
if (!ts_dict_w) {
throw PyFatalError("greenlet: Failed to get Python thread state.");
}
if (PyDict_SetItemString(ts_dict_w, "__greenlet_cleanup", cleanup.borrow_o()) < 0) {
throw PyFatalError("greenlet: Failed to save cleanup key in Python thread state.");
}
}
return *_g_thread_state_global_ptr;
}
#endif
Greenlet::Greenlet(PyGreenlet* p)
{
p ->pimpl = this;
}
Greenlet::Greenlet(PyGreenlet* p, const StackState& initial_stack)
: stack_state(initial_stack)
{
// can't use a delegating constructor because of
// MSVC for Python 2.7
p->pimpl = this;
}
UserGreenlet::UserGreenlet(PyGreenlet* p,BorrowedGreenlet the_parent)
: Greenlet(p), _parent(the_parent)
{
this->_self = p;
}
MainGreenlet::MainGreenlet(PyGreenlet* p, ThreadState* state)
: Greenlet(p, StackState::make_main()),
_self(p),
_thread_state(state)
{
total_main_greenlets++;
}
ThreadState*
MainGreenlet::thread_state() const G_NOEXCEPT
{
return this->_thread_state;
}
void
MainGreenlet::thread_state(ThreadState* t) G_NOEXCEPT
{
assert(!t);
this->_thread_state = t;
}
BorrowedGreenlet
UserGreenlet::self() const G_NOEXCEPT
{
return this->_self;
}
BorrowedGreenlet
MainGreenlet::self() const G_NOEXCEPT
{
return BorrowedGreenlet(this->_self.borrow());
}
const BorrowedMainGreenlet
UserGreenlet::main_greenlet() const
{
return this->_main_greenlet;
}
const BorrowedMainGreenlet
MainGreenlet::main_greenlet() const
{
return this->_self;
}
static PyGreenlet*
green_create_main(ThreadState* state)
{
PyGreenlet* gmain;
/* create the main greenlet for this thread */
gmain = (PyGreenlet*)PyType_GenericAlloc(&PyGreenlet_Type, 0);
if (gmain == NULL) {
Py_FatalError("green_create_main failed to alloc");
return NULL;
}
new MainGreenlet(gmain, state);
assert(Py_REFCNT(gmain) == 1);
return gmain;
}
BorrowedMainGreenlet
UserGreenlet::find_main_greenlet_in_lineage() const
{
if (this->started()) {
assert(this->_main_greenlet);
return BorrowedMainGreenlet(this->_main_greenlet);
}
if (!this->_parent) {
/* garbage collected greenlet in chain */
// XXX: WHAT?
return BorrowedMainGreenlet(nullptr);
}
return this->_parent->find_main_greenlet_in_lineage();
}
BorrowedMainGreenlet
MainGreenlet::find_main_greenlet_in_lineage() const
{
return BorrowedMainGreenlet(this->_self);
}
/***********************************************************/
/* 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
g_initialstub is a member function and declared virtual so that the
compiler always calls it through a vtable.
slp_save_state and slp_restore_state are also member functions. They
are called from trampoline functions that themselves are declared as
not eligible for inlining.
*/
/* add forward declarations */
static void
g_calltrace(const OwnedObject& tracefunc,
const ImmortalEventName& event,
const BorrowedGreenlet& origin,
const BorrowedGreenlet& target);
static OwnedObject
g_handle_exit(const OwnedObject& greenlet_result);
/**
* CAUTION: May invoke arbitrary Python code.
*
* Figure out what the result of ``greenlet.switch(arg, kwargs)``
* should be and transfers ownership of it to the left-hand-side.
*
* 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.
*/
OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) G_NOEXCEPT
{
// Because this may invoke arbitrary Python code, which could
// result in switching back to us, we need to get the
// arguments locally on the stack.
assert(rhs);
OwnedObject args = rhs.args();
OwnedObject kwargs = rhs.kwargs();
rhs.CLEAR();
// We shouldn't be called twice for the same switch.
assert(args || kwargs);
assert(!rhs);
if (!kwargs) {
lhs = args;
}
else if (!PyDict_Size(kwargs.borrow())) {
lhs = args;
}
else if (!PySequence_Length(args.borrow())) {
lhs = kwargs;
}
else {
lhs = OwnedObject::consuming(PyTuple_Pack(2, args.borrow(), kwargs.borrow()));
}
return lhs;
}
void Greenlet::release_args()
{
this->switch_args.CLEAR();
}
void* UserGreenlet::operator new(size_t UNUSED(count))
{
return allocator.allocate(1);
}
void UserGreenlet::operator delete(void* ptr)
{
return allocator.deallocate(static_cast<UserGreenlet*>(ptr),
1);
}
void* MainGreenlet::operator new(size_t UNUSED(count))
{
return allocator.allocate(1);
}
void MainGreenlet::operator delete(void* ptr)
{
return allocator.deallocate(static_cast<MainGreenlet*>(ptr),
1);
}
OwnedObject
Greenlet::throw_GreenletExit_during_dealloc(const ThreadState& UNUSED(current_thread_state))
{
// If we're killed because we lost all references in the
// middle of a switch, that's ok. Don't reset the args/kwargs,
// we still want to pass them to the parent.
PyErr_SetString(mod_globs.PyExc_GreenletExit,
"Killing the greenlet because all references have vanished.");
// To get here it had to have run before
return this->g_switch();
}
OwnedObject
UserGreenlet::throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state)
{
/* The dying greenlet cannot be a parent of ts_current
because the 'parent' field chain would hold a
reference */
UserGreenlet::ParentIsCurrentGuard with_current_parent(this, current_thread_state);
// We don't care about the return value, only whether an
// exception happened. Whether or not an exception happens,
// we need to restore the parent in case the greenlet gets
// resurrected.