forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathimmutability.c
More file actions
2477 lines (2170 loc) · 73.8 KB
/
immutability.c
File metadata and controls
2477 lines (2170 loc) · 73.8 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
#include "Python.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include "pycore_descrobject.h"
#include "pycore_gc.h"
#include "pycore_object.h"
#include "pycore_immutability.h"
#include "pycore_interp.h"
#include "pycore_list.h"
#include "pycore_weakref.h"
// This file has many in progress aspects
//
// 1. Improve backtracking of freezing in the presence of failures.
// 2. Support GIL disabled mode properly.
// 3. Improve storage of freeze_location
// 4. Improve Mermaid output to handle re-entrancy
// 5. Add pre-freeze hook to allow custom objects to prepare for freezing.
// #define IMMUTABLE_TRACING
#ifdef IMMUTABLE_TRACING
#define debug(msg, ...) \
do { \
printf(msg __VA_OPT__(,) __VA_ARGS__); \
} while(0)
#define debug_obj(msg, obj, ...) \
do { \
PyObject* repr = PyObject_Repr(obj); \
printf(msg, PyUnicode_AsUTF8(repr), obj __VA_OPT__(,) __VA_ARGS__); \
Py_DECREF(repr); \
} while(0)
#else
#define debug(...)
#define debug_obj(...)
#endif
// #define MERMAID_TRACING
#ifdef MERMAID_TRACING
#define TRACE_MERMAID_START() \
do { \
FILE* f = fopen("freeze_trace.md", "w"); \
if (f != NULL) { \
fprintf(f, "```mermaid\n"); \
fprintf(f, "graph LR\n"); \
fclose(f); \
} \
} while(0)
#define TRACE_MERMAID_NODE(obj) \
do { \
FILE* f = fopen("freeze_trace.md", "a"); \
if (f != NULL) { \
fprintf(f, " %p[\"%s (rc=%zd) - %p\"]\n", \
(void*)obj, (PyObject*)obj->ob_type->tp_name, \
Py_REFCNT(obj), (void*)obj); \
fclose(f); \
} \
} while(0)
#define TRACE_MERMAID_EDGE(from, to) \
do { \
FILE* f = fopen("freeze_trace.md", "a"); \
if (f != NULL) { \
fprintf(f, " %p --> %p\n", (void*)from, (void*)to); \
fclose(f); \
} \
} while(0)
#define TRACE_MERMAID_END() \
do { \
FILE* f = fopen("freeze_trace.md", "a"); \
if (f != NULL) { \
fprintf(f, "```\n"); \
fclose(f); \
} \
} while(0)
#else
#define TRACE_MERMAID_START()
#define TRACE_MERMAID_NODE(obj)
#define TRACE_MERMAID_EDGE(from, to)
#define TRACE_MERMAID_END()
#endif
#if SIZEOF_VOID_P > 4
#define IMMUTABLE_FLAG_FIELD(op) (op->ob_flags)
#else
#define IMMUTABLE_FLAG_FIELD(op) (op->ob_refcnt)
#endif
// Macro that jumps to error, if the expression `x` does not succeed.
#define SUCCEEDS(x) { do { int r = (x); if (r != 0) goto error; } while (0); }
static
int init_state(struct _Py_immutability_state *state)
{
state->warned_types = _Py_hashtable_new(
_Py_hashtable_hash_ptr,
_Py_hashtable_compare_direct);
if(state->warned_types == NULL){
return -1;
}
state->shallow_immutable_types = _Py_hashtable_new(
_Py_hashtable_hash_ptr,
_Py_hashtable_compare_direct);
if(state->shallow_immutable_types == NULL){
_Py_hashtable_destroy(state->warned_types);
state->warned_types = NULL;
return -1;
}
// Register built-in shallow immutable types.
// These types produce objects that are individually immutable
// but may reference other objects (e.g. tuple elements).
PyTypeObject *shallow_types[] = {
&PyTuple_Type,
&PyFrozenSet_Type,
&PyCode_Type,
&PyRange_Type,
&PyBytes_Type,
&PyUnicode_Type,
&PyLong_Type,
&PyFloat_Type,
&PyComplex_Type,
&PyBool_Type,
&_PyNone_Type,
&PyEllipsis_Type,
&_PyNotImplemented_Type,
&PyCFunction_Type,
NULL
};
for (int i = 0; shallow_types[i] != NULL; i++) {
if (_PyImmutability_RegisterShallowImmutable(shallow_types[i])) {
return -1;
}
}
PyTypeObject *builtin_freezable_types[] = {
&PyType_Type,
&PyBaseObject_Type,
&PyFunction_Type,
&PyList_Type,
&PyDict_Type,
&PySet_Type,
&PyMemoryView_Type,
&PyByteArray_Type,
&PyGetSetDescr_Type,
&PyMemberDescr_Type,
&PyProperty_Type,
&PyWrapperDescr_Type,
&PyMethodDescr_Type,
&PyClassMethod_Type, // TODO(Immutable): mjp I added this, is it correct? Discuss with maj
&PyClassMethodDescr_Type,
&PyStaticMethod_Type,
&PyMethod_Type,
&PyCapsule_Type,
&PyCode_Type,
&PyCell_Type,
&PyFrame_Type,
&_PyWeakref_RefType,
&PyModule_Type, // TODO(Immutable): mjp I added this, is it correct? Discuss with maj
&_PyImmModule_Type,
&PyCFunction_Type,
&_PyMethodWrapper_Type,
NULL
};
for (int i = 0; builtin_freezable_types[i] != NULL; i++) {
if (_PyImmutability_SetFreezable((PyObject*)builtin_freezable_types[i], _Py_FREEZABLE_YES)) {
return -1;
}
}
if (_PyImmutability_SetFreezable((PyObject*)&PyModule_Type, _Py_FREEZABLE_PROXY)) {
return -1;
}
return 0;
}
static struct _Py_immutability_state* get_immutable_state(void)
{
PyInterpreterState* interp = PyInterpreterState_Get();
struct _Py_immutability_state *state = &interp->immutability;
if(state->shallow_immutable_types == NULL){
if(init_state(state) == -1){
PyErr_SetString(PyExc_RuntimeError, "Failed to initialize immutability state");
return NULL;
}
}
return state;
}
static int push(PyObject* s, PyObject* item){
if(item == NULL){
return 0;
}
if(!PyList_Check(s)){
PyErr_SetString(PyExc_TypeError, "Expected a list");
return -1;
}
// Don't incref here, so that the algorithm doesn't have to account for the additional counts
// from the dfs and pending.
return _PyList_AppendTakeRef(_PyList_CAST(s), item);
}
// Returns a borrowed reference to the last item in the list.
static PyObject* peek(PyObject* s){
PyObject* item;
Py_ssize_t size = PyList_Size(s);
if(size == 0){
return NULL;
}
item = PyList_GetItem(s, size - 1);
if(item == NULL){
return NULL;
}
return item;
}
// Depend on internal list pop implementation to avoid
// unnecessary refcount operations.
static PyObject* pop(PyObject* s){
PyObject* item;
Py_ssize_t size = PyList_Size(s);
if(size == 0){
return NULL;
}
// The push doesn't incref, so can avoid the extra
// incref/decref here by using the internal pop.
item = _Py_ListPop((PyListObject *)s, size - 1);
if(item == NULL){
PyErr_SetString(PyExc_RuntimeError, "Internal error: Failed to pop from list");
return NULL;
}
return item;
}
// Artifact[Implementation]: Explanation how a stack is used to implement the DFS based SCC algorithm
/**
* The DFS walk for SCC calculations needs to perform actions on both
* the pre-order and post-order visits to an object. To achieve this
* with a single stack we use a marker object (PostOrderMarker) to
* indicate that the object being popped is a post-order visit.
*
* Effectively we do
* obj = pop()
* if obj is PostOrderMarker:
* obj = pop()
* post_order_action(obj)
* else:
* push(obj)
* push(PostOrderMarker)
* pre_order_action(obj)
*
* In pre_order_action, the children of obj can be pushed onto the stack,
* and once all that work is completed, then the PostOrderMarker will pop out
* and the post_order_action can be performed.
*
* Using a separate object means it cannot conflict with anything
* in the actual python object graph.
*/
PyObject PostOrderMarkerStruct = _PyObject_HEAD_INIT(&_PyNone_Type);
static PyObject* PostOrderMarker = &PostOrderMarkerStruct;
/**
* `tp_traverse` and `tp_reachable` **should** visit their types but
* this is sometimes forgotten. To deal with this inconsistency we
* push the type on to the stack and use this marker to indicate that
* the type should only be visited if it is not marked as pending when
* the marker is reached again. We can then manually visit the type
* and print a warning.
*
* If the type is part of an SCC we may end up with a higher SCC-RC
* since this can only account for one internal edge. But this will
* just cause a memory leak instead of crashing.
*/
PyObject EnsureVisitedMarkerStruct = _PyObject_HEAD_INIT(&_PyNone_Type);
static PyObject* EnsureVisitedMarker = &EnsureVisitedMarkerStruct;
static bool is_c_wrapper(PyObject* obj){
return PyCFunction_Check(obj) || Py_IS_TYPE(obj, &_PyMethodWrapper_Type) || Py_IS_TYPE(obj, &PyWrapperDescr_Type);
}
// Artifact[Implementation]: The state used to track a single freeze call and construct SCCs
/**
* Used to track the state of an in progress freeze operation.
*
* TODO(Immutable): This representation could mostly be done in the
* GC header for the GIL enabled build. Doing it externally works for
* both builds, and we can optimize later.
**/
struct FreezeState {
#ifndef GIL_DISABLED
// Used to track traversal order
PyObject *dfs;
// Used to track SCC to handle cycles during traversal
PyObject *pending;
#endif
// Used to track visited nodes that don't have inline GC state.
// This is required to be able to backtrack a failed freeze.
// It is also used to track nodes in GIL_DISABLED builds.
_Py_hashtable_t *visited;
// The objects that freeze() was called directly on.
_Py_hashtable_t *roots;
// Intrusive linked list of completed SCC representatives
// (threaded through _gc_prev / scc_parent), for rollback on error.
// NULL-terminated; NULL means empty.
PyObject *completed_sccs;
// A pointer to enclosing freeze states taken from the
// interpreter local immutable state
struct FreezeState *enclosing;
bool restart;
#ifdef Py_DEBUG
// For debugging, track the stack trace of the freeze operation.
PyObject* freeze_location;
#endif
#ifdef MERMAID_TRACING
PyObject* start;
#endif
};
// Wrapper around tp_traverse that also visits the type object.
// tp_traverse does not visit the type for non-heap types, but
// tp_reachable should visit all reachable objects including the type.
static int
traverse_via_tp_traverse(PyObject *obj, visitproc visit, void *freeze_state_untyped)
{
PyTypeObject *tp = Py_TYPE(obj);
// `tp_traverse` of heap types *should* include a
// `Py_VISIT(Py_TYPE(self));` since around Python 2.7 but
// there are still plenty of types that don't. LLMs currently
// also don't do this consistently. So, instead of visiting the
// type directly we throw it on to the DFS stack to check the
// correct behavior on back traversal.
//
// Only push the type if it's still mutable and not pending
if (!_Py_IsImmutable(tp)) {
struct FreezeState* freeze_state = (struct FreezeState *)freeze_state_untyped;
SUCCEEDS(push(freeze_state->dfs, _PyObject_CAST(tp)));
SUCCEEDS(push(freeze_state->dfs, EnsureVisitedMarker));
}
traverseproc traverse = tp->tp_traverse;
if (traverse != NULL) {
int err = traverse(obj, visit, freeze_state_untyped);
if (err) {
return err;
}
}
// Manually visit the type if it's a static type
if (!(tp->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
return visit((PyObject *)Py_TYPE(obj), freeze_state_untyped);
}
return 0;
error:
return -1;
}
// Returns the appropriate traversal function for reaching all references
// from an object. Prefers tp_reachable, falls back to tp_traverse wrapped
// to also visit the type. Emits a warning once per type on fallback.
static traverseproc
get_reachable_proc(PyTypeObject *tp)
{
if (tp->tp_reachable != NULL) {
return tp->tp_reachable;
}
struct _Py_immutability_state *imm_state = get_immutable_state();
if (imm_state != NULL &&
_Py_hashtable_get(imm_state->warned_types, (void *)tp) == NULL)
{
_Py_hashtable_set(imm_state->warned_types, (void *)tp, (void *)1);
if (tp->tp_traverse != NULL) {
PySys_FormatStderr(
"freeze: type '%.100s' has tp_traverse but no tp_reachable\n",
tp->tp_name);
} else {
PySys_FormatStderr(
"freeze: type '%.100s' has no tp_traverse and no tp_reachable\n",
tp->tp_name);
}
}
// Always return the wrapper; even when tp_traverse is NULL, the wrapper
// will still visit the type object which tp_reachable is expected to do.
return traverse_via_tp_traverse;
}
#ifdef GIL_DISABLED
static inline void _Py_SetImmutable(PyObject *op)
{
if(op) {
IMMUTABLE_FLAG_FIELD(op) |= _Py_IMMUTABLE_FLAG;
}
}
#endif
#define REPRESENTATIVE_FLAG 1
#define COMPLETE_FLAG 2
#define REFCOUNT_SHIFT 2
/*
In GIL builds we use the _gc_prev and _gc_next fields to store SCC information:
- The _gc_prev field stores either the rank of the SCC (if the SCC is a
representative), or a pointer to the parent representative (if not).
The Collecting bit on the prev field is used to distinguish between the two.
We cannot use the finalizer flag as that needs to be preserved.
We could have a situation where an object is frozen after having a finalizer
run on it, and we do not want to run the finalizer again.
- The _gc_next field stores the next object in the cyclic list of objects
in the SCC.
*/
#define SCC_RANK_FLAG _PyGC_PREV_MASK_COLLECTING
static int
is_root(struct FreezeState *state, PyObject *obj)
{
return _Py_hashtable_get(state->roots, obj) != NULL;
}
static int init_freeze_state(struct FreezeState *state)
{
#ifndef GIL_DISABLED
state->dfs = PyList_New(0);
state->pending = PyList_New(0);
#endif
state->visited = _Py_hashtable_new(
_Py_hashtable_hash_ptr,
_Py_hashtable_compare_direct);
state->completed_sccs = NULL;
state->roots = _Py_hashtable_new(
_Py_hashtable_hash_ptr,
_Py_hashtable_compare_direct);
state->enclosing = NULL;
state->restart = false;
#ifdef Py_DEBUG
state->freeze_location = NULL;
#endif
// TODO detect failure?
return 0;
}
static void deallocate_FreezeState(struct FreezeState *state)
{
_Py_hashtable_destroy(state->visited);
_Py_hashtable_destroy(state->roots);
#ifndef GIL_DISABLED
// We can't call the destructor directly as we didn't newref the objects
// on push. This is a slow path if there are still objects in the stack,
// so there is no need to optimize it.
while(PyList_Size(state->pending) > 0){
pop(state->pending);
}
while(PyList_Size(state->dfs) > 0){
pop(state->dfs);
}
Py_DECREF(state->dfs);
Py_DECREF(state->pending);
#endif
}
static void set_direct_rc(PyObject* obj)
{
#ifndef GIL_DISABLED
IMMUTABLE_FLAG_FIELD(obj) = (IMMUTABLE_FLAG_FIELD(obj) & ~_Py_IMMUTABLE_MASK) | _Py_IMMUTABLE_DIRECT;
#else
(void)obj;
#endif
}
static void set_indirect_rc(PyObject* obj)
{
#ifndef GIL_DISABLED
IMMUTABLE_FLAG_FIELD(obj) = (IMMUTABLE_FLAG_FIELD(obj) & ~_Py_IMMUTABLE_MASK) | _Py_IMMUTABLE_INDIRECT;
#else
(void)obj;
#endif
}
static bool has_direct_rc(PyObject* obj)
{
#ifdef GIL_DISABLED
return false;
#else
return (IMMUTABLE_FLAG_FIELD(obj) & _Py_IMMUTABLE_MASK) == _Py_IMMUTABLE_DIRECT;
#endif
}
static int is_representative(PyObject* obj, struct FreezeState *state)
{
#ifdef GIL_DISABLED
void* result = _Py_hashtable_get(state->rep, obj);
return ((uintptr_t)result & REPRESENTATIVE_FLAG) != 0;
#else
return (_Py_AS_GC(obj)->_gc_prev & SCC_RANK_FLAG) != 0;
#endif
}
static void set_scc_parent(PyObject* obj, PyObject* parent)
{
PyGC_Head* gc = _Py_AS_GC(obj);
// Use GC space for the parent pointer.
assert(((uintptr_t)parent & ~_PyGC_PREV_MASK) == 0);
uintptr_t finalized_bit = gc->_gc_prev & _PyGC_PREV_MASK_FINALIZED;
gc->_gc_prev = finalized_bit | _Py_CAST(uintptr_t, parent);
}
static PyObject* scc_parent(PyObject* obj)
{
// Use GC space for the parent pointer.
assert((_Py_AS_GC(obj)->_gc_prev & SCC_RANK_FLAG) == 0);
return _Py_CAST(PyObject*, _Py_AS_GC(obj)->_gc_prev & _PyGC_PREV_MASK);
}
static void set_scc_rank(PyObject* obj, size_t rank)
{
// Use GC space for the rank.
_Py_AS_GC(obj)->_gc_prev = (rank << _PyGC_PREV_SHIFT) | SCC_RANK_FLAG;
}
static size_t scc_rank(PyObject* obj)
{
assert((_Py_AS_GC(obj)->_gc_prev & SCC_RANK_FLAG) == SCC_RANK_FLAG);
// Use GC space for the rank.
return _Py_AS_GC(obj)->_gc_prev >> _PyGC_PREV_SHIFT;
}
static void set_scc_next(PyObject* obj, PyObject* next)
{
debug(" set_scc_next %p -> %p\n", obj, next);
// Use GC space for the next pointer.
_Py_AS_GC(obj)->_gc_next = (uintptr_t)next;
}
static PyObject* scc_next(PyObject* obj)
{
// Use GC space for the next pointer.
return _Py_CAST(PyObject*, _Py_AS_GC(obj)->_gc_next);
}
static void scc_init_non_trivial(PyObject* obj)
{
// Check if this not been part of an SCC yet.
if (scc_next(obj) == NULL) {
// Set up a new SCC with a single element.
set_scc_rank(obj, 0);
set_scc_next(obj, obj);
}
}
static void return_to_gc(PyObject* op)
{
set_scc_next(op, NULL);
set_scc_parent(op, NULL);
// Use internal version as we don't satisfy all the invariants,
// as we call this on state we are tearing down in SCC reclaiming.
// PyObject_GC_Track(op);
_PyObject_GC_TRACK(op);
}
static void scc_init(PyObject* obj)
{
assert(_PyObject_IS_GC(obj));
// Let the Immutable GC take over tracking the lifetime
// of this object. This releases the space for the SCC
// algorithm.
if (_PyObject_GC_IS_TRACKED(obj)) {
_PyObject_GC_UNTRACK(obj);
}
// The GC uses the collecting flag to identify objects part of the
// current collection set. This flag remains while the finalizer
// of unreachable objects is being called.
//
// If something calls `freeze(obj)` as part of their finalizer we
// might receive an object with the flag set. This removes the flag
// to prevent future GC collections to assume this object is currently
// being collected.
_PyGC_CLEAR_COLLECTING(obj);
// Mark as pending so we can detect back edges in the traversal.
IMMUTABLE_FLAG_FIELD(obj) |= _Py_IMMUTABLE_PENDING;
set_scc_rank(obj, 0);
}
static bool scc_is_pending(PyObject* obj)
{
return (IMMUTABLE_FLAG_FIELD(obj) & _Py_IMMUTABLE_MASK) == _Py_IMMUTABLE_PENDING;
}
static PyObject* get_representative(PyObject* obj, struct FreezeState *state)
{
if (is_representative(obj, state)) {
return obj;
}
// Grandparent path compression for union find.
PyObject* grandparent = obj;
PyObject* rep = scc_parent(obj);
while (1) {
if (is_representative(rep, state)) {
break;
}
PyObject* parent = rep;
rep = scc_parent(rep);
set_scc_parent(grandparent, rep);
grandparent = parent;
}
return rep;
}
static bool
union_scc(PyObject* a, PyObject* b, struct FreezeState *state)
{
// Initialize SCC information for both objects.
// If they are already in an SCC, this is a no-op.
scc_init_non_trivial(a);
scc_init_non_trivial(b);
// TODO(Immutable): use rank and merge in correct direction.
PyObject* rep_a = get_representative(a, state);
PyObject* rep_b = get_representative(b, state);
if (rep_a == rep_b)
return false;
// Determine rank, and switch so that rep_a has higher rank.
size_t rank_a = scc_rank(rep_a);
size_t rank_b = scc_rank(rep_b);
if (rank_a < rank_b) {
PyObject* temp = rep_a;
rep_a = rep_b;
rep_b = temp;
} else if (rank_a == rank_b) {
// Increase rank of new representative.
set_scc_rank(rep_a, rank_a + 1);
}
set_scc_parent(rep_b, rep_a);
// Merge the cyclic lists.
PyObject* next_a = scc_next(rep_a);
PyObject* next_b = scc_next(rep_b);
set_scc_next(rep_a, next_b);
set_scc_next(rep_b, next_a);
return true;
}
static PyObject* get_next(PyObject* obj, struct FreezeState *freeze_state)
{
(void)freeze_state;
PyObject* next = scc_next(obj);
return next;
}
static int has_visited(struct FreezeState *state, PyObject* obj)
{
#ifdef GIL_DISABLED
return _Py_hashtable_get(state->visited, obj) != NULL;
#else
return _Py_IsImmutable(obj);
#endif
}
#ifndef GIL_DISABLED
static PyObject* scc_root(PyObject* obj)
{
assert(_Py_IsImmutable(obj));
if (has_direct_rc(obj))
return obj;
// If the object is pending, then it is still being explored,
// the final pass of the SCC algorithm will calculate the whole SCCs RC,
// apply the ref count directly so we don't accidentally delete an object
// that is still being explored.
if (scc_is_pending(obj))
return obj;
PyObject* parent = scc_parent(obj);
if (parent != NULL)
return parent;
assert(get_next(obj, NULL) == NULL);
return obj;
}
#endif
// During the freeze, we removed the reference counts associated
// with the internal edges of the SCC. This visitor detects these
// internal edges and re-adds the reference counts to the
// objects in the SCC.
static int scc_add_internal_refcount_visit(PyObject* obj, void* curr_root)
{
if (obj == NULL)
return 0;
// Ignore mutable outgoing edges.
if (!_Py_IsImmutable(obj))
return 0;
// Find the scc root.
PyObject* root = scc_root(obj);
// If it is different SCC, then we can ignore it.
if (root != curr_root)
return 0;
// Increase the reference count as we found an interior edge for the SCC.
debug_obj("Reinstate %s (%p) with rc %zu from %p\n", obj, Py_REFCNT(obj), curr_root);
obj->ob_refcnt++;
return 0;
}
struct SCCDetails {
int has_weakreferences;
int has_legacy_finalizers;
int has_finalizers;
};
static void scc_set_refcounts_to_one(PyObject* obj)
{
PyObject* n = obj;
do {
PyObject* c = n;
n = scc_next(c);
c->ob_refcnt = 1;
} while (n != obj);
}
static void scc_reset_root_refcount(PyObject* obj)
{
assert(scc_root(obj) == obj);
size_t scc_rc = _Py_REFCNT(obj) * 2;
PyObject* n = obj;
do {
PyObject* c = n;
n = scc_next(c);
scc_rc -= _Py_REFCNT(c);
} while (n != obj);
obj->ob_refcnt = scc_rc;
}
// This will restore the reference counts for the interior edges of the SCC.
// It calculates some properties of the SCC, to decide how it might be
// finalised. Adds an RC to every element in the SCC.
static void scc_add_internal_refcounts(PyObject* obj, struct SCCDetails* details)
{
assert(_Py_IsImmutable(obj));
PyObject* root = scc_root(obj);
details->has_weakreferences = 0;
details->has_legacy_finalizers = 0;
details->has_finalizers = 0;
// Add back the reference counts for the interior edges.
PyObject* n = obj;
do {
debug_obj("Unfreezing %s @ %p\n", n);
PyObject* c = n;
n = scc_next(c);
// WARNING
// CHANGES HERE NEED TO BE REFLECTED IN freeze_visit
get_reachable_proc(Py_TYPE(c))(c, (visitproc)scc_add_internal_refcount_visit, root);
if (PyWeakref_Check(c)) {
// We followed weakreferences during freeze, so need to here as well.
PyObject* wr = NULL;
PyWeakref_GetRef(c, &wr);
if (wr != NULL) {
// This will increment the reference if it is in the same SCC
// and do nothing otherwise. We are treating the weakref as
// a strong reference for the immutable state.
scc_add_internal_refcount_visit(wr, root);
Py_DECREF(wr);
}
details->has_weakreferences++;
}
if (Py_TYPE(c)->tp_del != NULL)
details->has_legacy_finalizers++;
if (Py_TYPE(c)->tp_finalize != NULL && !_PyGC_FINALIZED(c))
details->has_finalizers++;
if (_PyType_SUPPORTS_WEAKREFS(Py_TYPE(c)) &&
*_PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(c) != NULL) {
details->has_weakreferences++;
}
} while (n != obj);
}
// This takes an SCC and turns it back to mutable.
// Must be called after a call to
// scc_add_internal_refcount, so that the reference counts are correct.
static void scc_make_mutable(PyObject* obj)
{
PyObject* n = obj;
do {
PyObject* c = n;
n = scc_next(c);
_Py_CLEAR_IMMUTABLE(c);
if (PyWeakref_Check(c)) {
PyObject* wr = NULL;
PyWeakref_GetRef(c, &wr);
if (wr != NULL) {
// Turn back to weak reference. We made the weak references strong during freeze.
Py_DECREF(wr);
Py_DECREF(wr);
}
}
} while (n != obj);
}
// Returns all the objects in the SCC to the Python cycle detector.
static void scc_return_to_gc(PyObject* obj, bool decref_required)
{
PyObject* n = obj;
do {
PyObject* c = n;
n = scc_next(c);
return_to_gc(c);
debug("Returned %p rc = %zu to GC\n", c, Py_REFCNT(c));
if (decref_required) {
Py_DECREF(c);
}
} while (n != obj);
}
static void unfreeze(PyObject* obj)
{
// Repr should not be called with an exception set. This can therefore
// only print the memory address of the object
debug("Unfreezing SCC starting at %p\n", obj);
if (scc_next(obj) == NULL)
{
// Clear Immutable flags
_Py_CLEAR_IMMUTABLE(obj);
// Return to the GC.
return_to_gc(obj);
return;
}
debug("Unfreezing %p\n", obj);
// Note: We don't need the details of the SCC for a simple unfreeze.
struct SCCDetails scc_details;
scc_reset_root_refcount(obj);
scc_add_internal_refcounts(obj, &scc_details);
scc_make_mutable(obj);
scc_return_to_gc(obj, true);
}
// Copy-pasted from weakrefobject.c
static void weakref_handle_callback(PyWeakReference* ref, PyObject* callback)
{
PyObject* cbresult = PyObject_CallOneArg(callback, (PyObject*)ref);
if (cbresult == NULL) {
PyErr_FormatUnraisable("Exception ignored while "
"calling weakref callback %R", callback);
}
else {
Py_DECREF(cbresult);
}
}
// Copy-pasted from weakrefobject.c
static void weakref_insert_head(PyWeakReference* newref, PyWeakReference** list)
{
PyWeakReference* next = *list;
newref->wr_prev = NULL;
newref->wr_next = next;
if (next != NULL)
next->wr_prev = newref;
*list = newref;
}
static void weakref_remove(PyWeakReference* self, PyWeakReference** list)
{
if (*list == self) {
*list = self->wr_next;
}
if (self->wr_prev != NULL) {
self->wr_prev->wr_next = self->wr_next;
}
if (self->wr_next != NULL) {
self->wr_next->wr_prev = self->wr_prev;
}
self->wr_prev = NULL;
self->wr_next = NULL;
}
static void weakref_decref_weakrefs(PyWeakReference* head)
{
while (head != NULL) {
PyWeakReference* weakref = head;
head = weakref->wr_next;
weakref->wr_next = NULL;
weakref->wr_prev = NULL;
Py_DECREF(weakref);
}
}
typedef struct {
int32_t interpreters_remaining;
PyObject* to_dealloc;
} callback_progress;
typedef struct {
PyWeakReference* head;
callback_progress* progress;
} pending_callbacks;
/* Signal that the current interpreter handled the callbacks.
* If all interpreters have handled the callbacks, deallocate the object.
*/
static void weakref_signal_handled(callback_progress* progress)
{
int32_t old = _Py_atomic_add_int32(
&progress->interpreters_remaining, -1);
if (old == 1) {
// All callbacks handled, trigger deallocation again.
Py_INCREF(progress->to_dealloc);
Py_DECREF(progress->to_dealloc);
PyMem_Free(progress);
}
}
/* Call the pending callbacks.
* This function can be executed asynchronously using Py_AddPendingCall.
*/
static int weakref_call_callbacks(void* arg)
{
pending_callbacks* pending = (pending_callbacks*)arg;
PyWeakReference* head = pending->head;
debug("Interpreter %zd handling callbacks for dying object %p\n",
PyInterpreterState_GetID(PyInterpreterState_Get()),
pending->progress->to_dealloc);
while (head != NULL) {
PyWeakReference* weakref = head;
PyObject* callback = weakref->wr_callback;
assert(callback != NULL);
weakref->wr_callback = NULL;
weakref_handle_callback(weakref, callback);
Py_DECREF(callback);
head = weakref->wr_next;
weakref->wr_next = NULL;
weakref->wr_prev = NULL;
Py_DECREF(weakref);
}
weakref_signal_handled(pending->progress);
PyMem_Free(pending);
// Report success as per Py_AddPendingCall contract
return 0;
}
/* Schedule the callbacks on the given interpreter. */
static void weakref_schedule_callbacks(int64_t ipid, pending_callbacks* pending)
{
// FIXME(Immutable): Can the interpreter go away in the middle of scheduling?
PyInterpreterState* target_is = _PyInterpreterState_LookUpID(ipid);
if (target_is == NULL) {
// Interpreter is already gone.
goto abort;
}
// We just need to get any thread state to schedule the call.
PyThreadState* tstate_target = PyInterpreterState_ThreadHead(target_is);
if (tstate_target == NULL) {