forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrossinterp.c
More file actions
2120 lines (1875 loc) · 55.9 KB
/
crossinterp.c
File metadata and controls
2120 lines (1875 loc) · 55.9 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
/* API for managing interactions between isolated interpreters */
#include "Python.h"
#include "pycore_ceval.h" // _Py_simple_func
#include "pycore_crossinterp.h" // struct _xid
#include "pycore_initconfig.h" // _PyStatus_OK()
#include "pycore_namespace.h" //_PyNamespace_New()
#include "pycore_pyerrors.h" // _PyErr_Clear()
#include "pycore_pystate.h" // _PyInterpreterState_GET()
#include "pycore_typeobject.h" // _PyType_GetModuleName()
#include "pycore_weakref.h" // _PyWeakref_GET_REF()
/***************************/
/* cross-interpreter calls */
/***************************/
int
_Py_CallInInterpreter(PyInterpreterState *interp,
_Py_simple_func func, void *arg)
{
if (interp == _PyThreadState_GetCurrent()->interp) {
return func(arg);
}
// XXX Emit a warning if this fails?
_PyEval_AddPendingCall(interp, (_Py_pending_call_func)func, arg, 0);
return 0;
}
int
_Py_CallInInterpreterAndRawFree(PyInterpreterState *interp,
_Py_simple_func func, void *arg)
{
if (interp == _PyThreadState_GetCurrent()->interp) {
int res = func(arg);
PyMem_RawFree(arg);
return res;
}
// XXX Emit a warning if this fails?
_PyEval_AddPendingCall(interp, func, arg, _Py_PENDING_RAWFREE);
return 0;
}
/**************************/
/* cross-interpreter data */
/**************************/
_PyCrossInterpreterData *
_PyCrossInterpreterData_New(void)
{
_PyCrossInterpreterData *xid = PyMem_RawMalloc(
sizeof(_PyCrossInterpreterData));
if (xid == NULL) {
PyErr_NoMemory();
}
return xid;
}
void
_PyCrossInterpreterData_Free(_PyCrossInterpreterData *xid)
{
PyInterpreterState *interp = PyInterpreterState_Get();
_PyCrossInterpreterData_Clear(interp, xid);
PyMem_RawFree(xid);
}
/* exceptions */
static PyStatus
_init_not_shareable_error_type(PyInterpreterState *interp)
{
const char *name = "_interpreters.NotShareableError";
PyObject *base = PyExc_ValueError;
PyObject *ns = NULL;
PyObject *exctype = PyErr_NewException(name, base, ns);
if (exctype == NULL) {
PyErr_Clear();
return _PyStatus_ERR("could not initialize NotShareableError");
}
interp->xi.PyExc_NotShareableError = exctype;
return _PyStatus_OK();
}
static void
_fini_not_shareable_error_type(PyInterpreterState *interp)
{
Py_CLEAR(interp->xi.PyExc_NotShareableError);
}
static PyObject *
_get_not_shareable_error_type(PyInterpreterState *interp)
{
assert(interp->xi.PyExc_NotShareableError != NULL);
return interp->xi.PyExc_NotShareableError;
}
/* defining cross-interpreter data */
static inline void
_xidata_init(_PyCrossInterpreterData *data)
{
// If the value is being reused
// then _xidata_clear() should have been called already.
assert(data->data == NULL);
assert(data->obj == NULL);
*data = (_PyCrossInterpreterData){0};
data->interpid = -1;
}
static inline void
_xidata_clear(_PyCrossInterpreterData *data)
{
// _PyCrossInterpreterData only has two members that need to be
// cleaned up, if set: "data" must be freed and "obj" must be decref'ed.
// In both cases the original (owning) interpreter must be used,
// which is the caller's responsibility to ensure.
if (data->data != NULL) {
if (data->free != NULL) {
data->free(data->data);
}
data->data = NULL;
}
Py_CLEAR(data->obj);
}
void
_PyCrossInterpreterData_Init(_PyCrossInterpreterData *data,
PyInterpreterState *interp,
void *shared, PyObject *obj,
xid_newobjectfunc new_object)
{
assert(data != NULL);
assert(new_object != NULL);
_xidata_init(data);
data->data = shared;
if (obj != NULL) {
assert(interp != NULL);
// released in _PyCrossInterpreterData_Clear()
data->obj = Py_NewRef(obj);
}
// Ideally every object would know its owning interpreter.
// Until then, we have to rely on the caller to identify it
// (but we don't need it in all cases).
data->interpid = (interp != NULL) ? interp->id : -1;
data->new_object = new_object;
}
int
_PyCrossInterpreterData_InitWithSize(_PyCrossInterpreterData *data,
PyInterpreterState *interp,
const size_t size, PyObject *obj,
xid_newobjectfunc new_object)
{
assert(size > 0);
// For now we always free the shared data in the same interpreter
// where it was allocated, so the interpreter is required.
assert(interp != NULL);
_PyCrossInterpreterData_Init(data, interp, NULL, obj, new_object);
data->data = PyMem_RawMalloc(size);
if (data->data == NULL) {
return -1;
}
data->free = PyMem_RawFree;
return 0;
}
void
_PyCrossInterpreterData_Clear(PyInterpreterState *interp,
_PyCrossInterpreterData *data)
{
assert(data != NULL);
// This must be called in the owning interpreter.
assert(interp == NULL
|| data->interpid == -1
|| data->interpid == interp->id);
_xidata_clear(data);
}
/* using cross-interpreter data */
static int
_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
{
// data->data can be anything, including NULL, so we don't check it.
// data->obj may be NULL, so we don't check it.
if (data->interpid < 0) {
_PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
return -1;
}
if (data->new_object == NULL) {
_PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
return -1;
}
// data->free may be NULL, so we don't check it.
return 0;
}
static crossinterpdatafunc _lookup_getdata_from_registry(
PyInterpreterState *, PyObject *);
static crossinterpdatafunc
_lookup_getdata(PyInterpreterState *interp, PyObject *obj)
{
/* Cross-interpreter objects are looked up by exact match on the class.
We can reassess this policy when we move from a global registry to a
tp_* slot. */
return _lookup_getdata_from_registry(interp, obj);
}
crossinterpdatafunc
_PyCrossInterpreterData_Lookup(PyObject *obj)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
return _lookup_getdata(interp, obj);
}
static inline void
_set_xid_lookup_failure(PyInterpreterState *interp,
PyObject *obj, const char *msg)
{
PyObject *exctype = _get_not_shareable_error_type(interp);
assert(exctype != NULL);
if (msg != NULL) {
assert(obj == NULL);
PyErr_SetString(exctype, msg);
}
else if (obj == NULL) {
PyErr_SetString(exctype,
"object does not support cross-interpreter data");
}
else {
PyErr_Format(exctype,
"%S does not support cross-interpreter data", obj);
}
}
int
_PyObject_CheckCrossInterpreterData(PyObject *obj)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
crossinterpdatafunc getdata = _lookup_getdata(interp, obj);
if (getdata == NULL) {
if (!PyErr_Occurred()) {
_set_xid_lookup_failure(interp, obj, NULL);
}
return -1;
}
return 0;
}
int
_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
{
PyThreadState *tstate = _PyThreadState_GetCurrent();
#ifdef Py_DEBUG
// The caller must hold the GIL
_Py_EnsureTstateNotNULL(tstate);
#endif
PyInterpreterState *interp = tstate->interp;
// Reset data before re-populating.
*data = (_PyCrossInterpreterData){0};
data->interpid = -1;
// Call the "getdata" func for the object.
Py_INCREF(obj);
crossinterpdatafunc getdata = _lookup_getdata(interp, obj);
if (getdata == NULL) {
Py_DECREF(obj);
if (!PyErr_Occurred()) {
_set_xid_lookup_failure(interp, obj, NULL);
}
return -1;
}
int res = getdata(tstate, obj, data);
Py_DECREF(obj);
if (res != 0) {
return -1;
}
// Fill in the blanks and validate the result.
data->interpid = interp->id;
if (_check_xidata(tstate, data) != 0) {
(void)_PyCrossInterpreterData_Release(data);
return -1;
}
return 0;
}
PyObject *
_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
{
return data->new_object(data);
}
static int
_call_clear_xidata(void *data)
{
_xidata_clear((_PyCrossInterpreterData *)data);
return 0;
}
static int
_xidata_release(_PyCrossInterpreterData *data, int rawfree)
{
if ((data->data == NULL || data->free == NULL) && data->obj == NULL) {
// Nothing to release!
if (rawfree) {
PyMem_RawFree(data);
}
else {
data->data = NULL;
}
return 0;
}
// Switch to the original interpreter.
PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interpid);
if (interp == NULL) {
// The interpreter was already destroyed.
// This function shouldn't have been called.
// XXX Someone leaked some memory...
assert(PyErr_Occurred());
if (rawfree) {
PyMem_RawFree(data);
}
return -1;
}
// "Release" the data and/or the object.
if (rawfree) {
return _Py_CallInInterpreterAndRawFree(interp, _call_clear_xidata, data);
}
else {
return _Py_CallInInterpreter(interp, _call_clear_xidata, data);
}
}
int
_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
{
return _xidata_release(data, 0);
}
int
_PyCrossInterpreterData_ReleaseAndRawFree(_PyCrossInterpreterData *data)
{
return _xidata_release(data, 1);
}
/* registry of {type -> crossinterpdatafunc} */
/* For now we use a global registry of shareable classes. An
alternative would be to add a tp_* slot for a class's
crossinterpdatafunc. It would be simpler and more efficient. */
static inline struct _xidregistry *
_get_global_xidregistry(_PyRuntimeState *runtime)
{
return &runtime->xi.registry;
}
static inline struct _xidregistry *
_get_xidregistry(PyInterpreterState *interp)
{
return &interp->xi.registry;
}
static inline struct _xidregistry *
_get_xidregistry_for_type(PyInterpreterState *interp, PyTypeObject *cls)
{
struct _xidregistry *registry = _get_global_xidregistry(interp->runtime);
if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
registry = _get_xidregistry(interp);
}
return registry;
}
static int
_xidregistry_add_type(struct _xidregistry *xidregistry,
PyTypeObject *cls, crossinterpdatafunc getdata)
{
struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
if (newhead == NULL) {
return -1;
}
*newhead = (struct _xidregitem){
// We do not keep a reference, to avoid keeping the class alive.
.cls = cls,
.refcount = 1,
.getdata = getdata,
};
if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
// XXX Assign a callback to clear the entry from the registry?
newhead->weakref = PyWeakref_NewRef((PyObject *)cls, NULL);
if (newhead->weakref == NULL) {
PyMem_RawFree(newhead);
return -1;
}
}
newhead->next = xidregistry->head;
if (newhead->next != NULL) {
newhead->next->prev = newhead;
}
xidregistry->head = newhead;
return 0;
}
static struct _xidregitem *
_xidregistry_remove_entry(struct _xidregistry *xidregistry,
struct _xidregitem *entry)
{
struct _xidregitem *next = entry->next;
if (entry->prev != NULL) {
assert(entry->prev->next == entry);
entry->prev->next = next;
}
else {
assert(xidregistry->head == entry);
xidregistry->head = next;
}
if (next != NULL) {
next->prev = entry->prev;
}
Py_XDECREF(entry->weakref);
PyMem_RawFree(entry);
return next;
}
static void
_xidregistry_clear(struct _xidregistry *xidregistry)
{
struct _xidregitem *cur = xidregistry->head;
xidregistry->head = NULL;
while (cur != NULL) {
struct _xidregitem *next = cur->next;
Py_XDECREF(cur->weakref);
PyMem_RawFree(cur);
cur = next;
}
}
static void
_xidregistry_lock(struct _xidregistry *registry)
{
if (registry->mutex != NULL) {
PyThread_acquire_lock(registry->mutex, WAIT_LOCK);
}
}
static void
_xidregistry_unlock(struct _xidregistry *registry)
{
if (registry->mutex != NULL) {
PyThread_release_lock(registry->mutex);
}
}
static struct _xidregitem *
_xidregistry_find_type(struct _xidregistry *xidregistry, PyTypeObject *cls)
{
struct _xidregitem *cur = xidregistry->head;
while (cur != NULL) {
if (cur->weakref != NULL) {
// cur is/was a heap type.
PyObject *registered = _PyWeakref_GET_REF(cur->weakref);
if (registered == NULL) {
// The weakly ref'ed object was freed.
cur = _xidregistry_remove_entry(xidregistry, cur);
continue;
}
assert(PyType_Check(registered));
assert(cur->cls == (PyTypeObject *)registered);
assert(cur->cls->tp_flags & Py_TPFLAGS_HEAPTYPE);
Py_DECREF(registered);
}
if (cur->cls == cls) {
return cur;
}
cur = cur->next;
}
return NULL;
}
int
_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
crossinterpdatafunc getdata)
{
if (!PyType_Check(cls)) {
PyErr_Format(PyExc_ValueError, "only classes may be registered");
return -1;
}
if (getdata == NULL) {
PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
return -1;
}
int res = 0;
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _xidregistry *xidregistry = _get_xidregistry_for_type(interp, cls);
_xidregistry_lock(xidregistry);
struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
if (matched != NULL) {
assert(matched->getdata == getdata);
matched->refcount += 1;
goto finally;
}
res = _xidregistry_add_type(xidregistry, cls, getdata);
finally:
_xidregistry_unlock(xidregistry);
return res;
}
int
_PyCrossInterpreterData_UnregisterClass(PyTypeObject *cls)
{
int res = 0;
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _xidregistry *xidregistry = _get_xidregistry_for_type(interp, cls);
_xidregistry_lock(xidregistry);
struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
if (matched != NULL) {
assert(matched->refcount > 0);
matched->refcount -= 1;
if (matched->refcount == 0) {
(void)_xidregistry_remove_entry(xidregistry, matched);
}
res = 1;
}
_xidregistry_unlock(xidregistry);
return res;
}
static crossinterpdatafunc
_lookup_getdata_from_registry(PyInterpreterState *interp, PyObject *obj)
{
PyTypeObject *cls = Py_TYPE(obj);
struct _xidregistry *xidregistry = _get_xidregistry_for_type(interp, cls);
_xidregistry_lock(xidregistry);
struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
crossinterpdatafunc func = matched != NULL ? matched->getdata : NULL;
_xidregistry_unlock(xidregistry);
return func;
}
/* cross-interpreter data for builtin types */
// bytes
struct _shared_bytes_data {
char *bytes;
Py_ssize_t len;
};
static PyObject *
_new_bytes_object(_PyCrossInterpreterData *data)
{
struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
return PyBytes_FromStringAndSize(shared->bytes, shared->len);
}
static int
_bytes_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
if (_PyCrossInterpreterData_InitWithSize(
data, tstate->interp, sizeof(struct _shared_bytes_data), obj,
_new_bytes_object
) < 0)
{
return -1;
}
struct _shared_bytes_data *shared = (struct _shared_bytes_data *)data->data;
if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
_PyCrossInterpreterData_Clear(tstate->interp, data);
return -1;
}
return 0;
}
// str
struct _shared_str_data {
int kind;
const void *buffer;
Py_ssize_t len;
};
static PyObject *
_new_str_object(_PyCrossInterpreterData *data)
{
struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
}
static int
_str_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
if (_PyCrossInterpreterData_InitWithSize(
data, tstate->interp, sizeof(struct _shared_str_data), obj,
_new_str_object
) < 0)
{
return -1;
}
struct _shared_str_data *shared = (struct _shared_str_data *)data->data;
shared->kind = PyUnicode_KIND(obj);
shared->buffer = PyUnicode_DATA(obj);
shared->len = PyUnicode_GET_LENGTH(obj);
return 0;
}
// int
static PyObject *
_new_long_object(_PyCrossInterpreterData *data)
{
return PyLong_FromSsize_t((Py_ssize_t)(data->data));
}
static int
_long_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
/* Note that this means the size of shareable ints is bounded by
* sys.maxsize. Hence on 32-bit architectures that is half the
* size of maximum shareable ints on 64-bit.
*/
Py_ssize_t value = PyLong_AsSsize_t(obj);
if (value == -1 && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
}
return -1;
}
_PyCrossInterpreterData_Init(data, tstate->interp, (void *)value, NULL,
_new_long_object);
// data->obj and data->free remain NULL
return 0;
}
// float
static PyObject *
_new_float_object(_PyCrossInterpreterData *data)
{
double * value_ptr = data->data;
return PyFloat_FromDouble(*value_ptr);
}
static int
_float_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
if (_PyCrossInterpreterData_InitWithSize(
data, tstate->interp, sizeof(double), NULL,
_new_float_object
) < 0)
{
return -1;
}
double *shared = (double *)data->data;
*shared = PyFloat_AsDouble(obj);
return 0;
}
// None
static PyObject *
_new_none_object(_PyCrossInterpreterData *data)
{
// XXX Singleton refcounts are problematic across interpreters...
return Py_NewRef(Py_None);
}
static int
_none_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
_PyCrossInterpreterData_Init(data, tstate->interp, NULL, NULL,
_new_none_object);
// data->data, data->obj and data->free remain NULL
return 0;
}
// bool
static PyObject *
_new_bool_object(_PyCrossInterpreterData *data)
{
if (data->data){
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static int
_bool_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
_PyCrossInterpreterData_Init(data, tstate->interp,
(void *) (Py_IsTrue(obj) ? (uintptr_t) 1 : (uintptr_t) 0), NULL,
_new_bool_object);
// data->obj and data->free remain NULL
return 0;
}
// tuple
struct _shared_tuple_data {
Py_ssize_t len;
_PyCrossInterpreterData **data;
};
static PyObject *
_new_tuple_object(_PyCrossInterpreterData *data)
{
struct _shared_tuple_data *shared = (struct _shared_tuple_data *)(data->data);
PyObject *tuple = PyTuple_New(shared->len);
if (tuple == NULL) {
return NULL;
}
for (Py_ssize_t i = 0; i < shared->len; i++) {
PyObject *item = _PyCrossInterpreterData_NewObject(shared->data[i]);
if (item == NULL){
Py_DECREF(tuple);
return NULL;
}
PyTuple_SET_ITEM(tuple, i, item);
}
return tuple;
}
static void
_tuple_shared_free(void* data)
{
struct _shared_tuple_data *shared = (struct _shared_tuple_data *)(data);
#ifndef NDEBUG
int64_t interpid = PyInterpreterState_GetID(_PyInterpreterState_GET());
#endif
for (Py_ssize_t i = 0; i < shared->len; i++) {
if (shared->data[i] != NULL) {
assert(shared->data[i]->interpid == interpid);
_PyCrossInterpreterData_Release(shared->data[i]);
PyMem_RawFree(shared->data[i]);
shared->data[i] = NULL;
}
}
PyMem_Free(shared->data);
PyMem_RawFree(shared);
}
static int
_tuple_shared(PyThreadState *tstate, PyObject *obj,
_PyCrossInterpreterData *data)
{
Py_ssize_t len = PyTuple_GET_SIZE(obj);
if (len < 0) {
return -1;
}
struct _shared_tuple_data *shared = PyMem_RawMalloc(sizeof(struct _shared_tuple_data));
if (shared == NULL){
PyErr_NoMemory();
return -1;
}
shared->len = len;
shared->data = (_PyCrossInterpreterData **) PyMem_Calloc(shared->len, sizeof(_PyCrossInterpreterData *));
if (shared->data == NULL) {
PyErr_NoMemory();
return -1;
}
for (Py_ssize_t i = 0; i < shared->len; i++) {
_PyCrossInterpreterData *data = _PyCrossInterpreterData_New();
if (data == NULL) {
goto error; // PyErr_NoMemory already set
}
PyObject *item = PyTuple_GET_ITEM(obj, i);
int res = -1;
if (!_Py_EnterRecursiveCallTstate(tstate, " while sharing a tuple")) {
res = _PyObject_GetCrossInterpreterData(item, data);
_Py_LeaveRecursiveCallTstate(tstate);
}
if (res < 0) {
PyMem_RawFree(data);
goto error;
}
shared->data[i] = data;
}
_PyCrossInterpreterData_Init(
data, tstate->interp, shared, obj, _new_tuple_object);
data->free = _tuple_shared_free;
return 0;
error:
_tuple_shared_free(shared);
return -1;
}
// registration
static void
_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
{
// None
if (_xidregistry_add_type(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Py_FatalError("could not register None for cross-interpreter sharing");
}
// int
if (_xidregistry_add_type(xidregistry, &PyLong_Type, _long_shared) != 0) {
Py_FatalError("could not register int for cross-interpreter sharing");
}
// bytes
if (_xidregistry_add_type(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Py_FatalError("could not register bytes for cross-interpreter sharing");
}
// str
if (_xidregistry_add_type(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Py_FatalError("could not register str for cross-interpreter sharing");
}
// bool
if (_xidregistry_add_type(xidregistry, &PyBool_Type, _bool_shared) != 0) {
Py_FatalError("could not register bool for cross-interpreter sharing");
}
// float
if (_xidregistry_add_type(xidregistry, &PyFloat_Type, _float_shared) != 0) {
Py_FatalError("could not register float for cross-interpreter sharing");
}
// tuple
if (_xidregistry_add_type(xidregistry, &PyTuple_Type, _tuple_shared) != 0) {
Py_FatalError("could not register tuple for cross-interpreter sharing");
}
}
/* registry lifecycle */
static void
_xidregistry_init(struct _xidregistry *registry)
{
if (registry->initialized) {
return;
}
registry->initialized = 1;
if (registry->global) {
// We manage the mutex lifecycle in pystate.c.
assert(registry->mutex != NULL);
// Registering the builtins is cheap so we don't bother doing it lazily.
assert(registry->head == NULL);
_register_builtins_for_crossinterpreter_data(registry);
}
else {
// Within an interpreter we rely on the GIL instead of a separate lock.
assert(registry->mutex == NULL);
// There's nothing else to initialize.
}
}
static void
_xidregistry_fini(struct _xidregistry *registry)
{
if (!registry->initialized) {
return;
}
registry->initialized = 0;
_xidregistry_clear(registry);
if (registry->global) {
// We manage the mutex lifecycle in pystate.c.
assert(registry->mutex != NULL);
}
else {
// There's nothing else to finalize.
// Within an interpreter we rely on the GIL instead of a separate lock.
assert(registry->mutex == NULL);
}
}
/*************************/
/* convenience utilities */
/*************************/
static const char *
_copy_string_obj_raw(PyObject *strobj)
{
const char *str = PyUnicode_AsUTF8(strobj);
if (str == NULL) {
return NULL;
}
char *copied = PyMem_RawMalloc(strlen(str)+1);
if (copied == NULL) {
PyErr_NoMemory();
return NULL;
}
strcpy(copied, str);
return copied;
}
static int
_release_xid_data(_PyCrossInterpreterData *data, int rawfree)
{
PyObject *exc = PyErr_GetRaisedException();
int res = rawfree
? _PyCrossInterpreterData_Release(data)
: _PyCrossInterpreterData_ReleaseAndRawFree(data);
if (res < 0) {
/* The owning interpreter is already destroyed. */
_PyCrossInterpreterData_Clear(NULL, data);
// XXX Emit a warning?
PyErr_Clear();
}
PyErr_SetRaisedException(exc);
return res;
}
/***********************/
/* exception snapshots */
/***********************/
static int
_excinfo_init_type(struct _excinfo_type *info, PyObject *exc)
{
/* Note that this copies directly rather than into an intermediate
struct and does not clear on error. If we need that then we
should have a separate function to wrap this one
and do all that there. */
PyObject *strobj = NULL;
PyTypeObject *type = Py_TYPE(exc);
if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
assert(_Py_IsImmortal((PyObject *)type));
info->builtin = type;
}
else {
// Only builtin types are preserved.
info->builtin = NULL;
}
// __name__
strobj = PyType_GetName(type);
if (strobj == NULL) {
return -1;
}
info->name = _copy_string_obj_raw(strobj);
Py_DECREF(strobj);
if (info->name == NULL) {
return -1;
}
// __qualname__
strobj = PyType_GetQualName(type);
if (strobj == NULL) {
return -1;
}
info->qualname = _copy_string_obj_raw(strobj);
Py_DECREF(strobj);
if (info->name == NULL) {
return -1;
}
// __module__
strobj = _PyType_GetModuleName(type);