forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathregions.c
More file actions
2284 lines (1960 loc) · 76.4 KB
/
regions.c
File metadata and controls
2284 lines (1960 loc) · 76.4 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 <stdint.h>
#include <stdio.h>
#include "object.h"
#include "regions.h"
#include "pycore_dict.h"
#include "pycore_interp.h"
#include "pycore_object.h"
#include "pycore_regions.h"
#include "pycore_pyerrors.h"
#include "pyerrors.h"
// This tag indicates that the `regionmetadata` object has been merged
// with another region. The `parent` pointer points to the region it was
// merged with.
//
// This tag is only used for the parent pointer in `regionmetadata`.
#define Py_METADATA_MERGE_TAG ((Py_region_ptr_t)0x2)
static inline Py_region_ptr_with_tags_t Py_TAGGED_REGION(PyObject *ob) {
return ob->ob_region;
}
#define Py_TAGGED_REGION(ob) Py_TAGGED_REGION(_PyObject_CAST(ob))
#define REGION_PRT_HAS_TAG(ptr, tag) ((ptr).value & tag)
#define REGION_PTR_SET_TAG(ptr, tag) (ptr = Py_region_ptr_with_tags((ptr).value | tag))
#define REGION_PTR_CLEAR_TAG(ptr, tag) (ptr = Py_region_ptr_with_tags((ptr).value & (~tag)))
#define REGION_DATA_CAST(r) (_Py_CAST(regionmetadata*, (r)))
#define REGION_PTR_CAST(r) (_Py_CAST(Py_region_ptr_t, (r)))
#define Py_REGION_DATA(ob) (REGION_DATA_CAST(Py_REGION(ob)))
#define Py_REGION_FIELD(ob) (ob->ob_region)
#define IS_IMMUTABLE_REGION(r) (REGION_PTR_CAST(r) == _Py_IMMUTABLE)
#define IS_LOCAL_REGION(r) (REGION_PTR_CAST(r) == _Py_LOCAL_REGION)
#define IS_COWN_REGION(r) (REGION_PTR_CAST(r) == _Py_COWN)
#define HAS_METADATA(r) (!IS_LOCAL_REGION(r) && !IS_IMMUTABLE_REGION(r) && !IS_COWN_REGION(r))
typedef struct regionmetadata regionmetadata;
typedef struct PyRegionObject PyRegionObject;
static regionmetadata* regionmetadata_get_parent(regionmetadata* self);
static PyObject *PyRegion_add_object(PyRegionObject *self, PyObject *args);
static PyObject *PyRegion_remove_object(PyRegionObject *self, PyObject *args);
static const char *get_region_name(PyObject* obj);
static void _PyErr_Region(PyObject *src, PyObject *tgt, const char *msg);
/**
* Global status for performing the region check.
*/
bool invariant_do_region_check = false;
/**
* TODO: revisit the definition of this builting function
*/
int Py_is_invariant_enabled(void) {
return invariant_do_region_check;
}
// The src object for an edge that invalidated the invariant.
PyObject* invariant_error_src = Py_None;
// The tgt object for an edge that invalidated the invariant.
PyObject* invariant_error_tgt = Py_None;
// Once an error has occurred this is used to surpress further checking
bool invariant_error_occurred = false;
// This uses the given arguments to create and throw a `RegionError`
static void throw_region_error(
PyObject* src, PyObject* tgt,
const char *format_str, PyObject *obj)
{
// Don't stomp existing exception
PyThreadState *tstate = _PyThreadState_GET();
assert(tstate && "_PyThreadState_GET documentation says it's not safe, when?");
if (_PyErr_Occurred(tstate)) {
return;
}
// This disables the invariance check, as it could otherwise emit a runtime
// error before the emitted `RegionError` could be handled.
invariant_do_region_check = false;
invariant_error_occurred = true;
// Create the error, this sets the error value in `tstate`
PyErr_Format(PyExc_RegionError, format_str, obj);
// Set source and target fields
PyRegionErrorObject* exc = _Py_CAST(PyRegionErrorObject*,
PyErr_GetRaisedException());
Py_XINCREF(src);
exc->source = src;
Py_XINCREF(tgt);
exc->target = tgt;
PyErr_SetRaisedException(_PyObject_CAST(exc));
}
#define throw_region_error(src, tgt, format_str, format_arg) \
throw_region_error(_PyObject_CAST(src), _PyObject_CAST(tgt), \
format_str, format_arg)
struct PyRegionObject {
PyObject_HEAD
regionmetadata* metadata;
PyObject *dict;
};
struct regionmetadata {
// The number of references coming in from the local region.
Py_ssize_t lrc;
// The number of open subregions.
Py_ssize_t osc;
// The number of references to this object
Py_ssize_t rc;
bool is_open;
// Indicates if the LRC value can be trusted or not.
//
// FIXME: Only a single bit is needed, this can be integrated into another field
bool is_dirty;
// This field might either point to the parent region or another region
// that this one was merged into. The `Py_METADATA_MERGE_TAG` tag is used
// to indicate this points to a merged region.
Py_region_ptr_with_tags_t parent;
// A weak reference to the bridge object. The bridge object has increased the
// rc of this metadata object. If this was a strong reference it could create
// a cycle.
PyRegionObject* bridge;
PyObject *name; // Optional string field for "name"
// TODO: Currently only used for invariant checking. If it's not used for other things
// it might make sense to make this conditional in debug builds (or something)
//
// Intrinsic list for invariant checking
regionmetadata* next;
PyObject* cown; // To be able to release a cown; to be integrated with parent
};
static Py_region_ptr_t regionmetadata_get_merge_tree_root(Py_region_ptr_t self)
{
// Test for local and immutable region
if (!HAS_METADATA(self)) {
return self;
}
// Return self if it wasn't merged with another region
regionmetadata* self_data = REGION_DATA_CAST(self);
if (!REGION_PRT_HAS_TAG(self_data->parent, Py_METADATA_MERGE_TAG)) {
return self;
}
// FIXME: It can happen that there are several layers in this union-find
// structure. It would be efficient to directly update the parent pointers
// for deeper nodes.
return regionmetadata_get_merge_tree_root(Py_region_ptr(self_data->parent));
}
#define regionmetadata_get_merge_tree_root(self) \
regionmetadata_get_merge_tree_root(REGION_PTR_CAST(self))
static void regionmetadata_mark_as_dirty(Py_region_ptr_t self_ptr) {
if (!HAS_METADATA(self_ptr)) {
return;
}
REGION_DATA_CAST(self_ptr)->is_dirty = true;
}
# define regionmetadata_mark_as_dirty(data) \
(regionmetadata_mark_as_dirty(REGION_PTR_CAST(data)))
static void regionmetadata_mark_as_not_dirty(Py_region_ptr_t self_ptr) {
if (!HAS_METADATA(self_ptr)) {
return;
}
REGION_DATA_CAST(self_ptr)->is_dirty = false;
}
# define regionmetadata_mark_as_not_dirty(data) \
(regionmetadata_mark_as_not_dirty(REGION_PTR_CAST(data)))
static bool regionmetadata_is_dirty(Py_region_ptr_t self_ptr) {
if (!HAS_METADATA(self_ptr)) {
return false;
}
return REGION_DATA_CAST(self_ptr)->is_dirty;
}
# define regionmetadata_is_dirty(data) \
(regionmetadata_is_dirty(REGION_PTR_CAST(data)))
static void regionmetadata_inc_osc(Py_region_ptr_t self_ptr);
static int regionmetadata_dec_osc(Py_region_ptr_t self_ptr);
static void regionmetadata_open(regionmetadata* self) {
assert(HAS_METADATA(self));
if (self->is_open) {
return;
}
self->is_open = true;
regionmetadata_inc_osc(REGION_PTR_CAST(regionmetadata_get_parent(self)));
}
/// This function marks the region as closed and propagartes the status to
/// the parent region or owning cown.
///
/// It returns `0` if the close was successful. It should only fails, if the
/// system is in an inconsistent state and this close attempted to release a
/// cown which is currently not owned by the current thread.
static int regionmetadata_close(regionmetadata* self) {
// The LRC might be 1 or 2, if the owning references is a local and the
// bridge object was used as an argument.
assert(self->lrc <= 2 && "Attempting to close a region with an LRC > 2");
assert(self->osc == 0 && "Attempting to close a region with an OSC != 0");
if (!self->is_open) {
return 0;
}
self->is_open = false;
Py_region_ptr_t parent = REGION_PTR_CAST(regionmetadata_get_parent(self));
if (HAS_METADATA(parent)) {
// Cowns and parents are mutually exclusive this can therefore return directly
return regionmetadata_dec_osc(parent);
}
// Check if in a cown which is waiting for the region to close -- if so, release cown
if (self->cown && _PyCown_is_pending_release(self->cown)) {
// Propagate error from release
return _PyCown_release(self->cown);
}
// Everything is a-okay
return 0;
}
static bool regionmetadata_is_open(Py_region_ptr_t self) {
if (!HAS_METADATA(self)) {
// The immutable and local region are open by default and can't be closed.
return true;
}
return REGION_DATA_CAST(self)->is_open;
}
#define regionmetadata_is_open(self) \
regionmetadata_is_open(REGION_PTR_CAST(self))
static void regionmetadata_inc_osc(Py_region_ptr_t self_ptr)
{
if (!HAS_METADATA(self_ptr)) {
return;
}
regionmetadata* self = REGION_DATA_CAST(self_ptr);
self->osc += 1;
regionmetadata_open(self);
}
#define regionmetadata_inc_osc(self) \
(regionmetadata_inc_osc(REGION_PTR_CAST(self)))
/// Decrements the OSC of the region. This might close the region if the LRC
/// and ORC both hit zero and the region is not marked as dirty.
///
/// Returns `0` on success. An error might come from closing the region
/// see `regionmetadata_close` for potential errors.
static int regionmetadata_dec_osc(Py_region_ptr_t self_ptr)
{
if (!HAS_METADATA(self_ptr)) {
return 0;
}
regionmetadata* self = REGION_DATA_CAST(self_ptr);
self->osc -= 1;
// Check if the OSC decrease has closed this region as well.
if (self->osc == 0 && self->lrc == 0 && !regionmetadata_is_dirty(self)) {
return regionmetadata_close(self);
}
return 0;
}
#define regionmetadata_dec_osc(self) \
(regionmetadata_dec_osc(REGION_PTR_CAST(self)))
static void regionmetadata_inc_rc(Py_region_ptr_t self)
{
if (HAS_METADATA(self)) {
REGION_DATA_CAST(self)->rc += 1;
}
}
#define regionmetadata_inc_rc(self) \
(regionmetadata_inc_rc(REGION_PTR_CAST(self)))
static int regionmetadata_dec_rc(Py_region_ptr_t self_ptr)
{
if (!HAS_METADATA(self_ptr)) {
return 0;
}
// Update RC
regionmetadata* self = REGION_DATA_CAST(self_ptr);
self->rc -= 1;
if (self->rc != 0) {
return 0;
}
// Sort out the funeral by informing everyone about the future freeing
Py_CLEAR(self->name);
// Buffer the results since we don't want to leak any memory if this fails.
// OSC decreases in this function should also be safe.
int result = 0;
if (regionmetadata_is_open(self)) {
result |= regionmetadata_dec_osc(regionmetadata_get_parent(self));
}
// This access the parent directly to update the rc.
// It also doesn't matter if the parent pointer is a
// merge or subregion relation, since both cases have
// increased the rc.
result |= regionmetadata_dec_rc(Py_region_ptr(self->parent));
free(self);
return result;
}
#define regionmetadata_dec_rc(self) \
(regionmetadata_dec_rc(REGION_PTR_CAST(self)))
static void regionmetadata_set_parent(regionmetadata* self, regionmetadata* parent) {
// Just a sanity check, since these cases should never happen
assert(HAS_METADATA(self) && "Can't set the parent on the immutable and local region");
assert(REGION_PTR_CAST(self) == regionmetadata_get_merge_tree_root(self) && "Sanity Check");
assert(REGION_PTR_CAST(parent) == regionmetadata_get_merge_tree_root(parent) && "Sanity Check");
Py_region_ptr_t old_parent = Py_region_ptr(self->parent);
Py_region_ptr_t new_parent = REGION_PTR_CAST(parent);
self->parent = Py_region_ptr_with_tags(new_parent);
// Update RCs
regionmetadata_inc_rc(new_parent);
if (regionmetadata_is_open(self)) {
regionmetadata_inc_osc(new_parent);
regionmetadata_dec_osc(old_parent);
}
regionmetadata_dec_rc(old_parent);
}
static regionmetadata* regionmetadata_get_parent(regionmetadata* self) {
assert(REGION_PTR_CAST(self) == regionmetadata_get_merge_tree_root(self) && "Sanity check");
if (!HAS_METADATA(self)) {
// The local and immutable regions never have a parent
return NULL;
}
Py_region_ptr_t parent_field = Py_region_ptr(self->parent);
Py_region_ptr_t parent_root = regionmetadata_get_merge_tree_root(parent_field);
// If the parent was merged with another region we want to update the
// pointer to point at the root.
if (parent_field != parent_root) {
// set_parent ensures that the RC's are correctly updated
regionmetadata_set_parent(self, REGION_DATA_CAST(parent_root));
}
return REGION_DATA_CAST(parent_root);
}
#define regionmetadata_get_parent(self) \
regionmetadata_get_parent(REGION_DATA_CAST(self))
static bool regionmetadata_has_parent(regionmetadata* self) {
return regionmetadata_get_parent(self) != NULL;
}
static bool regionmetadata_has_ancestor(regionmetadata* self, regionmetadata* other) {
// The immutable or local region can never be a parent
if (!HAS_METADATA(other)) {
return false;
}
while (self) {
if (self == other) {
return true;
}
self = regionmetadata_get_parent(self);
}
return false;
}
// This implementation merges `self` into `other`. Merging is not allowed
// to break external uniqueness. It's therefore not allowed if both regions
// to have a parent. Except cases, where one region has the other region as
// it's parent.
//
// This function expects `self` to be a valid object.
static PyObject* regionmetadata_merge(regionmetadata* self, Py_region_ptr_t other) {
assert(HAS_METADATA(self) && "The immutable and local region can't be merged into another region");
assert(REGION_PTR_CAST(self) == regionmetadata_get_merge_tree_root(self) && "Sanity Check");
// If `other` is the parent of `self` we can merge it. We unset the the
// parent which will also update the rc and other counts.
regionmetadata* self_parent = regionmetadata_get_parent(self);
if (self_parent && REGION_PTR_CAST(self_parent) == other) {
assert(HAS_METADATA(self_parent) && "The immutable and local region can never have children");
regionmetadata_set_parent(self, NULL);
self_parent = NULL;
}
// If only `self` has a parent we can make `other` the child and
// remove the parent from `self`. The merged region will then again
// have the correct parent.
regionmetadata* other_parent = regionmetadata_get_parent(self);
if (self_parent && HAS_METADATA(other) && other_parent == NULL) {
// Make sure we don't create any cycles
if (regionmetadata_has_ancestor(self_parent, REGION_DATA_CAST(other))) {
throw_region_error(self->bridge, REGION_DATA_CAST(other)->bridge,
"Merging these regions would create a cycle", NULL);
return NULL;
}
regionmetadata_set_parent(REGION_DATA_CAST(other), self_parent);
regionmetadata_set_parent(self, NULL);
self_parent = NULL;
}
// If `self` still has a parent we can't merge it into `other`
if (self_parent != NULL) {
PyObject* other_node = NULL;
if (HAS_METADATA(other)) {
other_node = _PyObject_CAST(REGION_DATA_CAST(other)->bridge);
}
throw_region_error(self->bridge, other_node,
"Unable to merge regions", NULL);
return NULL;
}
regionmetadata_inc_rc(other);
// Merge state into the root.
if (HAS_METADATA(other)) {
regionmetadata* other_data = REGION_DATA_CAST(other);
other_data->lrc += self->lrc;
other_data->osc += self->osc;
other_data->is_open |= self->is_open;
other_data->is_dirty |= self->is_dirty;
}
// remove information from self
self->lrc = 0;
self->osc = 0;
self->is_open = false;
self->is_dirty = false;
self->parent = Py_region_ptr_with_tags(other);
REGION_PTR_SET_TAG(self->parent, Py_METADATA_MERGE_TAG);
// No decref, since this is a weak reference. Otherwise we would get
// a cycle between the `regionmetadata` as a non GC'ed object and the bridge.
self->bridge = NULL;
Py_RETURN_NONE;
}
#define regionmetadata_merge(self, other) \
(regionmetadata_merge(self, REGION_PTR_CAST(other)));
int _Py_IsLocal(PyObject *op) {
return IS_LOCAL_REGION(Py_REGION(op));
}
int _Py_IsImmutable(PyObject *op)
{
return IS_IMMUTABLE_REGION(Py_REGION(op));
}
int _Py_IsCown(PyObject *op)
{
return Py_REGION(op) == _Py_COWN;
}
Py_region_ptr_t _Py_REGION(PyObject *ob) {
if (!ob) {
return REGION_PTR_CAST(NULL);
}
Py_region_ptr_t field_value = Py_region_ptr(Py_REGION_FIELD(ob));
if (!HAS_METADATA(field_value)) {
return field_value;
}
Py_region_ptr_t region = regionmetadata_get_merge_tree_root(field_value);
// Update the region if we're not pointing to the root of the merge tree.
// This can allow freeing of non root regions and speedup future lookups.
if (region != field_value) {
// We keep the tags, since the owning region stays the same.
Py_region_ptr_t tags = Py_region_ptr(Py_REGION_FIELD(ob)) & (~Py_REGION_MASK);
_Py_SET_TAGGED_REGION(ob, Py_region_ptr_with_tags(region | tags));
}
return region;
}
void _Py_SET_TAGGED_REGION(PyObject *ob, Py_region_ptr_with_tags_t region) {
// Here we access the field directly, since we want to update the RC of the
// regions we're actually holding and not the root of the merge tree.
Py_region_ptr_t old_region = Py_region_ptr(Py_REGION_FIELD(ob));
ob->ob_region = region;
// Update the RC of the region
regionmetadata_inc_rc(Py_region_ptr(region));
regionmetadata_dec_rc(old_region);
}
/**
* Simple implementation of stack for tracing during make immutable.
* TODO: More efficient implementation
*/
typedef struct node_s {
PyObject* object;
struct node_s* next;
} node;
typedef struct stack_s {
node* head;
} stack;
static stack* stack_new(void){
stack* s = (stack*)malloc(sizeof(stack));
if(s == NULL){
return NULL;
}
s->head = NULL;
return s;
}
static bool stack_push(stack* s, PyObject* object){
node* n = (node*)malloc(sizeof(node));
if(n == NULL){
// FIXME: This DECREF should only be used by MakeImmutable, since
// `add_to_region` and other functions only use weak refs.
Py_DECREF(object);
// Should we also free the stack?
return true;
}
n->object = object;
n->next = s->head;
s->head = n;
return false;
}
static PyObject* stack_pop(stack* s){
if(s->head == NULL){
return NULL;
}
node* n = s->head;
PyObject* object = n->object;
s->head = n->next;
free(n);
return object;
}
// Returns a pointer to the top object without poping it.
static PyObject* stack_peek(stack* s){
if(s->head == NULL){
return NULL;
}
return s->head->object;
}
static void stack_free(stack* s){
while(s->head != NULL){
PyObject* op = stack_pop(s);
Py_DECREF(op);
}
free(s);
}
static bool stack_empty(stack* s){
return s->head == NULL;
}
static bool stack_contains(stack* s, PyObject* object){
node* n = s->head;
while(n != NULL){
if (n->object == object) {
return true;
}
n = n->next;
}
return false;
}
static bool is_c_wrapper(PyObject* obj){
return PyCFunction_Check(obj) || Py_IS_TYPE(obj, &_PyMethodWrapper_Type) || Py_IS_TYPE(obj, &PyWrapperDescr_Type);
}
// Start of a linked list of bridge objects used to check for external uniqueness
// Bridge objects appear in this list if they are captured
#define CAPTURED_SENTINEL ((regionmetadata*) 0xc0defefe)
regionmetadata* captured = CAPTURED_SENTINEL;
/**
* Enable the region check.
*/
void _Py_notify_regions_in_use(void)
{
// Do not re-enable, if we have detected a fault.
if (!invariant_error_occurred)
invariant_do_region_check = true;
}
PyObject* _Py_EnableInvariant(void)
{
// Disable failure as program has explicitly requested invariant to be checked again.
invariant_error_occurred = false;
// Re-enable region check
invariant_do_region_check = true;
// Reset the error state
Py_DecRef(invariant_error_src);
invariant_error_src = Py_None;
Py_DecRef(invariant_error_tgt);
invariant_error_tgt = Py_None;
return Py_None;
}
/**
* Set the global variables for a failure.
* This allows the interpreter to inspect what has failed.
*/
static void emit_invariant_error(PyObject* src, PyObject* tgt, const char* msg)
{
Py_DecRef(invariant_error_src);
Py_IncRef(src);
invariant_error_src = src;
Py_DecRef(invariant_error_tgt);
Py_IncRef(tgt);
invariant_error_tgt = tgt;
/* Don't stomp existing exception */
PyThreadState *tstate = _PyThreadState_GET();
assert(tstate && "_PyThreadState_GET documentation says it's not safe, when?");
if (_PyErr_Occurred(tstate)) {
return;
}
_PyErr_Region(src, tgt, msg);
// We have discovered a failure.
// Disable region check, until the program switches it back on.
invariant_do_region_check = false;
invariant_error_occurred = true;
}
PyObject* _Py_InvariantSrcFailure(void)
{
return Py_NewRef(invariant_error_src);
}
PyObject* _Py_InvariantTgtFailure(void)
{
return Py_NewRef(invariant_error_tgt);
}
// Lifted from gcmodule.c
typedef struct _gc_runtime_state GCState;
#define GEN_HEAD(gcstate, n) (&(gcstate)->generations[n].head)
#define GC_NEXT _PyGCHead_NEXT
#define GC_PREV _PyGCHead_PREV
#define FROM_GC(g) ((PyObject *)(((char *)(g))+sizeof(PyGC_Head)))
/* A traversal callback for _Py_CheckRegionInvariant.
- tgt is the target of the reference we are checking, and
- src(_void) is the source of the reference we are checking.
*/
static int
visit_invariant_check(PyObject *tgt, void *src_void)
{
PyObject *src = _PyObject_CAST(src_void);
Py_region_ptr_t src_region_ptr = Py_REGION(src);
Py_region_ptr_t tgt_region_ptr = Py_REGION(tgt);
// Internal references are always allowed
if (src_region_ptr == tgt_region_ptr)
return 0;
// Anything is allowed to point to immutable
if (Py_IsImmutable(tgt))
return 0;
// Borrowed references are unrestricted
if (Py_IsLocal(src))
return 0;
// References to cowns are unrestricted
if (Py_IsCown(tgt))
return 0;
// Since tgt is not immutable, src also may not be as immutable may not point to mutable
if (Py_IsImmutable(src)) {
emit_invariant_error(src, tgt, "Reference from immutable object to mutable target");
return 0;
}
// Cross-region references must be to a bridge
if (!_Py_is_bridge_object(tgt)) {
emit_invariant_error(src, tgt, "Reference from object in one region into another region");
return 0;
}
regionmetadata* src_region = REGION_DATA_CAST(src_region_ptr);
// Region objects may be stored in cowns
if (IS_COWN_REGION(src_region)) {
return 0;
}
regionmetadata* tgt_region = REGION_DATA_CAST(tgt_region_ptr);
// Check if region is already added to captured list
if (tgt_region->next != NULL) {
// Bridge object was already captured
emit_invariant_error(src, tgt, "Reference to bridge is not externally unique");
return 0;
}
// Forbid cycles in the region topology
if (regionmetadata_has_ancestor(src_region, tgt_region)) {
emit_invariant_error(src, tgt, "Regions create a cycle with subregions");
return 0;
}
// First discovery of bridge -- add to list of captured bridge objects
tgt_region->next = captured;
captured = tgt_region;
return 0;
}
static void invariant_reset_captured_list(void) {
// Reset the captured list
while (captured != CAPTURED_SENTINEL) {
regionmetadata* m = captured;
captured = m->next;
m->next = NULL;
}
}
/**
* This uses checks that the region topology is valid.
*
* It is currently implemented using the GC data. This
* means that not all objects are traversed as some objects
* are considered to not participate in cycles, and hence
* do not need to be understood for the cycle detector.
*
* This is not ideal for the region invariant, but is a good
* first approximation. We could actually walk the heap
* in a subsequent more elaborate invariant check.
*
* Returns non-zero if the invariant is violated.
*/
int _Py_CheckRegionInvariant(PyThreadState *tstate)
{
// Check if we should perform the region invariant check
if(!invariant_do_region_check || true){
return 0;
}
// Use the GC data to find all the objects, and traverse them to
// confirm all their references satisfy the region invariant.
GCState *gcstate = &tstate->interp->gc;
// There is an cyclic doubly linked list per generation of all the objects
// in that generation.
for (int i = NUM_GENERATIONS-1; i >= 0; i--) {
PyGC_Head *containers = GEN_HEAD(gcstate, i);
PyGC_Head *gc = GC_NEXT(containers);
// Walk doubly linked list of objects.
for (; gc != containers; gc = GC_NEXT(gc)) {
PyObject *op = FROM_GC(gc);
// Local can point to anything. No invariant needed
if (Py_IsLocal(op))
continue;
// Functions are complex.
// Removing from invariant initially.
// TODO provide custom traverse here.
if (PyFunction_Check(op))
continue;
// TODO the immutable code ignores c_wrappers
// review if this is correct.
if (is_c_wrapper(op))
continue;
// Use traverse proceduce to visit each field of the object.
traverseproc traverse = Py_TYPE(op)->tp_traverse;
(void) traverse(op,
(visitproc)visit_invariant_check,
op);
// Also need to visit the type of the object
// As this isn't covered by the traverse.
PyObject* type_op = PyObject_Type(op);
visit_invariant_check(type_op, op);
Py_DECREF(type_op);
// If we detected an error, stop so we don't
// write too much.
// TODO: The first error might not be the most useful.
// So might not need to build all error edges as a structure.
if (invariant_error_occurred) {
invariant_reset_captured_list();
return 1;
}
}
}
invariant_reset_captured_list();
return 0;
}
#define _Py_VISIT_FUNC_ATTR(attr, frontier) do { \
if(attr != NULL && !Py_IsImmutable(attr)){ \
Py_INCREF(attr); \
if(stack_push(frontier, attr)){ \
return PyErr_NoMemory(); \
} \
} \
} while(0)
static PyObject* make_global_immutable(PyObject* globals, PyObject* name)
{
PyObject* value = PyDict_GetItem(globals, name); // value.rc = x
_PyDict_SetKeyImmutable((PyDictObject*)globals, name);
if(!Py_IsImmutable(value)){
Py_INCREF(value);
return value;
}else{
Py_RETURN_NONE;
}
}
/**
* Special function for walking the reachable graph of a function object.
*
* This is necessary because the function object has a pointer to the global
* object, and this is problematic because freezing any function will make the
* global object immutable, which is not always the desired behaviour.
*
* This function attempts to find the globals that a function will use, and freeze
* just those, and prevent those keys from being updated in the global dictionary
* from this point onwards.
*/
static PyObject* make_function_immutable(PyObject* op, stack* frontier)
{
PyObject* builtins;
PyObject* globals;
PyObject* module;
PyObject* module_dict;
PyFunctionObject* f;
PyObject* f_ptr;
PyCodeObject* f_code;
Py_ssize_t size;
stack* f_stack;
bool check_globals = false;
_PyObject_ASSERT(op, PyFunction_Check(op));
_Py_SetImmutable(op);
f = (PyFunctionObject*)op;
// TODO find a way to use traverse to avoid having to manually walk
// the function's members
// f->func_code needs special treatment (see below)
// func_globals, func_builtins, and func_module can stay mutable, but depending on code we may need to make some keys immutable
globals = f->func_globals;
builtins = f->func_builtins;
module = PyImport_Import(f->func_module);
if(PyModule_Check(module)){
module_dict = PyModule_GetDict(module);
}else{
module_dict = NULL;
}
_Py_VISIT_FUNC_ATTR(f->func_defaults, frontier);
_Py_VISIT_FUNC_ATTR(f->func_kwdefaults, frontier);
_Py_VISIT_FUNC_ATTR(f->func_doc, frontier);
_Py_VISIT_FUNC_ATTR(f->func_name, frontier);
_Py_VISIT_FUNC_ATTR(f->func_dict, frontier);
_Py_VISIT_FUNC_ATTR(f->func_closure, frontier);
_Py_VISIT_FUNC_ATTR(f->func_annotations, frontier);
_Py_VISIT_FUNC_ATTR(f->func_typeparams, frontier);
_Py_VISIT_FUNC_ATTR(f->func_qualname, frontier);
f_stack = stack_new();
if(f_stack == NULL){
return PyErr_NoMemory();
}
f_ptr = f->func_code;
if(stack_push(f_stack, f_ptr)){
stack_free(f_stack);
return PyErr_NoMemory();
}
Py_INCREF(f_ptr); // fp.rc = x + 1
while(!stack_empty(f_stack)){
f_ptr = stack_pop(f_stack); // fp.rc = x + 1
_PyObject_ASSERT(f_ptr, PyCode_Check(f_ptr));
f_code = (PyCodeObject*)f_ptr;
size = 0;
if (f_code->co_names != NULL)
size = PySequence_Fast_GET_SIZE(f_code->co_names);
for(Py_ssize_t i = 0; i < size; i++){
PyObject* name = PySequence_Fast_GET_ITEM(f_code->co_names, i); // name.rc = x
if(PyUnicode_CompareWithASCIIString(name, "globals") == 0){
// if the code calls the globals() builtin, then any
// cellvar or const in the function could, potentially, refer to
// a global variable. As such, we need to check if the globals
// dictionary contains that key and then make it immutable
// from this point forwards.
check_globals = true;
}
if(PyDict_Contains(globals, name)){
PyObject* value = make_global_immutable(globals, name);
if(!Py_IsNone(value)){
if(stack_push(frontier, value)){
stack_free(f_stack);
// frontier freed by the caller
return PyErr_NoMemory();
}
}
}else if(PyDict_Contains(builtins, name)){
_PyDict_SetKeyImmutable((PyDictObject*)builtins, name);
PyObject* value = PyDict_GetItem(builtins, name); // value.rc = x
if(!Py_IsImmutable(value)){
_Py_SetImmutable(value);
}
}else if(PyDict_Contains(module_dict, name)){
PyObject* value = PyDict_GetItem(module_dict, name); // value.rc = x
_PyDict_SetKeyImmutable((PyDictObject*)module_dict, name);
if(!Py_IsImmutable(value)){
Py_INCREF(value); // value.rc = x + 1
if(stack_push(frontier, value)){
stack_free(f_stack);
// frontier freed by the caller
return PyErr_NoMemory();
}
}else{
}
}else{
// TODO assert that it is an instance variable
}
}
size = PySequence_Fast_GET_SIZE(f_code->co_consts);
for(Py_ssize_t i = 0; i < size; i++){
PyObject* value = PySequence_Fast_GET_ITEM(f_code->co_consts, i); // value.rc = x
if(!Py_IsImmutable(value)){
Py_INCREF(value); // value.rc = x + 1
if(PyCode_Check(value)){
_Py_SetImmutable(value);
if(stack_push(f_stack, value)){
stack_free(f_stack);
// frontier freed by the caller
return PyErr_NoMemory();
}
}else{
if(stack_push(frontier, value)){
stack_free(f_stack);
// frontier freed by the caller
return PyErr_NoMemory();
}
}
}else{
}
if(check_globals && PyUnicode_Check(value)){
PyObject* name = value;
if(PyDict_Contains(globals, name)){
value = make_global_immutable(globals, name);
if(!Py_IsNone(value)){
if(stack_push(frontier, value)){
stack_free(f_stack);
// frontier freed by the caller
return PyErr_NoMemory();
}
}