Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/crossinterp.c
Line
Count
Source
1
2
/* API for managing interactions between isolated interpreters */
3
4
#include "Python.h"
5
#include "marshal.h"              // PyMarshal_WriteObjectToString()
6
#include "osdefs.h"               // MAXPATHLEN
7
#include "pycore_ceval.h"         // _Py_simple_func
8
#include "pycore_crossinterp.h"   // _PyXIData_t
9
#include "pycore_function.h"      // _PyFunction_VerifyStateless()
10
#include "pycore_global_strings.h"  // _Py_ID()
11
#include "pycore_import.h"        // _PyImport_SetModule()
12
#include "pycore_initconfig.h"    // _PyStatus_OK()
13
#include "pycore_namespace.h"     // _PyNamespace_New()
14
#include "pycore_pythonrun.h"     // _Py_SourceAsString()
15
#include "pycore_runtime.h"       // _PyRuntime
16
#include "pycore_setobject.h"     // _PySet_NextEntry()
17
#include "pycore_typeobject.h"    // _PyStaticType_InitBuiltin()
18
19
20
static Py_ssize_t
21
_Py_GetMainfile(char *buffer, size_t maxlen)
22
0
{
23
    // We don't expect subinterpreters to have the __main__ module's
24
    // __name__ set, but proceed just in case.
25
0
    PyThreadState *tstate = _PyThreadState_GET();
26
0
    PyObject *module = _Py_GetMainModule(tstate);
27
0
    if (_Py_CheckMainModule(module) < 0) {
28
0
        Py_XDECREF(module);
29
0
        return -1;
30
0
    }
31
0
    Py_ssize_t size = _PyModule_GetFilenameUTF8(module, buffer, maxlen);
32
0
    Py_DECREF(module);
33
0
    return size;
34
0
}
35
36
37
static PyObject *
38
runpy_run_path(const char *filename, const char *modname)
39
0
{
40
0
    PyObject *run_path = PyImport_ImportModuleAttrString("runpy", "run_path");
41
0
    if (run_path == NULL) {
42
0
        return NULL;
43
0
    }
44
0
    PyObject *args = Py_BuildValue("(sOs)", filename, Py_None, modname);
45
0
    if (args == NULL) {
46
0
        Py_DECREF(run_path);
47
0
        return NULL;
48
0
    }
49
0
    PyObject *ns = PyObject_Call(run_path, args, NULL);
50
0
    Py_DECREF(run_path);
51
0
    Py_DECREF(args);
52
0
    return ns;
53
0
}
54
55
56
static void
57
set_exc_with_cause(PyObject *exctype, const char *msg)
58
0
{
59
0
    PyObject *cause = PyErr_GetRaisedException();
60
0
    PyErr_SetString(exctype, msg);
61
0
    PyObject *exc = PyErr_GetRaisedException();
62
0
    PyException_SetCause(exc, cause);
63
0
    PyErr_SetRaisedException(exc);
64
0
}
65
66
67
/****************************/
68
/* module duplication utils */
69
/****************************/
70
71
struct sync_module_result {
72
    PyObject *module;
73
    PyObject *loaded;
74
    PyObject *failed;
75
};
76
77
struct sync_module {
78
    const char *filename;
79
    char _filename[MAXPATHLEN+1];
80
    struct sync_module_result cached;
81
};
82
83
static void
84
sync_module_clear(struct sync_module *data)
85
0
{
86
0
    data->filename = NULL;
87
0
    Py_CLEAR(data->cached.module);
88
0
    Py_CLEAR(data->cached.loaded);
89
0
    Py_CLEAR(data->cached.failed);
90
0
}
91
92
static void
93
sync_module_capture_exc(PyThreadState *tstate, struct sync_module *data)
94
0
{
95
0
    assert(_PyErr_Occurred(tstate));
96
0
    PyObject *context = data->cached.failed;
97
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
98
0
    _PyErr_SetRaisedException(tstate, Py_NewRef(exc));
99
0
    if (context != NULL) {
100
0
        PyException_SetContext(exc, context);
101
0
    }
102
0
    data->cached.failed = exc;
103
0
}
104
105
106
static int
107
ensure_isolated_main(PyThreadState *tstate, struct sync_module *main)
108
0
{
109
    // Load the module from the original file (or from a cache).
110
111
    // First try the local cache.
112
0
    if (main->cached.failed != NULL) {
113
        // We'll deal with this in apply_isolated_main().
114
0
        assert(main->cached.module == NULL);
115
0
        assert(main->cached.loaded == NULL);
116
0
        return 0;
117
0
    }
118
0
    else if (main->cached.loaded != NULL) {
119
0
        assert(main->cached.module != NULL);
120
0
        return 0;
121
0
    }
122
0
    assert(main->cached.module == NULL);
123
124
0
    if (main->filename == NULL) {
125
0
        _PyErr_SetString(tstate, PyExc_NotImplementedError, "");
126
0
        return -1;
127
0
    }
128
129
    // It wasn't in the local cache so we'll need to populate it.
130
0
    PyObject *mod = _Py_GetMainModule(tstate);
131
0
    if (_Py_CheckMainModule(mod) < 0) {
132
        // This is probably unrecoverable, so don't bother caching the error.
133
0
        assert(_PyErr_Occurred(tstate));
134
0
        Py_XDECREF(mod);
135
0
        return -1;
136
0
    }
137
0
    PyObject *loaded = NULL;
138
139
    // Try the per-interpreter cache for the loaded module.
140
    // XXX Store it in sys.modules?
141
0
    PyObject *interpns = PyInterpreterState_GetDict(tstate->interp);
142
0
    assert(interpns != NULL);
143
0
    PyObject *key = PyUnicode_FromString("CACHED_MODULE_NS___main__");
144
0
    if (key == NULL) {
145
        // It's probably unrecoverable, so don't bother caching the error.
146
0
        Py_DECREF(mod);
147
0
        return -1;
148
0
    }
149
0
    else if (PyDict_GetItemRef(interpns, key, &loaded) < 0) {
150
        // It's probably unrecoverable, so don't bother caching the error.
151
0
        Py_DECREF(mod);
152
0
        Py_DECREF(key);
153
0
        return -1;
154
0
    }
155
0
    else if (loaded == NULL) {
156
        // It wasn't already loaded from file.
157
0
        loaded = PyModule_NewObject(&_Py_ID(__main__));
158
0
        if (loaded == NULL) {
159
0
            goto error;
160
0
        }
161
0
        PyObject *ns = _PyModule_GetDict(loaded);
162
163
        // We don't want to trigger "if __name__ == '__main__':",
164
        // so we use a bogus module name.
165
0
        PyObject *loaded_ns =
166
0
                    runpy_run_path(main->filename, "<fake __main__>");
167
0
        if (loaded_ns == NULL) {
168
0
            goto error;
169
0
        }
170
0
        int res = PyDict_Update(ns, loaded_ns);
171
0
        Py_DECREF(loaded_ns);
172
0
        if (res < 0) {
173
0
            goto error;
174
0
        }
175
176
        // Set the per-interpreter cache entry.
177
0
        if (PyDict_SetItem(interpns, key, loaded) < 0) {
178
0
            goto error;
179
0
        }
180
0
    }
181
182
0
    Py_DECREF(key);
183
0
    main->cached = (struct sync_module_result){
184
0
       .module = mod,
185
0
       .loaded = loaded,
186
0
    };
187
0
    return 0;
188
189
0
error:
190
0
    sync_module_capture_exc(tstate, main);
191
0
    Py_XDECREF(loaded);
192
0
    Py_DECREF(mod);
193
0
    Py_XDECREF(key);
194
0
    return -1;
195
0
}
196
197
#ifndef NDEBUG
198
static int
199
main_mod_matches(PyObject *expected)
200
{
201
    PyObject *mod = PyImport_GetModule(&_Py_ID(__main__));
202
    Py_XDECREF(mod);
203
    return mod == expected;
204
}
205
#endif
206
207
static int
208
apply_isolated_main(PyThreadState *tstate, struct sync_module *main)
209
0
{
210
0
    assert((main->cached.loaded == NULL) == (main->cached.loaded == NULL));
211
0
    if (main->cached.failed != NULL) {
212
        // It must have failed previously.
213
0
        assert(main->cached.loaded == NULL);
214
0
        _PyErr_SetRaisedException(tstate, main->cached.failed);
215
0
        return -1;
216
0
    }
217
0
    assert(main->cached.loaded != NULL);
218
219
0
    assert(main_mod_matches(main->cached.module));
220
0
    if (_PyImport_SetModule(&_Py_ID(__main__), main->cached.loaded) < 0) {
221
0
        sync_module_capture_exc(tstate, main);
222
0
        return -1;
223
0
    }
224
0
    return 0;
225
0
}
226
227
static void
228
restore_main(PyThreadState *tstate, struct sync_module *main)
229
0
{
230
0
    assert(main->cached.failed == NULL);
231
0
    assert(main->cached.module != NULL);
232
0
    assert(main->cached.loaded != NULL);
233
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
234
0
    assert(main_mod_matches(main->cached.loaded));
235
0
    int res = _PyImport_SetModule(&_Py_ID(__main__), main->cached.module);
236
0
    assert(res == 0);
237
0
    if (res < 0) {
238
0
        PyErr_FormatUnraisable("Exception ignored while restoring __main__");
239
0
    }
240
0
    _PyErr_SetRaisedException(tstate, exc);
241
0
}
242
243
244
/**************/
245
/* exceptions */
246
/**************/
247
248
typedef struct xi_exceptions exceptions_t;
249
static int init_static_exctypes(exceptions_t *, PyInterpreterState *);
250
static void fini_static_exctypes(exceptions_t *, PyInterpreterState *);
251
static int init_heap_exctypes(exceptions_t *);
252
static void fini_heap_exctypes(exceptions_t *);
253
#include "crossinterp_exceptions.h"
254
255
256
/***************************/
257
/* cross-interpreter calls */
258
/***************************/
259
260
int
261
_Py_CallInInterpreter(PyInterpreterState *interp,
262
                      _Py_simple_func func, void *arg)
263
0
{
264
0
    if (interp == PyInterpreterState_Get()) {
265
0
        return func(arg);
266
0
    }
267
    // XXX Emit a warning if this fails?
268
0
    _PyEval_AddPendingCall(interp, (_Py_pending_call_func)func, arg, 0);
269
0
    return 0;
270
0
}
271
272
int
273
_Py_CallInInterpreterAndRawFree(PyInterpreterState *interp,
274
                                _Py_simple_func func, void *arg)
275
0
{
276
0
    if (interp == PyInterpreterState_Get()) {
277
0
        int res = func(arg);
278
0
        PyMem_RawFree(arg);
279
0
        return res;
280
0
    }
281
    // XXX Emit a warning if this fails?
282
0
    _PyEval_AddPendingCall(interp, func, arg, _Py_PENDING_RAWFREE);
283
0
    return 0;
284
0
}
285
286
287
/**************************/
288
/* cross-interpreter data */
289
/**************************/
290
291
/* registry of {type -> _PyXIData_getdata_t} */
292
293
/* For now we use a global registry of shareable classes.
294
   An alternative would be to add a tp_* slot for a class's
295
   _PyXIData_getdata_t.  It would be simpler and more efficient. */
296
297
static void xid_lookup_init(_PyXIData_lookup_t *);
298
static void xid_lookup_fini(_PyXIData_lookup_t *);
299
struct _dlcontext;
300
static _PyXIData_getdata_t lookup_getdata(struct _dlcontext *, PyObject *);
301
#include "crossinterp_data_lookup.h"
302
303
304
/* lifecycle */
305
306
_PyXIData_t *
307
_PyXIData_New(void)
308
0
{
309
0
    _PyXIData_t *xid = PyMem_RawCalloc(1, sizeof(_PyXIData_t));
310
0
    if (xid == NULL) {
311
0
        PyErr_NoMemory();
312
0
    }
313
0
    return xid;
314
0
}
315
316
void
317
_PyXIData_Free(_PyXIData_t *xid)
318
0
{
319
0
    PyInterpreterState *interp = PyInterpreterState_Get();
320
0
    _PyXIData_Clear(interp, xid);
321
0
    PyMem_RawFree(xid);
322
0
}
323
324
325
/* defining cross-interpreter data */
326
327
static inline void
328
_xidata_init(_PyXIData_t *xidata)
329
0
{
330
    // If the value is being reused
331
    // then _xidata_clear() should have been called already.
332
0
    assert(xidata->data == NULL);
333
0
    assert(xidata->obj == NULL);
334
0
    *xidata = (_PyXIData_t){0};
335
0
    _PyXIData_INTERPID(xidata) = -1;
336
0
}
337
338
static inline void
339
_xidata_clear(_PyXIData_t *xidata)
340
0
{
341
    // _PyXIData_t only has two members that need to be
342
    // cleaned up, if set: "xidata" must be freed and "obj" must be decref'ed.
343
    // In both cases the original (owning) interpreter must be used,
344
    // which is the caller's responsibility to ensure.
345
0
    if (xidata->data != NULL) {
346
0
        if (xidata->free != NULL) {
347
0
            xidata->free(xidata->data);
348
0
        }
349
0
        xidata->data = NULL;
350
0
    }
351
0
    Py_CLEAR(xidata->obj);
352
0
}
353
354
void
355
_PyXIData_Init(_PyXIData_t *xidata,
356
               PyInterpreterState *interp,
357
               void *shared, PyObject *obj,
358
               xid_newobjfunc new_object)
359
0
{
360
0
    assert(xidata != NULL);
361
0
    assert(new_object != NULL);
362
0
    _xidata_init(xidata);
363
0
    xidata->data = shared;
364
0
    if (obj != NULL) {
365
0
        assert(interp != NULL);
366
        // released in _PyXIData_Clear()
367
0
        xidata->obj = Py_NewRef(obj);
368
0
    }
369
    // Ideally every object would know its owning interpreter.
370
    // Until then, we have to rely on the caller to identify it
371
    // (but we don't need it in all cases).
372
0
    _PyXIData_INTERPID(xidata) = (interp != NULL)
373
0
        ? PyInterpreterState_GetID(interp)
374
0
        : -1;
375
0
    xidata->new_object = new_object;
376
0
}
377
378
int
379
_PyXIData_InitWithSize(_PyXIData_t *xidata,
380
                       PyInterpreterState *interp,
381
                       const size_t size, PyObject *obj,
382
                       xid_newobjfunc new_object)
383
0
{
384
0
    assert(size > 0);
385
    // For now we always free the shared data in the same interpreter
386
    // where it was allocated, so the interpreter is required.
387
0
    assert(interp != NULL);
388
0
    _PyXIData_Init(xidata, interp, NULL, obj, new_object);
389
0
    xidata->data = PyMem_RawCalloc(1, size);
390
0
    if (xidata->data == NULL) {
391
0
        Py_CLEAR(xidata->obj);
392
0
        PyErr_NoMemory();
393
0
        return -1;
394
0
    }
395
0
    xidata->free = PyMem_RawFree;
396
0
    return 0;
397
0
}
398
399
void
400
_PyXIData_Clear(PyInterpreterState *interp, _PyXIData_t *xidata)
401
0
{
402
0
    assert(xidata != NULL);
403
    // This must be called in the owning interpreter.
404
0
    assert(interp == NULL
405
0
           || _PyXIData_INTERPID(xidata) == -1
406
0
           || _PyXIData_INTERPID(xidata) == PyInterpreterState_GetID(interp));
407
0
    _xidata_clear(xidata);
408
0
}
409
410
411
/* getting cross-interpreter data */
412
413
static inline void
414
_set_xid_lookup_failure(PyThreadState *tstate, PyObject *obj, const char *msg,
415
                        PyObject *cause)
416
0
{
417
0
    if (msg != NULL) {
418
0
        assert(obj == NULL);
419
0
        set_notshareableerror(tstate, cause, 0, msg);
420
0
    }
421
0
    else if (obj == NULL) {
422
0
        msg = "object does not support cross-interpreter data";
423
0
        set_notshareableerror(tstate, cause, 0, msg);
424
0
    }
425
0
    else {
426
0
        msg = "%R does not support cross-interpreter data";
427
0
        format_notshareableerror(tstate, cause, 0, msg, obj);
428
0
    }
429
0
}
430
431
432
int
433
_PyObject_CheckXIData(PyThreadState *tstate, PyObject *obj)
434
0
{
435
0
    dlcontext_t ctx;
436
0
    if (get_lookup_context(tstate, &ctx) < 0) {
437
0
        return -1;
438
0
    }
439
0
    _PyXIData_getdata_t getdata = lookup_getdata(&ctx, obj);
440
0
    if (getdata.basic == NULL && getdata.fallback == NULL) {
441
0
        if (!_PyErr_Occurred(tstate)) {
442
0
            _set_xid_lookup_failure(tstate, obj, NULL, NULL);
443
0
        }
444
0
        return -1;
445
0
    }
446
0
    return 0;
447
0
}
448
449
static int
450
_check_xidata(PyThreadState *tstate, _PyXIData_t *xidata)
451
0
{
452
    // xidata->data can be anything, including NULL, so we don't check it.
453
454
    // xidata->obj may be NULL, so we don't check it.
455
456
0
    if (_PyXIData_INTERPID(xidata) < 0) {
457
0
        PyErr_SetString(PyExc_SystemError, "missing interp");
458
0
        return -1;
459
0
    }
460
461
0
    if (xidata->new_object == NULL) {
462
0
        PyErr_SetString(PyExc_SystemError, "missing new_object func");
463
0
        return -1;
464
0
    }
465
466
    // xidata->free may be NULL, so we don't check it.
467
468
0
    return 0;
469
0
}
470
471
static int
472
_get_xidata(PyThreadState *tstate,
473
            PyObject *obj, xidata_fallback_t fallback, _PyXIData_t *xidata)
474
0
{
475
0
    PyInterpreterState *interp = tstate->interp;
476
477
0
    assert(xidata->data == NULL);
478
0
    assert(xidata->obj == NULL);
479
0
    if (xidata->data != NULL || xidata->obj != NULL) {
480
0
        _PyErr_SetString(tstate, PyExc_ValueError, "xidata not cleared");
481
0
        return -1;
482
0
    }
483
484
    // Call the "getdata" func for the object.
485
0
    dlcontext_t ctx;
486
0
    if (get_lookup_context(tstate, &ctx) < 0) {
487
0
        return -1;
488
0
    }
489
0
    Py_INCREF(obj);
490
0
    _PyXIData_getdata_t getdata = lookup_getdata(&ctx, obj);
491
0
    if (getdata.basic == NULL && getdata.fallback == NULL) {
492
0
        if (PyErr_Occurred()) {
493
0
            Py_DECREF(obj);
494
0
            return -1;
495
0
        }
496
        // Fall back to obj
497
0
        Py_DECREF(obj);
498
0
        if (!_PyErr_Occurred(tstate)) {
499
0
            _set_xid_lookup_failure(tstate, obj, NULL, NULL);
500
0
        }
501
0
        return -1;
502
0
    }
503
0
    int res = getdata.basic != NULL
504
0
        ? getdata.basic(tstate, obj, xidata)
505
0
        : getdata.fallback(tstate, obj, fallback, xidata);
506
0
    Py_DECREF(obj);
507
0
    if (res != 0) {
508
0
        PyObject *cause = _PyErr_GetRaisedException(tstate);
509
0
        assert(cause != NULL);
510
0
        _set_xid_lookup_failure(tstate, obj, NULL, cause);
511
0
        Py_XDECREF(cause);
512
0
        return -1;
513
0
    }
514
515
    // Fill in the blanks and validate the result.
516
0
    _PyXIData_INTERPID(xidata) = PyInterpreterState_GetID(interp);
517
0
    if (_check_xidata(tstate, xidata) != 0) {
518
0
        (void)_PyXIData_Release(xidata);
519
0
        return -1;
520
0
    }
521
522
0
    return 0;
523
0
}
524
525
int
526
_PyObject_GetXIDataNoFallback(PyThreadState *tstate,
527
                              PyObject *obj, _PyXIData_t *xidata)
528
0
{
529
0
    return _get_xidata(tstate, obj, _PyXIDATA_XIDATA_ONLY, xidata);
530
0
}
531
532
int
533
_PyObject_GetXIData(PyThreadState *tstate,
534
                    PyObject *obj, xidata_fallback_t fallback,
535
                    _PyXIData_t *xidata)
536
0
{
537
0
    switch (fallback) {
538
0
        case _PyXIDATA_XIDATA_ONLY:
539
0
            return _get_xidata(tstate, obj, fallback, xidata);
540
0
        case _PyXIDATA_FULL_FALLBACK:
541
0
            if (_get_xidata(tstate, obj, fallback, xidata) == 0) {
542
0
                return 0;
543
0
            }
544
0
            PyObject *exc = _PyErr_GetRaisedException(tstate);
545
0
            if (PyFunction_Check(obj)) {
546
0
                if (_PyFunction_GetXIData(tstate, obj, xidata) == 0) {
547
0
                    Py_DECREF(exc);
548
0
                    return 0;
549
0
                }
550
0
                _PyErr_Clear(tstate);
551
0
            }
552
            // We could try _PyMarshal_GetXIData() but we won't for now.
553
0
            if (_PyPickle_GetXIData(tstate, obj, xidata) == 0) {
554
0
                Py_DECREF(exc);
555
0
                return 0;
556
0
            }
557
            // Raise the original exception.
558
0
            _PyErr_SetRaisedException(tstate, exc);
559
0
            return -1;
560
0
        default:
561
#ifdef Py_DEBUG
562
            Py_FatalError("unsupported xidata fallback option");
563
#endif
564
0
            _PyErr_SetString(tstate, PyExc_SystemError,
565
0
                             "unsupported xidata fallback option");
566
0
            return -1;
567
0
    }
568
0
}
569
570
571
/* pickle C-API */
572
573
/* Per-interpreter cache for pickle.dumps and pickle.loads.
574
 *
575
 * Each interpreter has its own cache in _PyXI_state_t.pickle, preserving
576
 * interpreter isolation.  The cache is populated lazily on first use and
577
 * cleared during interpreter finalization in _Py_xi_state_fini().
578
 *
579
 * Note: the cached references are captured at first use and not invalidated
580
 * on module reload.  This matches the caching pattern used elsewhere in
581
 * CPython (e.g. arraymodule.c, _decimal.c). */
582
583
static PyObject *
584
_get_pickle_dumps(PyThreadState *tstate)
585
0
{
586
0
    _PyXI_state_t *state = _PyXI_GET_STATE(tstate->interp);
587
0
    PyObject *dumps = state->pickle.dumps;
588
0
    if (dumps != NULL) {
589
0
        return dumps;
590
0
    }
591
0
    dumps = PyImport_ImportModuleAttrString("pickle", "dumps");
592
0
    if (dumps == NULL) {
593
0
        return NULL;
594
0
    }
595
0
    state->pickle.dumps = dumps;  // owns the reference
596
0
    return dumps;
597
0
}
598
599
static PyObject *
600
_get_pickle_loads(PyThreadState *tstate)
601
0
{
602
0
    _PyXI_state_t *state = _PyXI_GET_STATE(tstate->interp);
603
0
    PyObject *loads = state->pickle.loads;
604
0
    if (loads != NULL) {
605
0
        return loads;
606
0
    }
607
0
    loads = PyImport_ImportModuleAttrString("pickle", "loads");
608
0
    if (loads == NULL) {
609
0
        return NULL;
610
0
    }
611
0
    state->pickle.loads = loads;  // owns the reference
612
0
    return loads;
613
0
}
614
615
struct _pickle_context {
616
    PyThreadState *tstate;
617
};
618
619
static PyObject *
620
_PyPickle_Dumps(struct _pickle_context *ctx, PyObject *obj)
621
0
{
622
0
    PyObject *dumps = _get_pickle_dumps(ctx->tstate);
623
0
    if (dumps == NULL) {
624
0
        return NULL;
625
0
    }
626
    // dumps is a borrowed reference from the cache.
627
0
    return PyObject_CallOneArg(dumps, obj);
628
0
}
629
630
631
struct _unpickle_context {
632
    PyThreadState *tstate;
633
    // We only special-case the __main__ module,
634
    // since other modules behave consistently.
635
    struct sync_module main;
636
};
637
638
static void
639
_unpickle_context_clear(struct _unpickle_context *ctx)
640
0
{
641
0
    sync_module_clear(&ctx->main);
642
0
}
643
644
static int
645
check_missing___main___attr(PyObject *exc)
646
0
{
647
0
    assert(!PyErr_Occurred());
648
0
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
649
0
        return 0;
650
0
    }
651
652
    // Get the error message.
653
0
    PyObject *args = PyException_GetArgs(exc);
654
0
    if (args == NULL || args == Py_None || PyObject_Size(args) < 1) {
655
0
        Py_XDECREF(args);
656
0
        assert(!PyErr_Occurred());
657
0
        return 0;
658
0
    }
659
0
    PyObject *msgobj = args;
660
0
    if (!PyUnicode_Check(msgobj)) {
661
0
        msgobj = PySequence_GetItem(args, 0);
662
0
        Py_DECREF(args);
663
0
        if (msgobj == NULL) {
664
0
            PyErr_Clear();
665
0
            return 0;
666
0
        }
667
0
    }
668
0
    const char *err = PyUnicode_AsUTF8(msgobj);
669
0
    if (err == NULL) {
670
0
        PyErr_Clear();
671
0
        Py_DECREF(msgobj);
672
0
        return 0;
673
0
    }
674
675
    // Check if it's a missing __main__ attr.
676
0
    int cmp = strncmp(err, "module '__main__' has no attribute '", 36);
677
0
    Py_DECREF(msgobj);
678
0
    return cmp == 0;
679
0
}
680
681
static PyObject *
682
_PyPickle_Loads(struct _unpickle_context *ctx, PyObject *pickled)
683
0
{
684
0
    PyThreadState *tstate = ctx->tstate;
685
686
0
    PyObject *exc = NULL;
687
    // loads is a borrowed reference from the per-interpreter cache.
688
0
    PyObject *loads = _get_pickle_loads(tstate);
689
0
    if (loads == NULL) {
690
0
        return NULL;
691
0
    }
692
693
    // Make an initial attempt to unpickle.
694
0
    PyObject *obj = PyObject_CallOneArg(loads, pickled);
695
0
    if (obj != NULL) {
696
0
        goto finally;
697
0
    }
698
0
    assert(_PyErr_Occurred(tstate));
699
0
    if (ctx == NULL) {
700
0
        goto finally;
701
0
    }
702
0
    exc = _PyErr_GetRaisedException(tstate);
703
0
    if (!check_missing___main___attr(exc)) {
704
0
        goto finally;
705
0
    }
706
707
    // Temporarily swap in a fake __main__ loaded from the original
708
    // file and cached.  Note that functions will use the cached ns
709
    // for __globals__, // not the actual module.
710
0
    if (ensure_isolated_main(tstate, &ctx->main) < 0) {
711
0
        goto finally;
712
0
    }
713
0
    if (apply_isolated_main(tstate, &ctx->main) < 0) {
714
0
        goto finally;
715
0
    }
716
717
    // Try to unpickle once more.
718
0
    obj = PyObject_CallOneArg(loads, pickled);
719
0
    restore_main(tstate, &ctx->main);
720
0
    if (obj == NULL) {
721
0
        goto finally;
722
0
    }
723
0
    Py_CLEAR(exc);
724
725
0
finally:
726
0
    if (exc != NULL) {
727
0
        if (_PyErr_Occurred(tstate)) {
728
0
            sync_module_capture_exc(tstate, &ctx->main);
729
0
        }
730
        // We restore the original exception.
731
        // It might make sense to chain it (__context__).
732
0
        _PyErr_SetRaisedException(tstate, exc);
733
0
    }
734
0
    return obj;
735
0
}
736
737
738
/* pickle wrapper */
739
740
struct _pickle_xid_context {
741
    // __main__.__file__
742
    struct {
743
        const char *utf8;
744
        size_t len;
745
        char _utf8[MAXPATHLEN+1];
746
    } mainfile;
747
};
748
749
static int
750
_set_pickle_xid_context(PyThreadState *tstate, struct _pickle_xid_context *ctx)
751
0
{
752
    // Set mainfile if possible.
753
0
    Py_ssize_t len = _Py_GetMainfile(ctx->mainfile._utf8, MAXPATHLEN);
754
0
    if (len < 0) {
755
        // For now we ignore any exceptions.
756
0
        PyErr_Clear();
757
0
    }
758
0
    else if (len > 0) {
759
0
        ctx->mainfile.utf8 = ctx->mainfile._utf8;
760
0
        ctx->mainfile.len = (size_t)len;
761
0
    }
762
763
0
    return 0;
764
0
}
765
766
767
struct _shared_pickle_data {
768
    _PyBytes_data_t pickled;  // Must be first if we use _PyBytes_FromXIData().
769
    struct _pickle_xid_context ctx;
770
};
771
772
PyObject *
773
_PyPickle_LoadFromXIData(_PyXIData_t *xidata)
774
0
{
775
0
    PyThreadState *tstate = _PyThreadState_GET();
776
0
    struct _shared_pickle_data *shared =
777
0
                            (struct _shared_pickle_data *)xidata->data;
778
    // We avoid copying the pickled data by wrapping it in a memoryview.
779
    // The alternative is to get a bytes object using _PyBytes_FromXIData().
780
0
    PyObject *pickled = PyMemoryView_FromMemory(
781
0
            (char *)shared->pickled.bytes, shared->pickled.len, PyBUF_READ);
782
0
    if (pickled == NULL) {
783
0
        return NULL;
784
0
    }
785
786
    // Unpickle the object.
787
0
    struct _unpickle_context ctx = {
788
0
        .tstate = tstate,
789
0
        .main = {
790
0
            .filename = shared->ctx.mainfile.utf8,
791
0
        },
792
0
    };
793
0
    PyObject *obj = _PyPickle_Loads(&ctx, pickled);
794
0
    Py_DECREF(pickled);
795
0
    _unpickle_context_clear(&ctx);
796
0
    if (obj == NULL) {
797
0
        PyObject *cause = _PyErr_GetRaisedException(tstate);
798
0
        assert(cause != NULL);
799
0
        _set_xid_lookup_failure(
800
0
                    tstate, NULL, "object could not be unpickled", cause);
801
0
        Py_DECREF(cause);
802
0
    }
803
0
    return obj;
804
0
}
805
806
807
int
808
_PyPickle_GetXIData(PyThreadState *tstate, PyObject *obj, _PyXIData_t *xidata)
809
0
{
810
    // Pickle the object.
811
0
    struct _pickle_context ctx = {
812
0
        .tstate = tstate,
813
0
    };
814
0
    PyObject *bytes = _PyPickle_Dumps(&ctx, obj);
815
0
    if (bytes == NULL) {
816
0
        PyObject *cause = _PyErr_GetRaisedException(tstate);
817
0
        assert(cause != NULL);
818
0
        _set_xid_lookup_failure(
819
0
                    tstate, NULL, "object could not be pickled", cause);
820
0
        Py_DECREF(cause);
821
0
        return -1;
822
0
    }
823
824
    // If we had an "unwrapper" mechnanism, we could call
825
    // _PyObject_GetXIData() on the bytes object directly and add
826
    // a simple unwrapper to call pickle.loads() on the bytes.
827
0
    size_t size = sizeof(struct _shared_pickle_data);
828
0
    struct _shared_pickle_data *shared =
829
0
            (struct _shared_pickle_data *)_PyBytes_GetXIDataWrapped(
830
0
                    tstate, bytes, size, _PyPickle_LoadFromXIData, xidata);
831
0
    Py_DECREF(bytes);
832
0
    if (shared == NULL) {
833
0
        return -1;
834
0
    }
835
836
    // If it mattered, we could skip getting __main__.__file__
837
    // when "__main__" doesn't show up in the pickle bytes.
838
0
    if (_set_pickle_xid_context(tstate, &shared->ctx) < 0) {
839
0
        _xidata_clear(xidata);
840
0
        return -1;
841
0
    }
842
843
0
    return 0;
844
0
}
845
846
847
/* marshal wrapper */
848
849
PyObject *
850
_PyMarshal_ReadObjectFromXIData(_PyXIData_t *xidata)
851
0
{
852
0
    PyThreadState *tstate = _PyThreadState_GET();
853
0
    _PyBytes_data_t *shared = (_PyBytes_data_t *)xidata->data;
854
0
    PyObject *obj = PyMarshal_ReadObjectFromString(shared->bytes, shared->len);
855
0
    if (obj == NULL) {
856
0
        PyObject *cause = _PyErr_GetRaisedException(tstate);
857
0
        assert(cause != NULL);
858
0
        _set_xid_lookup_failure(
859
0
                    tstate, NULL, "object could not be unmarshalled", cause);
860
0
        Py_DECREF(cause);
861
0
        return NULL;
862
0
    }
863
0
    return obj;
864
0
}
865
866
int
867
_PyMarshal_GetXIData(PyThreadState *tstate, PyObject *obj, _PyXIData_t *xidata)
868
0
{
869
0
    PyObject *bytes = PyMarshal_WriteObjectToString(obj, Py_MARSHAL_VERSION);
870
0
    if (bytes == NULL) {
871
0
        PyObject *cause = _PyErr_GetRaisedException(tstate);
872
0
        assert(cause != NULL);
873
0
        _set_xid_lookup_failure(
874
0
                    tstate, NULL, "object could not be marshalled", cause);
875
0
        Py_DECREF(cause);
876
0
        return -1;
877
0
    }
878
0
    size_t size = sizeof(_PyBytes_data_t);
879
0
    _PyBytes_data_t *shared = _PyBytes_GetXIDataWrapped(
880
0
            tstate, bytes, size, _PyMarshal_ReadObjectFromXIData, xidata);
881
0
    Py_DECREF(bytes);
882
0
    if (shared == NULL) {
883
0
        return -1;
884
0
    }
885
0
    return 0;
886
0
}
887
888
889
/* script wrapper */
890
891
static int
892
verify_script(PyThreadState *tstate, PyCodeObject *co, int checked, int pure)
893
0
{
894
    // Make sure it isn't a closure and (optionally) doesn't use globals.
895
0
    PyObject *builtins = NULL;
896
0
    if (pure) {
897
0
        builtins = _PyEval_GetBuiltins(tstate);
898
0
        assert(builtins != NULL);
899
0
    }
900
0
    if (checked) {
901
0
        assert(_PyCode_VerifyStateless(tstate, co, NULL, NULL, builtins) == 0);
902
0
    }
903
0
    else if (_PyCode_VerifyStateless(tstate, co, NULL, NULL, builtins) < 0) {
904
0
        return -1;
905
0
    }
906
    // Make sure it doesn't have args.
907
0
    if (co->co_argcount > 0
908
0
        || co->co_posonlyargcount > 0
909
0
        || co->co_kwonlyargcount > 0
910
0
        || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS))
911
0
    {
912
0
        _PyErr_SetString(tstate, PyExc_ValueError,
913
0
                         "code with args not supported");
914
0
        return -1;
915
0
    }
916
    // Make sure it doesn't return anything.
917
0
    if (!_PyCode_ReturnsOnlyNone(co)) {
918
0
        _PyErr_SetString(tstate, PyExc_ValueError,
919
0
                         "code that returns a value is not a script");
920
0
        return -1;
921
0
    }
922
0
    return 0;
923
0
}
924
925
static int
926
get_script_xidata(PyThreadState *tstate, PyObject *obj, int pure,
927
                  _PyXIData_t *xidata)
928
0
{
929
    // Get the corresponding code object.
930
0
    PyObject *code = NULL;
931
0
    int checked = 0;
932
0
    if (PyCode_Check(obj)) {
933
0
        code = obj;
934
0
        Py_INCREF(code);
935
0
    }
936
0
    else if (PyFunction_Check(obj)) {
937
0
        code = PyFunction_GET_CODE(obj);
938
0
        assert(code != NULL);
939
0
        Py_INCREF(code);
940
0
        if (pure) {
941
0
            if (_PyFunction_VerifyStateless(tstate, obj) < 0) {
942
0
                goto error;
943
0
            }
944
0
            checked = 1;
945
0
        }
946
0
    }
947
0
    else {
948
0
        const char *filename = "<script>";
949
0
        int optimize = 0;
950
0
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
951
0
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
952
0
        PyObject *ref = NULL;
953
0
        const char *script = _Py_SourceAsString(obj, "???", "???", &cf, &ref);
954
0
        if (script == NULL) {
955
0
            if (!_PyObject_SupportedAsScript(obj)) {
956
                // We discard the raised exception.
957
0
                _PyErr_Format(tstate, PyExc_TypeError,
958
0
                              "unsupported script %R", obj);
959
0
            }
960
0
            goto error;
961
0
        }
962
#ifdef Py_GIL_DISABLED
963
        // Don't immortalize code constants to avoid memory leaks.
964
        ((_PyThreadStateImpl *)tstate)->suppress_co_const_immortalization++;
965
#endif
966
0
        code = Py_CompileStringExFlags(
967
0
                    script, filename, Py_file_input, &cf, optimize);
968
#ifdef Py_GIL_DISABLED
969
        ((_PyThreadStateImpl *)tstate)->suppress_co_const_immortalization--;
970
#endif
971
0
        Py_XDECREF(ref);
972
0
        if (code == NULL) {
973
0
            goto error;
974
0
        }
975
        // Compiled text can't have args or any return statements,
976
        // nor be a closure.  It can use globals though.
977
0
        if (!pure) {
978
            // We don't need to check for globals either.
979
0
            checked = 1;
980
0
        }
981
0
    }
982
983
    // Make sure it's actually a script.
984
0
    if (verify_script(tstate, (PyCodeObject *)code, checked, pure) < 0) {
985
0
        goto error;
986
0
    }
987
988
    // Convert the code object.
989
0
    int res = _PyCode_GetXIData(tstate, code, xidata);
990
0
    Py_DECREF(code);
991
0
    if (res < 0) {
992
0
        return -1;
993
0
    }
994
0
    return 0;
995
996
0
error:
997
0
    Py_XDECREF(code);
998
0
    PyObject *cause = _PyErr_GetRaisedException(tstate);
999
0
    assert(cause != NULL);
1000
0
    _set_xid_lookup_failure(
1001
0
                tstate, NULL, "object not a valid script", cause);
1002
0
    Py_DECREF(cause);
1003
0
    return -1;
1004
0
}
1005
1006
int
1007
_PyCode_GetScriptXIData(PyThreadState *tstate,
1008
                        PyObject *obj, _PyXIData_t *xidata)
1009
0
{
1010
0
    return get_script_xidata(tstate, obj, 0, xidata);
1011
0
}
1012
1013
int
1014
_PyCode_GetPureScriptXIData(PyThreadState *tstate,
1015
                            PyObject *obj, _PyXIData_t *xidata)
1016
0
{
1017
0
    return get_script_xidata(tstate, obj, 1, xidata);
1018
0
}
1019
1020
1021
/* using cross-interpreter data */
1022
1023
PyObject *
1024
_PyXIData_NewObject(_PyXIData_t *xidata)
1025
0
{
1026
0
    return xidata->new_object(xidata);
1027
0
}
1028
1029
static int
1030
_call_clear_xidata(void *data)
1031
0
{
1032
0
    _xidata_clear((_PyXIData_t *)data);
1033
0
    return 0;
1034
0
}
1035
1036
static int
1037
_xidata_release(_PyXIData_t *xidata, int rawfree)
1038
0
{
1039
0
    if ((xidata->data == NULL || xidata->free == NULL) && xidata->obj == NULL) {
1040
        // Nothing to release!
1041
0
        if (rawfree) {
1042
0
            PyMem_RawFree(xidata);
1043
0
        }
1044
0
        else {
1045
0
            xidata->data = NULL;
1046
0
        }
1047
0
        return 0;
1048
0
    }
1049
1050
    // Switch to the original interpreter.
1051
0
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(
1052
0
                                        _PyXIData_INTERPID(xidata));
1053
0
    if (interp == NULL) {
1054
        // The interpreter was already destroyed.
1055
        // This function shouldn't have been called.
1056
        // XXX Someone leaked some memory...
1057
0
        assert(PyErr_Occurred());
1058
0
        if (rawfree) {
1059
0
            PyMem_RawFree(xidata);
1060
0
        }
1061
0
        return -1;
1062
0
    }
1063
1064
    // "Release" the data and/or the object.
1065
0
    if (rawfree) {
1066
0
        return _Py_CallInInterpreterAndRawFree(interp, _call_clear_xidata, xidata);
1067
0
    }
1068
0
    else {
1069
0
        return _Py_CallInInterpreter(interp, _call_clear_xidata, xidata);
1070
0
    }
1071
0
}
1072
1073
int
1074
_PyXIData_Release(_PyXIData_t *xidata)
1075
0
{
1076
0
    return _xidata_release(xidata, 0);
1077
0
}
1078
1079
int
1080
_PyXIData_ReleaseAndRawFree(_PyXIData_t *xidata)
1081
0
{
1082
0
    return _xidata_release(xidata, 1);
1083
0
}
1084
1085
1086
/*************************/
1087
/* convenience utilities */
1088
/*************************/
1089
1090
static char *
1091
_copy_string_obj_raw(PyObject *strobj, Py_ssize_t *p_size)
1092
0
{
1093
0
    Py_ssize_t size = -1;
1094
0
    const char *str = PyUnicode_AsUTF8AndSize(strobj, &size);
1095
0
    if (str == NULL) {
1096
0
        return NULL;
1097
0
    }
1098
1099
0
    if (size != (Py_ssize_t)strlen(str)) {
1100
0
        PyErr_SetString(PyExc_ValueError, "found embedded NULL character");
1101
0
        return NULL;
1102
0
    }
1103
1104
0
    char *copied = PyMem_RawMalloc(size+1);
1105
0
    if (copied == NULL) {
1106
0
        PyErr_NoMemory();
1107
0
        return NULL;
1108
0
    }
1109
0
    strcpy(copied, str);
1110
0
    if (p_size != NULL) {
1111
0
        *p_size = size;
1112
0
    }
1113
0
    return copied;
1114
0
}
1115
1116
1117
static int
1118
_convert_exc_to_TracebackException(PyObject *exc, PyObject **p_tbexc)
1119
0
{
1120
0
    PyObject *args = NULL;
1121
0
    PyObject *kwargs = NULL;
1122
0
    PyObject *create = NULL;
1123
1124
    // This is inspired by _PyErr_Display().
1125
0
    PyObject *tbexc_type = PyImport_ImportModuleAttrString(
1126
0
        "traceback",
1127
0
        "TracebackException");
1128
0
    if (tbexc_type == NULL) {
1129
0
        return -1;
1130
0
    }
1131
0
    create = PyObject_GetAttrString(tbexc_type, "from_exception");
1132
0
    Py_DECREF(tbexc_type);
1133
0
    if (create == NULL) {
1134
0
        return -1;
1135
0
    }
1136
1137
0
    args = PyTuple_Pack(1, exc);
1138
0
    if (args == NULL) {
1139
0
        goto error;
1140
0
    }
1141
1142
0
    kwargs = PyDict_New();
1143
0
    if (kwargs == NULL) {
1144
0
        goto error;
1145
0
    }
1146
0
    if (PyDict_SetItemString(kwargs, "save_exc_type", Py_False) < 0) {
1147
0
        goto error;
1148
0
    }
1149
0
    if (PyDict_SetItemString(kwargs, "lookup_lines", Py_False) < 0) {
1150
0
        goto error;
1151
0
    }
1152
1153
0
    PyObject *tbexc = PyObject_Call(create, args, kwargs);
1154
0
    if (tbexc == NULL) {
1155
0
        goto error;
1156
0
    }
1157
0
    Py_DECREF(args);
1158
0
    Py_DECREF(kwargs);
1159
0
    Py_DECREF(create);
1160
1161
0
    *p_tbexc = tbexc;
1162
0
    return 0;
1163
1164
0
error:
1165
0
    Py_XDECREF(args);
1166
0
    Py_XDECREF(kwargs);
1167
0
    Py_XDECREF(create);
1168
0
    return -1;
1169
0
}
1170
1171
// We accommodate backports here.
1172
#ifndef _Py_EMPTY_STR
1173
0
# define _Py_EMPTY_STR &_Py_STR(empty)
1174
#endif
1175
1176
static const char *
1177
_format_TracebackException(PyObject *tbexc)
1178
0
{
1179
0
    PyObject *lines = PyObject_CallMethod(tbexc, "format", NULL);
1180
0
    if (lines == NULL) {
1181
0
        return NULL;
1182
0
    }
1183
0
    assert(_Py_EMPTY_STR != NULL);
1184
0
    PyObject *formatted_obj = PyUnicode_Join(_Py_EMPTY_STR, lines);
1185
0
    Py_DECREF(lines);
1186
0
    if (formatted_obj == NULL) {
1187
0
        return NULL;
1188
0
    }
1189
1190
0
    Py_ssize_t size = -1;
1191
0
    char *formatted = _copy_string_obj_raw(formatted_obj, &size);
1192
0
    Py_DECREF(formatted_obj);
1193
0
    if (formatted == NULL || size == 0) {
1194
0
        return formatted;
1195
0
    }
1196
0
    assert(formatted[size] == '\0');
1197
    // Remove a trailing newline if needed.
1198
0
    if (formatted[size-1] == '\n') {
1199
0
        formatted[size-1] = '\0';
1200
0
    }
1201
0
    return formatted;
1202
0
}
1203
1204
1205
static int
1206
_release_xid_data(_PyXIData_t *xidata, int rawfree)
1207
0
{
1208
0
    PyObject *exc = PyErr_GetRaisedException();
1209
0
    int res = rawfree
1210
0
        ? _PyXIData_ReleaseAndRawFree(xidata)
1211
0
        : _PyXIData_Release(xidata);
1212
0
    if (res < 0) {
1213
        /* The owning interpreter is already destroyed. */
1214
0
        _PyXIData_Clear(NULL, xidata);
1215
        // XXX Emit a warning?
1216
0
        PyErr_Clear();
1217
0
    }
1218
0
    PyErr_SetRaisedException(exc);
1219
0
    return res;
1220
0
}
1221
1222
1223
/***********************/
1224
/* exception snapshots */
1225
/***********************/
1226
1227
static int
1228
_excinfo_init_type_from_exception(struct _excinfo_type *info, PyObject *exc)
1229
0
{
1230
    /* Note that this copies directly rather than into an intermediate
1231
       struct and does not clear on error.  If we need that then we
1232
       should have a separate function to wrap this one
1233
       and do all that there. */
1234
0
    PyObject *strobj = NULL;
1235
1236
0
    PyTypeObject *type = Py_TYPE(exc);
1237
0
    if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
1238
0
        assert(_Py_IsImmortal((PyObject *)type));
1239
0
        info->builtin = type;
1240
0
    }
1241
0
    else {
1242
        // Only builtin types are preserved.
1243
0
        info->builtin = NULL;
1244
0
    }
1245
1246
    // __name__
1247
0
    strobj = PyType_GetName(type);
1248
0
    if (strobj == NULL) {
1249
0
        return -1;
1250
0
    }
1251
0
    info->name = _copy_string_obj_raw(strobj, NULL);
1252
0
    Py_DECREF(strobj);
1253
0
    if (info->name == NULL) {
1254
0
        return -1;
1255
0
    }
1256
1257
    // __qualname__
1258
0
    strobj = PyType_GetQualName(type);
1259
0
    if (strobj == NULL) {
1260
0
        return -1;
1261
0
    }
1262
0
    info->qualname = _copy_string_obj_raw(strobj, NULL);
1263
0
    Py_DECREF(strobj);
1264
0
    if (info->qualname == NULL) {
1265
0
        return -1;
1266
0
    }
1267
1268
    // __module__
1269
0
    strobj = PyType_GetModuleName(type);
1270
0
    if (strobj == NULL) {
1271
0
        return -1;
1272
0
    }
1273
0
    info->module = _copy_string_obj_raw(strobj, NULL);
1274
0
    Py_DECREF(strobj);
1275
0
    if (info->module == NULL) {
1276
0
        return -1;
1277
0
    }
1278
1279
0
    return 0;
1280
0
}
1281
1282
static int
1283
_excinfo_init_type_from_object(struct _excinfo_type *info, PyObject *exctype)
1284
0
{
1285
0
    PyObject *strobj = NULL;
1286
1287
    // __name__
1288
0
    strobj = PyObject_GetAttrString(exctype, "__name__");
1289
0
    if (strobj == NULL) {
1290
0
        return -1;
1291
0
    }
1292
0
    info->name = _copy_string_obj_raw(strobj, NULL);
1293
0
    Py_DECREF(strobj);
1294
0
    if (info->name == NULL) {
1295
0
        return -1;
1296
0
    }
1297
1298
    // __qualname__
1299
0
    strobj = PyObject_GetAttrString(exctype, "__qualname__");
1300
0
    if (strobj == NULL) {
1301
0
        return -1;
1302
0
    }
1303
0
    info->qualname = _copy_string_obj_raw(strobj, NULL);
1304
0
    Py_DECREF(strobj);
1305
0
    if (info->qualname == NULL) {
1306
0
        return -1;
1307
0
    }
1308
1309
    // __module__
1310
0
    strobj = PyObject_GetAttrString(exctype, "__module__");
1311
0
    if (strobj == NULL) {
1312
0
        return -1;
1313
0
    }
1314
0
    info->module = _copy_string_obj_raw(strobj, NULL);
1315
0
    Py_DECREF(strobj);
1316
0
    if (info->module == NULL) {
1317
0
        return -1;
1318
0
    }
1319
1320
0
    return 0;
1321
0
}
1322
1323
static void
1324
_excinfo_clear_type(struct _excinfo_type *info)
1325
0
{
1326
0
    if (info->builtin != NULL) {
1327
0
        assert(info->builtin->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
1328
0
        assert(_Py_IsImmortal((PyObject *)info->builtin));
1329
0
    }
1330
0
    if (info->name != NULL) {
1331
0
        PyMem_RawFree((void *)info->name);
1332
0
    }
1333
0
    if (info->qualname != NULL) {
1334
0
        PyMem_RawFree((void *)info->qualname);
1335
0
    }
1336
0
    if (info->module != NULL) {
1337
0
        PyMem_RawFree((void *)info->module);
1338
0
    }
1339
0
    *info = (struct _excinfo_type){NULL};
1340
0
}
1341
1342
static void
1343
_excinfo_normalize_type(struct _excinfo_type *info,
1344
                        const char **p_module, const char **p_qualname)
1345
0
{
1346
0
    if (info->name == NULL) {
1347
0
        assert(info->builtin == NULL);
1348
0
        assert(info->qualname == NULL);
1349
0
        assert(info->module == NULL);
1350
        // This is inspired by TracebackException.format_exception_only().
1351
0
        *p_module = NULL;
1352
0
        *p_qualname = NULL;
1353
0
        return;
1354
0
    }
1355
1356
0
    const char *module = info->module;
1357
0
    const char *qualname = info->qualname;
1358
0
    if (qualname == NULL) {
1359
0
        qualname = info->name;
1360
0
    }
1361
0
    assert(module != NULL);
1362
0
    if (strcmp(module, "builtins") == 0) {
1363
0
        module = NULL;
1364
0
    }
1365
0
    else if (strcmp(module, "__main__") == 0) {
1366
0
        module = NULL;
1367
0
    }
1368
0
    *p_qualname = qualname;
1369
0
    *p_module = module;
1370
0
}
1371
1372
static int
1373
excinfo_is_set(_PyXI_excinfo *info)
1374
0
{
1375
0
    return info->type.name != NULL || info->msg != NULL;
1376
0
}
1377
1378
static void
1379
_PyXI_excinfo_clear(_PyXI_excinfo *info)
1380
0
{
1381
0
    _excinfo_clear_type(&info->type);
1382
0
    if (info->msg != NULL) {
1383
0
        PyMem_RawFree((void *)info->msg);
1384
0
    }
1385
0
    if (info->errdisplay != NULL) {
1386
0
        PyMem_RawFree((void *)info->errdisplay);
1387
0
    }
1388
0
    *info = (_PyXI_excinfo){{NULL}};
1389
0
}
1390
1391
PyObject *
1392
_PyXI_excinfo_format(_PyXI_excinfo *info)
1393
0
{
1394
0
    const char *module, *qualname;
1395
0
    _excinfo_normalize_type(&info->type, &module, &qualname);
1396
0
    if (qualname != NULL) {
1397
0
        if (module != NULL) {
1398
0
            if (info->msg != NULL) {
1399
0
                return PyUnicode_FromFormat("%s.%s: %s",
1400
0
                                            module, qualname, info->msg);
1401
0
            }
1402
0
            else {
1403
0
                return PyUnicode_FromFormat("%s.%s", module, qualname);
1404
0
            }
1405
0
        }
1406
0
        else {
1407
0
            if (info->msg != NULL) {
1408
0
                return PyUnicode_FromFormat("%s: %s", qualname, info->msg);
1409
0
            }
1410
0
            else {
1411
0
                return PyUnicode_FromString(qualname);
1412
0
            }
1413
0
        }
1414
0
    }
1415
0
    else if (info->msg != NULL) {
1416
0
        return PyUnicode_FromString(info->msg);
1417
0
    }
1418
0
    else {
1419
0
        Py_RETURN_NONE;
1420
0
    }
1421
0
}
1422
1423
static const char *
1424
_PyXI_excinfo_InitFromException(_PyXI_excinfo *info, PyObject *exc)
1425
0
{
1426
0
    assert(exc != NULL);
1427
1428
0
    if (PyErr_GivenExceptionMatches(exc, PyExc_MemoryError)) {
1429
0
        _PyXI_excinfo_clear(info);
1430
0
        return NULL;
1431
0
    }
1432
0
    const char *failure = NULL;
1433
1434
0
    if (_excinfo_init_type_from_exception(&info->type, exc) < 0) {
1435
0
        failure = "error while initializing exception type snapshot";
1436
0
        goto error;
1437
0
    }
1438
1439
    // Extract the exception message.
1440
0
    PyObject *msgobj = PyObject_Str(exc);
1441
0
    if (msgobj == NULL) {
1442
0
        failure = "error while formatting exception";
1443
0
        goto error;
1444
0
    }
1445
0
    info->msg = _copy_string_obj_raw(msgobj, NULL);
1446
0
    Py_DECREF(msgobj);
1447
0
    if (info->msg == NULL) {
1448
0
        failure = "error while copying exception message";
1449
0
        goto error;
1450
0
    }
1451
1452
    // Pickle a traceback.TracebackException.
1453
0
    PyObject *tbexc = NULL;
1454
0
    if (_convert_exc_to_TracebackException(exc, &tbexc) < 0) {
1455
#ifdef Py_DEBUG
1456
        PyErr_FormatUnraisable("Exception ignored while creating TracebackException");
1457
#endif
1458
0
        PyErr_Clear();
1459
0
    }
1460
0
    else {
1461
0
        info->errdisplay = _format_TracebackException(tbexc);
1462
0
        Py_DECREF(tbexc);
1463
0
        if (info->errdisplay == NULL) {
1464
#ifdef Py_DEBUG
1465
            PyErr_FormatUnraisable("Exception ignored while formatting TracebackException");
1466
#endif
1467
0
            PyErr_Clear();
1468
0
        }
1469
0
    }
1470
1471
0
    return NULL;
1472
1473
0
error:
1474
0
    assert(failure != NULL);
1475
0
    _PyXI_excinfo_clear(info);
1476
0
    return failure;
1477
0
}
1478
1479
static const char *
1480
_PyXI_excinfo_InitFromObject(_PyXI_excinfo *info, PyObject *obj)
1481
0
{
1482
0
    const char *failure = NULL;
1483
1484
0
    PyObject *exctype = PyObject_GetAttrString(obj, "type");
1485
0
    if (exctype == NULL) {
1486
0
        failure = "exception snapshot missing 'type' attribute";
1487
0
        goto error;
1488
0
    }
1489
0
    int res = _excinfo_init_type_from_object(&info->type, exctype);
1490
0
    Py_DECREF(exctype);
1491
0
    if (res < 0) {
1492
0
        failure = "error while initializing exception type snapshot";
1493
0
        goto error;
1494
0
    }
1495
1496
    // Extract the exception message.
1497
0
    PyObject *msgobj = PyObject_GetAttrString(obj, "msg");
1498
0
    if (msgobj == NULL) {
1499
0
        failure = "exception snapshot missing 'msg' attribute";
1500
0
        goto error;
1501
0
    }
1502
0
    info->msg = _copy_string_obj_raw(msgobj, NULL);
1503
0
    Py_DECREF(msgobj);
1504
0
    if (info->msg == NULL) {
1505
0
        failure = "error while copying exception message";
1506
0
        goto error;
1507
0
    }
1508
1509
    // Pickle a traceback.TracebackException.
1510
0
    PyObject *errdisplay = PyObject_GetAttrString(obj, "errdisplay");
1511
0
    if (errdisplay == NULL) {
1512
0
        failure = "exception snapshot missing 'errdisplay' attribute";
1513
0
        goto error;
1514
0
    }
1515
0
    info->errdisplay = _copy_string_obj_raw(errdisplay, NULL);
1516
0
    Py_DECREF(errdisplay);
1517
0
    if (info->errdisplay == NULL) {
1518
0
        failure = "error while copying exception error display";
1519
0
        goto error;
1520
0
    }
1521
1522
0
    return NULL;
1523
1524
0
error:
1525
0
    assert(failure != NULL);
1526
0
    _PyXI_excinfo_clear(info);
1527
0
    return failure;
1528
0
}
1529
1530
static void
1531
_PyXI_excinfo_Apply(_PyXI_excinfo *info, PyObject *exctype)
1532
0
{
1533
0
    PyObject *tbexc = NULL;
1534
0
    if (info->errdisplay != NULL) {
1535
0
        tbexc = PyUnicode_FromString(info->errdisplay);
1536
0
        if (tbexc == NULL) {
1537
0
            PyErr_Clear();
1538
0
        }
1539
0
        else {
1540
0
            PyErr_SetObject(exctype, tbexc);
1541
0
            Py_DECREF(tbexc);
1542
0
            return;
1543
0
        }
1544
0
    }
1545
1546
0
    PyObject *formatted = _PyXI_excinfo_format(info);
1547
0
    PyErr_SetObject(exctype, formatted);
1548
0
    Py_XDECREF(formatted);
1549
1550
0
    if (tbexc != NULL) {
1551
0
        PyObject *exc = PyErr_GetRaisedException();
1552
0
        if (PyObject_SetAttrString(exc, "_errdisplay", tbexc) < 0) {
1553
#ifdef Py_DEBUG
1554
            PyErr_FormatUnraisable("Exception ignored while "
1555
                                   "setting _errdisplay");
1556
#endif
1557
0
            PyErr_Clear();
1558
0
        }
1559
0
        Py_DECREF(tbexc);
1560
0
        PyErr_SetRaisedException(exc);
1561
0
    }
1562
0
}
1563
1564
static PyObject *
1565
_PyXI_excinfo_TypeAsObject(_PyXI_excinfo *info)
1566
0
{
1567
0
    PyObject *ns = _PyNamespace_New(NULL);
1568
0
    if (ns == NULL) {
1569
0
        return NULL;
1570
0
    }
1571
0
    int empty = 1;
1572
1573
0
    if (info->type.name != NULL) {
1574
0
        PyObject *name = PyUnicode_FromString(info->type.name);
1575
0
        if (name == NULL) {
1576
0
            goto error;
1577
0
        }
1578
0
        int res = PyObject_SetAttrString(ns, "__name__", name);
1579
0
        Py_DECREF(name);
1580
0
        if (res < 0) {
1581
0
            goto error;
1582
0
        }
1583
0
        empty = 0;
1584
0
    }
1585
1586
0
    if (info->type.qualname != NULL) {
1587
0
        PyObject *qualname = PyUnicode_FromString(info->type.qualname);
1588
0
        if (qualname == NULL) {
1589
0
            goto error;
1590
0
        }
1591
0
        int res = PyObject_SetAttrString(ns, "__qualname__", qualname);
1592
0
        Py_DECREF(qualname);
1593
0
        if (res < 0) {
1594
0
            goto error;
1595
0
        }
1596
0
        empty = 0;
1597
0
    }
1598
1599
0
    if (info->type.module != NULL) {
1600
0
        PyObject *module = PyUnicode_FromString(info->type.module);
1601
0
        if (module == NULL) {
1602
0
            goto error;
1603
0
        }
1604
0
        int res = PyObject_SetAttrString(ns, "__module__", module);
1605
0
        Py_DECREF(module);
1606
0
        if (res < 0) {
1607
0
            goto error;
1608
0
        }
1609
0
        empty = 0;
1610
0
    }
1611
1612
0
    if (empty) {
1613
0
        Py_CLEAR(ns);
1614
0
    }
1615
1616
0
    return ns;
1617
1618
0
error:
1619
0
    Py_DECREF(ns);
1620
0
    return NULL;
1621
0
}
1622
1623
static PyObject *
1624
_PyXI_excinfo_AsObject(_PyXI_excinfo *info)
1625
0
{
1626
0
    PyObject *ns = _PyNamespace_New(NULL);
1627
0
    if (ns == NULL) {
1628
0
        return NULL;
1629
0
    }
1630
0
    int res;
1631
1632
0
    PyObject *type = _PyXI_excinfo_TypeAsObject(info);
1633
0
    if (type == NULL) {
1634
0
        if (PyErr_Occurred()) {
1635
0
            goto error;
1636
0
        }
1637
0
        type = Py_NewRef(Py_None);
1638
0
    }
1639
0
    res = PyObject_SetAttrString(ns, "type", type);
1640
0
    Py_DECREF(type);
1641
0
    if (res < 0) {
1642
0
        goto error;
1643
0
    }
1644
1645
0
    PyObject *msg = info->msg != NULL
1646
0
        ? PyUnicode_FromString(info->msg)
1647
0
        : Py_NewRef(Py_None);
1648
0
    if (msg == NULL) {
1649
0
        goto error;
1650
0
    }
1651
0
    res = PyObject_SetAttrString(ns, "msg", msg);
1652
0
    Py_DECREF(msg);
1653
0
    if (res < 0) {
1654
0
        goto error;
1655
0
    }
1656
1657
0
    PyObject *formatted = _PyXI_excinfo_format(info);
1658
0
    if (formatted == NULL) {
1659
0
        goto error;
1660
0
    }
1661
0
    res = PyObject_SetAttrString(ns, "formatted", formatted);
1662
0
    Py_DECREF(formatted);
1663
0
    if (res < 0) {
1664
0
        goto error;
1665
0
    }
1666
1667
0
    if (info->errdisplay != NULL) {
1668
0
        PyObject *tbexc = PyUnicode_FromString(info->errdisplay);
1669
0
        if (tbexc == NULL) {
1670
0
            PyErr_Clear();
1671
0
        }
1672
0
        else {
1673
0
            res = PyObject_SetAttrString(ns, "errdisplay", tbexc);
1674
0
            Py_DECREF(tbexc);
1675
0
            if (res < 0) {
1676
0
                goto error;
1677
0
            }
1678
0
        }
1679
0
    }
1680
1681
0
    return ns;
1682
1683
0
error:
1684
0
    Py_DECREF(ns);
1685
0
    return NULL;
1686
0
}
1687
1688
1689
_PyXI_excinfo *
1690
_PyXI_NewExcInfo(PyObject *exc)
1691
0
{
1692
0
    assert(!PyErr_Occurred());
1693
0
    if (exc == NULL || exc == Py_None) {
1694
0
        PyErr_SetString(PyExc_ValueError, "missing exc");
1695
0
        return NULL;
1696
0
    }
1697
0
    _PyXI_excinfo *info = PyMem_RawCalloc(1, sizeof(_PyXI_excinfo));
1698
0
    if (info == NULL) {
1699
0
        PyErr_NoMemory();
1700
0
        return NULL;
1701
0
    }
1702
0
    const char *failure;
1703
0
    if (PyExceptionInstance_Check(exc) || PyExceptionClass_Check(exc)) {
1704
0
        failure = _PyXI_excinfo_InitFromException(info, exc);
1705
0
    }
1706
0
    else {
1707
0
        failure = _PyXI_excinfo_InitFromObject(info, exc);
1708
0
    }
1709
0
    if (failure != NULL) {
1710
0
        PyMem_RawFree(info);
1711
0
        set_exc_with_cause(PyExc_Exception, failure);
1712
0
        return NULL;
1713
0
    }
1714
0
    return info;
1715
0
}
1716
1717
void
1718
_PyXI_FreeExcInfo(_PyXI_excinfo *info)
1719
0
{
1720
0
    assert(info != NULL);
1721
0
    _PyXI_excinfo_clear(info);
1722
0
    PyMem_RawFree(info);
1723
0
}
1724
1725
PyObject *
1726
_PyXI_FormatExcInfo(_PyXI_excinfo *info)
1727
0
{
1728
0
    return _PyXI_excinfo_format(info);
1729
0
}
1730
1731
PyObject *
1732
_PyXI_ExcInfoAsObject(_PyXI_excinfo *info)
1733
0
{
1734
0
    return _PyXI_excinfo_AsObject(info);
1735
0
}
1736
1737
1738
/***************************/
1739
/* short-term data sharing */
1740
/***************************/
1741
1742
/* error codes */
1743
1744
static int
1745
_PyXI_ApplyErrorCode(_PyXI_errcode code, PyInterpreterState *interp)
1746
0
{
1747
0
    PyThreadState *tstate = _PyThreadState_GET();
1748
1749
0
    assert(!PyErr_Occurred());
1750
0
    assert(code != _PyXI_ERR_NO_ERROR);
1751
0
    assert(code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1752
0
    switch (code) {
1753
0
    case _PyXI_ERR_OTHER:
1754
        // XXX msg?
1755
0
        PyErr_SetNone(PyExc_InterpreterError);
1756
0
        break;
1757
0
    case _PyXI_ERR_NO_MEMORY:
1758
0
        PyErr_NoMemory();
1759
0
        break;
1760
0
    case _PyXI_ERR_ALREADY_RUNNING:
1761
0
        assert(interp != NULL);
1762
0
        _PyErr_SetInterpreterAlreadyRunning();
1763
0
        break;
1764
0
    case _PyXI_ERR_MAIN_NS_FAILURE:
1765
0
        PyErr_SetString(PyExc_InterpreterError,
1766
0
                        "failed to get __main__ namespace");
1767
0
        break;
1768
0
    case _PyXI_ERR_APPLY_NS_FAILURE:
1769
0
        PyErr_SetString(PyExc_InterpreterError,
1770
0
                        "failed to apply namespace to __main__");
1771
0
        break;
1772
0
    case _PyXI_ERR_PRESERVE_FAILURE:
1773
0
        PyErr_SetString(PyExc_InterpreterError,
1774
0
                        "failed to preserve objects across session");
1775
0
        break;
1776
0
    case _PyXI_ERR_EXC_PROPAGATION_FAILURE:
1777
0
        PyErr_SetString(PyExc_InterpreterError,
1778
0
                        "failed to transfer exception between interpreters");
1779
0
        break;
1780
0
    case _PyXI_ERR_NOT_SHAREABLE:
1781
0
        _set_xid_lookup_failure(tstate, NULL, NULL, NULL);
1782
0
        break;
1783
0
    default:
1784
#ifdef Py_DEBUG
1785
        Py_FatalError("unsupported error code");
1786
#else
1787
0
        PyErr_Format(PyExc_RuntimeError, "unsupported error code %d", code);
1788
0
#endif
1789
0
    }
1790
0
    assert(PyErr_Occurred());
1791
0
    return -1;
1792
0
}
1793
1794
/* basic failure info */
1795
1796
struct xi_failure {
1797
    // The kind of error to propagate.
1798
    _PyXI_errcode code;
1799
    // The propagated message.
1800
    const char *msg;
1801
    int msg_owned;
1802
};  // _PyXI_failure
1803
1804
0
#define XI_FAILURE_INIT (_PyXI_failure){ .code = _PyXI_ERR_NO_ERROR }
1805
1806
static void
1807
clear_xi_failure(_PyXI_failure *failure)
1808
0
{
1809
0
    if (failure->msg != NULL && failure->msg_owned) {
1810
0
        PyMem_RawFree((void*)failure->msg);
1811
0
    }
1812
0
    *failure = XI_FAILURE_INIT;
1813
0
}
1814
1815
static void
1816
copy_xi_failure(_PyXI_failure *dest, _PyXI_failure *src)
1817
0
{
1818
0
    *dest = *src;
1819
0
    dest->msg_owned = 0;
1820
0
}
1821
1822
_PyXI_failure *
1823
_PyXI_NewFailure(void)
1824
0
{
1825
0
    _PyXI_failure *failure = PyMem_RawMalloc(sizeof(_PyXI_failure));
1826
0
    if (failure == NULL) {
1827
0
        PyErr_NoMemory();
1828
0
        return NULL;
1829
0
    }
1830
0
    *failure = XI_FAILURE_INIT;
1831
0
    return failure;
1832
0
}
1833
1834
void
1835
_PyXI_FreeFailure(_PyXI_failure *failure)
1836
0
{
1837
0
    clear_xi_failure(failure);
1838
0
    PyMem_RawFree(failure);
1839
0
}
1840
1841
_PyXI_errcode
1842
_PyXI_GetFailureCode(_PyXI_failure *failure)
1843
0
{
1844
0
    if (failure == NULL) {
1845
0
        return _PyXI_ERR_NO_ERROR;
1846
0
    }
1847
0
    return failure->code;
1848
0
}
1849
1850
void
1851
_PyXI_InitFailureUTF8(_PyXI_failure *failure,
1852
                      _PyXI_errcode code, const char *msg)
1853
0
{
1854
0
    *failure = (_PyXI_failure){
1855
0
        .code = code,
1856
0
        .msg = msg,
1857
0
        .msg_owned = 0,
1858
0
    };
1859
0
}
1860
1861
int
1862
_PyXI_InitFailure(_PyXI_failure *failure, _PyXI_errcode code, PyObject *obj)
1863
0
{
1864
0
    *failure = (_PyXI_failure){
1865
0
        .code = code,
1866
0
        .msg = NULL,
1867
0
        .msg_owned = 0,
1868
0
    };
1869
0
    if (obj == NULL) {
1870
0
        return 0;
1871
0
    }
1872
1873
0
    PyObject *msgobj = PyObject_Str(obj);
1874
0
    if (msgobj == NULL) {
1875
0
        return -1;
1876
0
    }
1877
    // This will leak if not paired with clear_xi_failure().
1878
    // That happens automatically in _capture_current_exception().
1879
0
    const char *msg = _copy_string_obj_raw(msgobj, NULL);
1880
0
    Py_DECREF(msgobj);
1881
0
    if (msg == NULL) {
1882
0
        return -1;
1883
0
    }
1884
0
    *failure = (_PyXI_failure){
1885
0
        .code = code,
1886
0
        .msg = msg,
1887
0
        .msg_owned = 1,
1888
0
    };
1889
0
    return 0;
1890
0
}
1891
1892
/* shared exceptions */
1893
1894
typedef struct {
1895
    // The originating interpreter.
1896
    PyInterpreterState *interp;
1897
    // The error to propagate, if different from the uncaught exception.
1898
    _PyXI_failure *override;
1899
    _PyXI_failure _override;
1900
    // The exception information to propagate, if applicable.
1901
    // This is populated only for some error codes,
1902
    // but always for _PyXI_ERR_UNCAUGHT_EXCEPTION.
1903
    _PyXI_excinfo uncaught;
1904
} _PyXI_error;
1905
1906
static void
1907
xi_error_clear(_PyXI_error *err)
1908
0
{
1909
0
    err->interp = NULL;
1910
0
    if (err->override != NULL) {
1911
0
        clear_xi_failure(err->override);
1912
0
    }
1913
0
    _PyXI_excinfo_clear(&err->uncaught);
1914
0
}
1915
1916
static int
1917
xi_error_is_set(_PyXI_error *error)
1918
0
{
1919
0
    if (error->override != NULL) {
1920
0
        assert(error->override->code != _PyXI_ERR_NO_ERROR);
1921
0
        assert(error->override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION
1922
0
               || excinfo_is_set(&error->uncaught));
1923
0
        return 1;
1924
0
    }
1925
0
    return excinfo_is_set(&error->uncaught);
1926
0
}
1927
1928
static int
1929
xi_error_has_override(_PyXI_error *err)
1930
0
{
1931
0
    if (err->override == NULL) {
1932
0
        return 0;
1933
0
    }
1934
0
    return (err->override->code != _PyXI_ERR_NO_ERROR
1935
0
            && err->override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1936
0
}
1937
1938
static PyObject *
1939
xi_error_resolve_current_exc(PyThreadState *tstate,
1940
                             _PyXI_failure *override)
1941
0
{
1942
0
    assert(override == NULL || override->code != _PyXI_ERR_NO_ERROR);
1943
1944
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
1945
0
    if (exc == NULL) {
1946
0
        assert(override == NULL
1947
0
               || override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1948
0
    }
1949
0
    else if (override == NULL) {
1950
        // This is equivalent to _PyXI_ERR_UNCAUGHT_EXCEPTION.
1951
0
    }
1952
0
    else if (override->code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
1953
        // We want to actually capture the current exception.
1954
0
    }
1955
0
    else if (exc != NULL) {
1956
        // It might make sense to do similarly for other codes.
1957
0
        if (override->code == _PyXI_ERR_ALREADY_RUNNING) {
1958
            // We don't need the exception info.
1959
0
            Py_CLEAR(exc);
1960
0
        }
1961
        // ...else we want to actually capture the current exception.
1962
0
    }
1963
0
    return exc;
1964
0
}
1965
1966
static void
1967
xi_error_set_override(PyThreadState *tstate, _PyXI_error *err,
1968
                      _PyXI_failure *override)
1969
0
{
1970
0
    assert(err->override == NULL);
1971
0
    assert(override != NULL);
1972
0
    assert(override->code != _PyXI_ERR_NO_ERROR);
1973
    // Use xi_error_set_exc() instead of setting _PyXI_ERR_UNCAUGHT_EXCEPTION..
1974
0
    assert(override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1975
0
    err->override = &err->_override;
1976
    // The caller still owns override->msg.
1977
0
    copy_xi_failure(&err->_override, override);
1978
0
    err->interp = tstate->interp;
1979
0
}
1980
1981
static void
1982
xi_error_set_override_code(PyThreadState *tstate, _PyXI_error *err,
1983
                           _PyXI_errcode code)
1984
0
{
1985
0
    _PyXI_failure override = XI_FAILURE_INIT;
1986
0
    override.code = code;
1987
0
    xi_error_set_override(tstate, err, &override);
1988
0
}
1989
1990
static const char *
1991
xi_error_set_exc(PyThreadState *tstate, _PyXI_error *err, PyObject *exc)
1992
0
{
1993
0
    assert(!_PyErr_Occurred(tstate));
1994
0
    assert(!xi_error_is_set(err));
1995
0
    assert(err->override == NULL);
1996
0
    assert(err->interp == NULL);
1997
0
    assert(exc != NULL);
1998
0
    const char *failure =
1999
0
                _PyXI_excinfo_InitFromException(&err->uncaught, exc);
2000
0
    if (failure != NULL) {
2001
        // We failed to initialize err->uncaught.
2002
        // XXX Print the excobj/traceback?  Emit a warning?
2003
        // XXX Print the current exception/traceback?
2004
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_MemoryError)) {
2005
0
            xi_error_set_override_code(tstate, err, _PyXI_ERR_NO_MEMORY);
2006
0
        }
2007
0
        else {
2008
0
            xi_error_set_override_code(tstate, err, _PyXI_ERR_OTHER);
2009
0
        }
2010
0
        PyErr_Clear();
2011
0
    }
2012
0
    return failure;
2013
0
}
2014
2015
static PyObject *
2016
_PyXI_ApplyError(_PyXI_error *error, const char *failure)
2017
0
{
2018
0
    PyThreadState *tstate = PyThreadState_Get();
2019
2020
0
    if (failure != NULL) {
2021
0
        if (error->override != NULL
2022
0
            && error->override->code == _PyXI_ERR_NO_MEMORY)
2023
0
        {
2024
0
            PyErr_NoMemory();
2025
0
        }
2026
0
        else {
2027
0
            PyErr_SetString(PyExc_InterpreterError, failure);
2028
0
        }
2029
0
        xi_error_clear(error);
2030
0
        return NULL;
2031
0
    }
2032
2033
0
    _PyXI_errcode code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2034
0
    if (error->override != NULL) {
2035
0
        code = error->override->code;
2036
0
        assert(code != _PyXI_ERR_NO_ERROR);
2037
0
    }
2038
2039
0
    if (code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
2040
        // We will raise an exception that proxies the propagated exception.
2041
0
       return _PyXI_excinfo_AsObject(&error->uncaught);
2042
0
    }
2043
0
    else if (code == _PyXI_ERR_NOT_SHAREABLE) {
2044
        // Propagate the exception directly.
2045
0
        assert(!_PyErr_Occurred(tstate));
2046
0
        PyObject *cause = NULL;
2047
0
        if (excinfo_is_set(&error->uncaught)) {
2048
            // Maybe instead set a PyExc_ExceptionSnapshot as __cause__?
2049
            // That type doesn't exist currently
2050
            // but would look like interpreters.ExecutionFailed.
2051
0
            _PyXI_excinfo_Apply(&error->uncaught, PyExc_Exception);
2052
0
            cause = _PyErr_GetRaisedException(tstate);
2053
0
        }
2054
0
        const char *msg = error->override != NULL
2055
0
            ? error->override->msg
2056
0
            : error->uncaught.msg;
2057
0
        _set_xid_lookup_failure(tstate, NULL, msg, cause);
2058
0
        Py_XDECREF(cause);
2059
0
    }
2060
0
    else {
2061
        // Raise an exception corresponding to the code.
2062
0
        (void)_PyXI_ApplyErrorCode(code, error->interp);
2063
0
        assert(error->override == NULL || error->override->msg == NULL);
2064
0
        if (excinfo_is_set(&error->uncaught)) {
2065
            // __context__ will be set to a proxy of the propagated exception.
2066
            // (or use PyExc_ExceptionSnapshot like _PyXI_ERR_NOT_SHAREABLE?)
2067
0
            PyObject *exc = _PyErr_GetRaisedException(tstate);
2068
0
            _PyXI_excinfo_Apply(&error->uncaught, PyExc_InterpreterError);
2069
0
            PyObject *exc2 = _PyErr_GetRaisedException(tstate);
2070
0
            PyException_SetContext(exc, exc2);
2071
0
            _PyErr_SetRaisedException(tstate, exc);
2072
0
        }
2073
0
    }
2074
0
    assert(PyErr_Occurred());
2075
0
    return NULL;
2076
0
}
2077
2078
/* shared namespaces */
2079
2080
/* Shared namespaces are expected to have relatively short lifetimes.
2081
   This means dealloc of a shared namespace will normally happen "soon".
2082
   Namespace items hold cross-interpreter data, which must get released.
2083
   If the namespace/items are cleared in a different interpreter than
2084
   where the items' cross-interpreter data was set then that will cause
2085
   pending calls to be used to release the cross-interpreter data.
2086
   The tricky bit is that the pending calls can happen sufficiently
2087
   later that the namespace/items might already be deallocated.  This is
2088
   a problem if the cross-interpreter data is allocated as part of a
2089
   namespace item.  If that's the case then we must ensure the shared
2090
   namespace is only cleared/freed *after* that data has been released. */
2091
2092
typedef struct _sharednsitem {
2093
    const char *name;
2094
    _PyXIData_t *xidata;
2095
    // We could have a "PyXIData _data" field, so it would
2096
    // be allocated as part of the item and avoid an extra allocation.
2097
    // However, doing so adds a bunch of complexity because we must
2098
    // ensure the item isn't freed before a pending call might happen
2099
    // in a different interpreter to release the XI data.
2100
} _PyXI_namespace_item;
2101
2102
#ifndef NDEBUG
2103
static int
2104
_sharednsitem_is_initialized(_PyXI_namespace_item *item)
2105
{
2106
    if (item->name != NULL) {
2107
        return 1;
2108
    }
2109
    return 0;
2110
}
2111
#endif
2112
2113
static int
2114
_sharednsitem_init(_PyXI_namespace_item *item, PyObject *key)
2115
0
{
2116
0
    item->name = _copy_string_obj_raw(key, NULL);
2117
0
    if (item->name == NULL) {
2118
0
        assert(!_sharednsitem_is_initialized(item));
2119
0
        return -1;
2120
0
    }
2121
0
    item->xidata = NULL;
2122
0
    assert(_sharednsitem_is_initialized(item));
2123
0
    return 0;
2124
0
}
2125
2126
static int
2127
_sharednsitem_has_value(_PyXI_namespace_item *item, int64_t *p_interpid)
2128
0
{
2129
0
    if (item->xidata == NULL) {
2130
0
        return 0;
2131
0
    }
2132
0
    if (p_interpid != NULL) {
2133
0
        *p_interpid = _PyXIData_INTERPID(item->xidata);
2134
0
    }
2135
0
    return 1;
2136
0
}
2137
2138
static int
2139
_sharednsitem_set_value(_PyXI_namespace_item *item, PyObject *value,
2140
                        xidata_fallback_t fallback)
2141
0
{
2142
0
    assert(_sharednsitem_is_initialized(item));
2143
0
    assert(item->xidata == NULL);
2144
0
    item->xidata = _PyXIData_New();
2145
0
    if (item->xidata == NULL) {
2146
0
        return -1;
2147
0
    }
2148
0
    PyThreadState *tstate = PyThreadState_Get();
2149
0
    if (_PyObject_GetXIData(tstate, value, fallback, item->xidata) < 0) {
2150
0
        PyMem_RawFree(item->xidata);
2151
0
        item->xidata = NULL;
2152
        // The caller may want to propagate PyExc_NotShareableError
2153
        // if currently switched between interpreters.
2154
0
        return -1;
2155
0
    }
2156
0
    return 0;
2157
0
}
2158
2159
static void
2160
_sharednsitem_clear_value(_PyXI_namespace_item *item)
2161
0
{
2162
0
    _PyXIData_t *xidata = item->xidata;
2163
0
    if (xidata != NULL) {
2164
0
        item->xidata = NULL;
2165
0
        int rawfree = 1;
2166
0
        (void)_release_xid_data(xidata, rawfree);
2167
0
    }
2168
0
}
2169
2170
static void
2171
_sharednsitem_clear(_PyXI_namespace_item *item)
2172
0
{
2173
0
    if (item->name != NULL) {
2174
0
        PyMem_RawFree((void *)item->name);
2175
0
        item->name = NULL;
2176
0
    }
2177
0
    _sharednsitem_clear_value(item);
2178
0
}
2179
2180
static int
2181
_sharednsitem_copy_from_ns(struct _sharednsitem *item, PyObject *ns,
2182
                           xidata_fallback_t fallback)
2183
0
{
2184
0
    assert(item->name != NULL);
2185
0
    assert(item->xidata == NULL);
2186
0
    PyObject *value = PyDict_GetItemString(ns, item->name);  // borrowed
2187
0
    if (value == NULL) {
2188
0
        if (PyErr_Occurred()) {
2189
0
            return -1;
2190
0
        }
2191
        // When applied, this item will be set to the default (or fail).
2192
0
        return 0;
2193
0
    }
2194
0
    if (_sharednsitem_set_value(item, value, fallback) < 0) {
2195
0
        return -1;
2196
0
    }
2197
0
    return 0;
2198
0
}
2199
2200
static int
2201
_sharednsitem_apply(_PyXI_namespace_item *item, PyObject *ns, PyObject *dflt)
2202
0
{
2203
0
    PyObject *name = PyUnicode_FromString(item->name);
2204
0
    if (name == NULL) {
2205
0
        return -1;
2206
0
    }
2207
0
    PyObject *value;
2208
0
    if (item->xidata != NULL) {
2209
0
        value = _PyXIData_NewObject(item->xidata);
2210
0
        if (value == NULL) {
2211
0
            Py_DECREF(name);
2212
0
            return -1;
2213
0
        }
2214
0
    }
2215
0
    else {
2216
0
        value = Py_NewRef(dflt);
2217
0
    }
2218
0
    int res = PyDict_SetItem(ns, name, value);
2219
0
    Py_DECREF(name);
2220
0
    Py_DECREF(value);
2221
0
    return res;
2222
0
}
2223
2224
2225
typedef struct {
2226
    Py_ssize_t maxitems;
2227
    Py_ssize_t numnames;
2228
    Py_ssize_t numvalues;
2229
    _PyXI_namespace_item items[1];
2230
} _PyXI_namespace;
2231
2232
#ifndef NDEBUG
2233
static int
2234
_sharedns_check_counts(_PyXI_namespace *ns)
2235
{
2236
    if (ns->maxitems <= 0) {
2237
        return 0;
2238
    }
2239
    if (ns->numnames < 0) {
2240
        return 0;
2241
    }
2242
    if (ns->numnames > ns->maxitems) {
2243
        return 0;
2244
    }
2245
    if (ns->numvalues < 0) {
2246
        return 0;
2247
    }
2248
    if (ns->numvalues > ns->numnames) {
2249
        return 0;
2250
    }
2251
    return 1;
2252
}
2253
2254
static int
2255
_sharedns_check_consistency(_PyXI_namespace *ns)
2256
{
2257
    if (!_sharedns_check_counts(ns)) {
2258
        return 0;
2259
    }
2260
2261
    Py_ssize_t i = 0;
2262
    _PyXI_namespace_item *item;
2263
    if (ns->numvalues > 0) {
2264
        item = &ns->items[0];
2265
        if (!_sharednsitem_is_initialized(item)) {
2266
            return 0;
2267
        }
2268
        int64_t interpid0 = -1;
2269
        if (!_sharednsitem_has_value(item, &interpid0)) {
2270
            return 0;
2271
        }
2272
        i += 1;
2273
        for (; i < ns->numvalues; i++) {
2274
            item = &ns->items[i];
2275
            if (!_sharednsitem_is_initialized(item)) {
2276
                return 0;
2277
            }
2278
            int64_t interpid = -1;
2279
            if (!_sharednsitem_has_value(item, &interpid)) {
2280
                return 0;
2281
            }
2282
            if (interpid != interpid0) {
2283
                return 0;
2284
            }
2285
        }
2286
    }
2287
    for (; i < ns->numnames; i++) {
2288
        item = &ns->items[i];
2289
        if (!_sharednsitem_is_initialized(item)) {
2290
            return 0;
2291
        }
2292
        if (_sharednsitem_has_value(item, NULL)) {
2293
            return 0;
2294
        }
2295
    }
2296
    for (; i < ns->maxitems; i++) {
2297
        item = &ns->items[i];
2298
        if (_sharednsitem_is_initialized(item)) {
2299
            return 0;
2300
        }
2301
        if (_sharednsitem_has_value(item, NULL)) {
2302
            return 0;
2303
        }
2304
    }
2305
    return 1;
2306
}
2307
#endif
2308
2309
static _PyXI_namespace *
2310
_sharedns_alloc(Py_ssize_t maxitems)
2311
0
{
2312
0
    if (maxitems < 0) {
2313
0
        if (!PyErr_Occurred()) {
2314
0
            PyErr_BadInternalCall();
2315
0
        }
2316
0
        return NULL;
2317
0
    }
2318
0
    else if (maxitems == 0) {
2319
0
        PyErr_SetString(PyExc_ValueError, "empty namespaces not allowed");
2320
0
        return NULL;
2321
0
    }
2322
2323
    // Check for overflow.
2324
0
    size_t fixedsize = sizeof(_PyXI_namespace) - sizeof(_PyXI_namespace_item);
2325
0
    if ((size_t)maxitems >
2326
0
        ((size_t)PY_SSIZE_T_MAX - fixedsize) / sizeof(_PyXI_namespace_item))
2327
0
    {
2328
0
        PyErr_NoMemory();
2329
0
        return NULL;
2330
0
    }
2331
2332
    // Allocate the value, including items.
2333
0
    size_t size = fixedsize + sizeof(_PyXI_namespace_item) * maxitems;
2334
2335
0
    _PyXI_namespace *ns = PyMem_RawCalloc(size, 1);
2336
0
    if (ns == NULL) {
2337
0
        PyErr_NoMemory();
2338
0
        return NULL;
2339
0
    }
2340
0
    ns->maxitems = maxitems;
2341
0
    assert(_sharedns_check_consistency(ns));
2342
0
    return ns;
2343
0
}
2344
2345
static void
2346
_sharedns_free(_PyXI_namespace *ns)
2347
0
{
2348
    // If we weren't always dynamically allocating the cross-interpreter
2349
    // data in each item then we would need to use a pending call
2350
    // to call _sharedns_free(), to avoid the race between freeing
2351
    // the shared namespace and releasing the XI data.
2352
0
    assert(_sharedns_check_counts(ns));
2353
0
    Py_ssize_t i = 0;
2354
0
    _PyXI_namespace_item *item;
2355
0
    if (ns->numvalues > 0) {
2356
        // One or more items may have interpreter-specific data.
2357
#ifndef NDEBUG
2358
        int64_t interpid = PyInterpreterState_GetID(PyInterpreterState_Get());
2359
        int64_t interpid_i;
2360
#endif
2361
0
        for (; i < ns->numvalues; i++) {
2362
0
            item = &ns->items[i];
2363
0
            assert(_sharednsitem_is_initialized(item));
2364
            // While we do want to ensure consistency across items,
2365
            // technically they don't need to match the current
2366
            // interpreter.  However, we keep the constraint for
2367
            // simplicity, by giving _PyXI_FreeNamespace() the exclusive
2368
            // responsibility of dealing with the owning interpreter.
2369
0
            assert(_sharednsitem_has_value(item, &interpid_i));
2370
0
            assert(interpid_i == interpid);
2371
0
            _sharednsitem_clear(item);
2372
0
        }
2373
0
    }
2374
0
    for (; i < ns->numnames; i++) {
2375
0
        item = &ns->items[i];
2376
0
        assert(_sharednsitem_is_initialized(item));
2377
0
        assert(!_sharednsitem_has_value(item, NULL));
2378
0
        _sharednsitem_clear(item);
2379
0
    }
2380
#ifndef NDEBUG
2381
    for (; i < ns->maxitems; i++) {
2382
        item = &ns->items[i];
2383
        assert(!_sharednsitem_is_initialized(item));
2384
        assert(!_sharednsitem_has_value(item, NULL));
2385
    }
2386
#endif
2387
2388
0
    PyMem_RawFree(ns);
2389
0
}
2390
2391
static _PyXI_namespace *
2392
_create_sharedns(PyObject *names)
2393
0
{
2394
0
    assert(names != NULL);
2395
0
    Py_ssize_t numnames = PyDict_CheckExact(names)
2396
0
        ? PyDict_Size(names)
2397
0
        : PySequence_Size(names);
2398
2399
0
    _PyXI_namespace *ns = _sharedns_alloc(numnames);
2400
0
    if (ns == NULL) {
2401
0
        return NULL;
2402
0
    }
2403
0
    _PyXI_namespace_item *items = ns->items;
2404
2405
    // Fill in the names.
2406
0
    if (PyDict_CheckExact(names)) {
2407
0
        Py_ssize_t i = 0;
2408
0
        Py_ssize_t pos = 0;
2409
0
        PyObject *name;
2410
0
        while(PyDict_Next(names, &pos, &name, NULL)) {
2411
0
            if (_sharednsitem_init(&items[i], name) < 0) {
2412
0
                goto error;
2413
0
            }
2414
0
            ns->numnames += 1;
2415
0
            i += 1;
2416
0
        }
2417
0
    }
2418
0
    else if (PySequence_Check(names)) {
2419
0
        for (Py_ssize_t i = 0; i < numnames; i++) {
2420
0
            PyObject *name = PySequence_GetItem(names, i);
2421
0
            if (name == NULL) {
2422
0
                goto error;
2423
0
            }
2424
0
            int res = _sharednsitem_init(&items[i], name);
2425
0
            Py_DECREF(name);
2426
0
            if (res < 0) {
2427
0
                goto error;
2428
0
            }
2429
0
            ns->numnames += 1;
2430
0
        }
2431
0
    }
2432
0
    else {
2433
0
        PyErr_SetString(PyExc_NotImplementedError,
2434
0
                        "non-sequence namespace not supported");
2435
0
        goto error;
2436
0
    }
2437
0
    assert(ns->numnames == ns->maxitems);
2438
0
    return ns;
2439
2440
0
error:
2441
0
    _sharedns_free(ns);
2442
0
    return NULL;
2443
0
}
2444
2445
static void _propagate_not_shareable_error(PyThreadState *,
2446
                                           _PyXI_failure *);
2447
2448
static int
2449
_fill_sharedns(_PyXI_namespace *ns, PyObject *nsobj,
2450
               xidata_fallback_t fallback, _PyXI_failure *p_err)
2451
0
{
2452
    // All items are expected to be shareable.
2453
0
    assert(_sharedns_check_counts(ns));
2454
0
    assert(ns->numnames == ns->maxitems);
2455
0
    assert(ns->numvalues == 0);
2456
0
    PyThreadState *tstate = PyThreadState_Get();
2457
0
    for (Py_ssize_t i=0; i < ns->maxitems; i++) {
2458
0
        if (_sharednsitem_copy_from_ns(&ns->items[i], nsobj, fallback) < 0) {
2459
0
            if (p_err != NULL) {
2460
0
                _propagate_not_shareable_error(tstate, p_err);
2461
0
            }
2462
            // Clear out the ones we set so far.
2463
0
            for (Py_ssize_t j=0; j < i; j++) {
2464
0
                _sharednsitem_clear_value(&ns->items[j]);
2465
0
                ns->numvalues -= 1;
2466
0
            }
2467
0
            return -1;
2468
0
        }
2469
0
        ns->numvalues += 1;
2470
0
    }
2471
0
    return 0;
2472
0
}
2473
2474
static int
2475
_sharedns_free_pending(void *data)
2476
0
{
2477
0
    _sharedns_free((_PyXI_namespace *)data);
2478
0
    return 0;
2479
0
}
2480
2481
static void
2482
_destroy_sharedns(_PyXI_namespace *ns)
2483
0
{
2484
0
    assert(_sharedns_check_counts(ns));
2485
0
    assert(ns->numnames == ns->maxitems);
2486
0
    if (ns->numvalues == 0) {
2487
0
        _sharedns_free(ns);
2488
0
        return;
2489
0
    }
2490
2491
0
    int64_t interpid0;
2492
0
    if (!_sharednsitem_has_value(&ns->items[0], &interpid0)) {
2493
        // This shouldn't have been possible.
2494
        // We can deal with it in _sharedns_free().
2495
0
        _sharedns_free(ns);
2496
0
        return;
2497
0
    }
2498
0
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(interpid0);
2499
0
    if (interp == PyInterpreterState_Get()) {
2500
0
        _sharedns_free(ns);
2501
0
        return;
2502
0
    }
2503
2504
    // One or more items may have interpreter-specific data.
2505
    // Currently the xidata for each value is dynamically allocated,
2506
    // so technically we don't need to worry about that.
2507
    // However, explicitly adding a pending call here is simpler.
2508
0
    (void)_Py_CallInInterpreter(interp, _sharedns_free_pending, ns);
2509
0
}
2510
2511
static int
2512
_apply_sharedns(_PyXI_namespace *ns, PyObject *nsobj, PyObject *dflt)
2513
0
{
2514
0
    for (Py_ssize_t i=0; i < ns->maxitems; i++) {
2515
0
        if (_sharednsitem_apply(&ns->items[i], nsobj, dflt) != 0) {
2516
0
            return -1;
2517
0
        }
2518
0
    }
2519
0
    return 0;
2520
0
}
2521
2522
2523
/*********************************/
2524
/* switched-interpreter sessions */
2525
/*********************************/
2526
2527
struct xi_session {
2528
#define SESSION_UNUSED 0
2529
0
#define SESSION_ACTIVE 1
2530
    int status;
2531
    int switched;
2532
2533
    // Once a session has been entered, this is the tstate that was
2534
    // current before the session.  If it is different from cur_tstate
2535
    // then we must have switched interpreters.  Either way, this will
2536
    // be the current tstate once we exit the session.
2537
    PyThreadState *prev_tstate;
2538
    // Once a session has been entered, this is the current tstate.
2539
    // It must be current when the session exits.
2540
    PyThreadState *init_tstate;
2541
    // This is true if init_tstate needs cleanup during exit.
2542
    int own_init_tstate;
2543
2544
    // This is true if, while entering the session, init_thread took
2545
    // "ownership" of the interpreter's __main__ module.  This means
2546
    // it is the only thread that is allowed to run code there.
2547
    // (Caveat: for now, users may still run exec() against the
2548
    // __main__ module's dict, though that isn't advisable.)
2549
    int running;
2550
    // This is a cached reference to the __dict__ of the entered
2551
    // interpreter's __main__ module.  It is looked up when at the
2552
    // beginning of the session as a convenience.
2553
    PyObject *main_ns;
2554
2555
    // This is a dict of objects that will be available (via sharing)
2556
    // once the session exits.  Do not access this directly; use
2557
    // _PyXI_Preserve() and _PyXI_GetPreserved() instead;
2558
    PyObject *_preserved;
2559
};
2560
2561
_PyXI_session *
2562
_PyXI_NewSession(void)
2563
0
{
2564
0
    _PyXI_session *session = PyMem_RawCalloc(1, sizeof(_PyXI_session));
2565
0
    if (session == NULL) {
2566
0
        PyErr_NoMemory();
2567
0
        return NULL;
2568
0
    }
2569
0
    return session;
2570
0
}
2571
2572
void
2573
_PyXI_FreeSession(_PyXI_session *session)
2574
0
{
2575
0
    assert(session->status == SESSION_UNUSED);
2576
0
    PyMem_RawFree(session);
2577
0
}
2578
2579
2580
static inline int
2581
_session_is_active(_PyXI_session *session)
2582
0
{
2583
0
    return session->status == SESSION_ACTIVE;
2584
0
}
2585
2586
2587
/* enter/exit a cross-interpreter session */
2588
2589
static void
2590
_enter_session(_PyXI_session *session, PyInterpreterState *interp)
2591
0
{
2592
    // Set here and cleared in _exit_session().
2593
0
    assert(session->status == SESSION_UNUSED);
2594
0
    assert(!session->own_init_tstate);
2595
0
    assert(session->init_tstate == NULL);
2596
0
    assert(session->prev_tstate == NULL);
2597
    // Set elsewhere and cleared in _exit_session().
2598
0
    assert(!session->running);
2599
0
    assert(session->main_ns == NULL);
2600
2601
    // Switch to interpreter.
2602
0
    PyThreadState *tstate = PyThreadState_Get();
2603
0
    PyThreadState *prev = tstate;
2604
0
    int same_interp = (interp == tstate->interp);
2605
0
    if (!same_interp) {
2606
0
        tstate = _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_EXEC);
2607
        // XXX Possible GILState issues?
2608
0
        PyThreadState *swapped = PyThreadState_Swap(tstate);
2609
0
        assert(swapped == prev);
2610
0
        (void)swapped;
2611
0
    }
2612
2613
0
    *session = (_PyXI_session){
2614
0
        .status = SESSION_ACTIVE,
2615
0
        .switched = !same_interp,
2616
0
        .init_tstate = tstate,
2617
0
        .prev_tstate = prev,
2618
0
        .own_init_tstate = !same_interp,
2619
0
    };
2620
0
}
2621
2622
static void
2623
_exit_session(_PyXI_session *session)
2624
0
{
2625
0
    PyThreadState *tstate = session->init_tstate;
2626
0
    assert(tstate != NULL);
2627
0
    assert(PyThreadState_Get() == tstate);
2628
0
    assert(!_PyErr_Occurred(tstate));
2629
2630
    // Release any of the entered interpreters resources.
2631
0
    Py_CLEAR(session->main_ns);
2632
0
    Py_CLEAR(session->_preserved);
2633
2634
    // Ensure this thread no longer owns __main__.
2635
0
    if (session->running) {
2636
0
        _PyInterpreterState_SetNotRunningMain(tstate->interp);
2637
0
        assert(!_PyErr_Occurred(tstate));
2638
0
        session->running = 0;
2639
0
    }
2640
2641
    // Switch back.
2642
0
    assert(session->prev_tstate != NULL);
2643
0
    if (session->prev_tstate != session->init_tstate) {
2644
0
        assert(session->own_init_tstate);
2645
0
        session->own_init_tstate = 0;
2646
0
        PyThreadState_Clear(tstate);
2647
0
        PyThreadState_Swap(session->prev_tstate);
2648
0
        PyThreadState_Delete(tstate);
2649
0
    }
2650
0
    else {
2651
0
        assert(!session->own_init_tstate);
2652
0
    }
2653
2654
0
    *session = (_PyXI_session){0};
2655
0
}
2656
2657
static void
2658
_propagate_not_shareable_error(PyThreadState *tstate,
2659
                               _PyXI_failure *override)
2660
0
{
2661
0
    assert(override != NULL);
2662
0
    PyObject *exctype = get_notshareableerror_type(tstate);
2663
0
    if (exctype == NULL) {
2664
0
        PyErr_FormatUnraisable(
2665
0
                "Exception ignored while propagating not shareable error");
2666
0
        return;
2667
0
    }
2668
0
    if (PyErr_ExceptionMatches(exctype)) {
2669
        // We want to propagate the exception directly.
2670
0
        *override = (_PyXI_failure){
2671
0
            .code = _PyXI_ERR_NOT_SHAREABLE,
2672
0
        };
2673
0
    }
2674
0
}
2675
2676
2677
static int _ensure_main_ns(_PyXI_session *, _PyXI_failure *);
2678
static const char * capture_session_error(_PyXI_session *, _PyXI_error *,
2679
                                          _PyXI_failure *);
2680
2681
int
2682
_PyXI_Enter(_PyXI_session *session,
2683
            PyInterpreterState *interp, PyObject *nsupdates,
2684
            _PyXI_session_result *result)
2685
0
{
2686
#ifndef NDEBUG
2687
    PyThreadState *tstate = _PyThreadState_GET();  // Only used for asserts
2688
#endif
2689
2690
    // Convert the attrs for cross-interpreter use.
2691
0
    _PyXI_namespace *sharedns = NULL;
2692
0
    if (nsupdates != NULL) {
2693
0
        assert(PyDict_Check(nsupdates));
2694
0
        Py_ssize_t len = PyDict_Size(nsupdates);
2695
0
        if (len < 0) {
2696
0
            if (result != NULL) {
2697
0
                result->errcode = _PyXI_ERR_APPLY_NS_FAILURE;
2698
0
            }
2699
0
            return -1;
2700
0
        }
2701
0
        if (len > 0) {
2702
0
            sharedns = _create_sharedns(nsupdates);
2703
0
            if (sharedns == NULL) {
2704
0
                if (result != NULL) {
2705
0
                    result->errcode = _PyXI_ERR_APPLY_NS_FAILURE;
2706
0
                }
2707
0
                return -1;
2708
0
            }
2709
            // For now we limit it to shareable objects.
2710
0
            xidata_fallback_t fallback = _PyXIDATA_XIDATA_ONLY;
2711
0
            _PyXI_failure _err = XI_FAILURE_INIT;
2712
0
            if (_fill_sharedns(sharedns, nsupdates, fallback, &_err) < 0) {
2713
0
                assert(_PyErr_Occurred(tstate));
2714
0
                if (_err.code == _PyXI_ERR_NO_ERROR) {
2715
0
                    _err.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2716
0
                }
2717
0
                _destroy_sharedns(sharedns);
2718
0
                if (result != NULL) {
2719
0
                    assert(_err.msg == NULL);
2720
0
                    result->errcode = _err.code;
2721
0
                }
2722
0
                return -1;
2723
0
            }
2724
0
        }
2725
0
    }
2726
2727
    // Switch to the requested interpreter (if necessary).
2728
0
    _enter_session(session, interp);
2729
0
    _PyXI_failure override = XI_FAILURE_INIT;
2730
0
    override.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2731
#ifndef NDEBUG
2732
    tstate = _PyThreadState_GET();
2733
#endif
2734
2735
    // Ensure this thread owns __main__.
2736
0
    if (_PyInterpreterState_SetRunningMain(interp) < 0) {
2737
        // In the case where we didn't switch interpreters, it would
2738
        // be more efficient to leave the exception in place and return
2739
        // immediately.  However, life is simpler if we don't.
2740
0
        override.code = _PyXI_ERR_ALREADY_RUNNING;
2741
0
        goto error;
2742
0
    }
2743
0
    session->running = 1;
2744
2745
    // Apply the cross-interpreter data.
2746
0
    if (sharedns != NULL) {
2747
0
        if (_ensure_main_ns(session, &override) < 0) {
2748
0
            goto error;
2749
0
        }
2750
0
        if (_apply_sharedns(sharedns, session->main_ns, NULL) < 0) {
2751
0
            override.code = _PyXI_ERR_APPLY_NS_FAILURE;
2752
0
            goto error;
2753
0
        }
2754
0
        _destroy_sharedns(sharedns);
2755
0
    }
2756
2757
0
    override.code = _PyXI_ERR_NO_ERROR;
2758
0
    assert(!_PyErr_Occurred(tstate));
2759
0
    return 0;
2760
2761
0
error:
2762
    // We want to propagate all exceptions here directly (best effort).
2763
0
    assert(override.code != _PyXI_ERR_NO_ERROR);
2764
0
    _PyXI_error err = {0};
2765
0
    const char *failure = capture_session_error(session, &err, &override);
2766
2767
    // Exit the session.
2768
0
    _exit_session(session);
2769
#ifndef NDEBUG
2770
    tstate = _PyThreadState_GET();
2771
#endif
2772
2773
0
    if (sharedns != NULL) {
2774
0
        _destroy_sharedns(sharedns);
2775
0
    }
2776
2777
    // Apply the error from the other interpreter.
2778
0
    PyObject *excinfo = _PyXI_ApplyError(&err, failure);
2779
0
    xi_error_clear(&err);
2780
0
    if (excinfo != NULL) {
2781
0
        if (result != NULL) {
2782
0
            result->excinfo = excinfo;
2783
0
        }
2784
0
        else {
2785
#ifdef Py_DEBUG
2786
            fprintf(stderr, "_PyXI_Enter(): uncaught exception discarded");
2787
#endif
2788
0
            Py_DECREF(excinfo);
2789
0
        }
2790
0
    }
2791
0
    assert(_PyErr_Occurred(tstate));
2792
2793
0
    return -1;
2794
0
}
2795
2796
static int _pop_preserved(_PyXI_session *, _PyXI_namespace **, PyObject **,
2797
                          _PyXI_failure *);
2798
static int _finish_preserved(_PyXI_namespace *, PyObject **);
2799
2800
int
2801
_PyXI_Exit(_PyXI_session *session, _PyXI_failure *override,
2802
           _PyXI_session_result *result)
2803
0
{
2804
0
    PyThreadState *tstate = _PyThreadState_GET();
2805
0
    int res = 0;
2806
2807
    // Capture the raised exception, if any.
2808
0
    _PyXI_error err = {0};
2809
0
    const char *failure = NULL;
2810
0
    if (override != NULL && override->code == _PyXI_ERR_NO_ERROR) {
2811
0
        assert(override->msg == NULL);
2812
0
        override = NULL;
2813
0
    }
2814
0
    if (_PyErr_Occurred(tstate)) {
2815
0
        failure = capture_session_error(session, &err, override);
2816
0
    }
2817
0
    else {
2818
0
        assert(override == NULL);
2819
0
    }
2820
2821
    // Capture the preserved namespace.
2822
0
    _PyXI_namespace *preserved = NULL;
2823
0
    PyObject *preservedobj = NULL;
2824
0
    if (result != NULL) {
2825
0
        assert(!_PyErr_Occurred(tstate));
2826
0
        _PyXI_failure _override = XI_FAILURE_INIT;
2827
0
        if (_pop_preserved(
2828
0
                    session, &preserved, &preservedobj, &_override) < 0)
2829
0
        {
2830
0
            assert(preserved == NULL);
2831
0
            assert(preservedobj == NULL);
2832
0
            if (xi_error_is_set(&err)) {
2833
                // XXX Chain the exception (i.e. set __context__)?
2834
0
                PyErr_FormatUnraisable(
2835
0
                    "Exception ignored while capturing preserved objects");
2836
0
                clear_xi_failure(&_override);
2837
0
            }
2838
0
            else {
2839
0
                if (_override.code == _PyXI_ERR_NO_ERROR) {
2840
0
                    _override.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2841
0
                }
2842
0
                failure = capture_session_error(session, &err, &_override);
2843
0
            }
2844
0
        }
2845
0
    }
2846
2847
    // Exit the session.
2848
0
    assert(!_PyErr_Occurred(tstate));
2849
0
    _exit_session(session);
2850
0
    tstate = _PyThreadState_GET();
2851
2852
    // Restore the preserved namespace.
2853
0
    assert(preserved == NULL || preservedobj == NULL);
2854
0
    if (_finish_preserved(preserved, &preservedobj) < 0) {
2855
0
        assert(preservedobj == NULL);
2856
0
        if (xi_error_is_set(&err)) {
2857
            // XXX Chain the exception (i.e. set __context__)?
2858
0
            PyErr_FormatUnraisable(
2859
0
                "Exception ignored while capturing preserved objects");
2860
0
        }
2861
0
        else {
2862
0
            xi_error_set_override_code(
2863
0
                            tstate, &err, _PyXI_ERR_PRESERVE_FAILURE);
2864
0
            _propagate_not_shareable_error(tstate, err.override);
2865
0
        }
2866
0
    }
2867
0
    if (result != NULL) {
2868
0
        result->preserved = preservedobj;
2869
0
        result->errcode = err.override != NULL
2870
0
            ? err.override->code
2871
0
            : _PyXI_ERR_NO_ERROR;
2872
0
    }
2873
2874
    // Apply the error from the other interpreter, if any.
2875
0
    if (xi_error_is_set(&err)) {
2876
0
        res = -1;
2877
0
        assert(!_PyErr_Occurred(tstate));
2878
0
        PyObject *excinfo = _PyXI_ApplyError(&err, failure);
2879
0
        if (excinfo == NULL) {
2880
0
            assert(_PyErr_Occurred(tstate));
2881
0
            if (result != NULL && !xi_error_has_override(&err)) {
2882
0
                _PyXI_ClearResult(result);
2883
0
                *result = (_PyXI_session_result){
2884
0
                    .errcode = _PyXI_ERR_EXC_PROPAGATION_FAILURE,
2885
0
                };
2886
0
            }
2887
0
        }
2888
0
        else if (result != NULL) {
2889
0
            result->excinfo = excinfo;
2890
0
        }
2891
0
        else {
2892
#ifdef Py_DEBUG
2893
            fprintf(stderr, "_PyXI_Exit(): uncaught exception discarded");
2894
#endif
2895
0
            Py_DECREF(excinfo);
2896
0
        }
2897
0
        xi_error_clear(&err);
2898
0
    }
2899
0
    return res;
2900
0
}
2901
2902
2903
/* in an active cross-interpreter session */
2904
2905
static const char *
2906
capture_session_error(_PyXI_session *session, _PyXI_error *err,
2907
                      _PyXI_failure *override)
2908
0
{
2909
0
    assert(_session_is_active(session));
2910
0
    assert(!xi_error_is_set(err));
2911
0
    PyThreadState *tstate = session->init_tstate;
2912
2913
    // Normalize the exception override.
2914
0
    if (override != NULL) {
2915
0
        if (override->code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
2916
0
            assert(override->msg == NULL);
2917
0
            override = NULL;
2918
0
        }
2919
0
        else {
2920
0
            assert(override->code != _PyXI_ERR_NO_ERROR);
2921
0
        }
2922
0
    }
2923
2924
    // Handle the exception, if any.
2925
0
    const char *failure = NULL;
2926
0
    PyObject *exc = xi_error_resolve_current_exc(tstate, override);
2927
0
    if (exc != NULL) {
2928
        // There is an unhandled exception we need to preserve.
2929
0
        failure = xi_error_set_exc(tstate, err, exc);
2930
0
        Py_DECREF(exc);
2931
0
        if (_PyErr_Occurred(tstate)) {
2932
0
            PyErr_FormatUnraisable(failure);
2933
0
        }
2934
0
    }
2935
2936
    // Handle the override.
2937
0
    if (override != NULL && failure == NULL) {
2938
0
        xi_error_set_override(tstate, err, override);
2939
0
    }
2940
2941
    // Finished!
2942
0
    assert(!_PyErr_Occurred(tstate));
2943
0
    return failure;
2944
0
}
2945
2946
static int
2947
_ensure_main_ns(_PyXI_session *session, _PyXI_failure *failure)
2948
0
{
2949
0
    assert(_session_is_active(session));
2950
0
    PyThreadState *tstate = session->init_tstate;
2951
0
    if (session->main_ns != NULL) {
2952
0
        return 0;
2953
0
    }
2954
    // Cache __main__.__dict__.
2955
0
    PyObject *main_mod = _Py_GetMainModule(tstate);
2956
0
    if (_Py_CheckMainModule(main_mod) < 0) {
2957
0
        Py_XDECREF(main_mod);
2958
0
        if (failure != NULL) {
2959
0
            *failure = (_PyXI_failure){
2960
0
                .code = _PyXI_ERR_MAIN_NS_FAILURE,
2961
0
            };
2962
0
        }
2963
0
        return -1;
2964
0
    }
2965
0
    PyObject *ns = PyModule_GetDict(main_mod);  // borrowed
2966
0
    Py_DECREF(main_mod);
2967
0
    if (ns == NULL) {
2968
0
        if (failure != NULL) {
2969
0
            *failure = (_PyXI_failure){
2970
0
                .code = _PyXI_ERR_MAIN_NS_FAILURE,
2971
0
            };
2972
0
        }
2973
0
        return -1;
2974
0
    }
2975
0
    session->main_ns = Py_NewRef(ns);
2976
0
    return 0;
2977
0
}
2978
2979
PyObject *
2980
_PyXI_GetMainNamespace(_PyXI_session *session, _PyXI_failure *failure)
2981
0
{
2982
0
    if (!_session_is_active(session)) {
2983
0
        PyErr_SetString(PyExc_RuntimeError, "session not active");
2984
0
        return NULL;
2985
0
    }
2986
0
    if (_ensure_main_ns(session, failure) < 0) {
2987
0
        return NULL;
2988
0
    }
2989
0
    return session->main_ns;
2990
0
}
2991
2992
2993
static int
2994
_pop_preserved(_PyXI_session *session,
2995
               _PyXI_namespace **p_xidata, PyObject **p_obj,
2996
               _PyXI_failure *p_failure)
2997
0
{
2998
0
    _PyXI_failure failure = XI_FAILURE_INIT;
2999
0
    _PyXI_namespace *xidata = NULL;
3000
0
    assert(_PyThreadState_GET() == session->init_tstate);  // active session
3001
3002
0
    if (session->_preserved == NULL) {
3003
0
        *p_xidata = NULL;
3004
0
        *p_obj = NULL;
3005
0
        return 0;
3006
0
    }
3007
0
    if (session->init_tstate == session->prev_tstate) {
3008
        // We did not switch interpreters.
3009
0
        *p_xidata = NULL;
3010
0
        *p_obj = session->_preserved;
3011
0
        session->_preserved = NULL;
3012
0
        return 0;
3013
0
    }
3014
0
    *p_obj = NULL;
3015
3016
    // We did switch interpreters.
3017
0
    Py_ssize_t len = PyDict_Size(session->_preserved);
3018
0
    if (len < 0) {
3019
0
        failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3020
0
        goto error;
3021
0
    }
3022
0
    else if (len == 0) {
3023
0
        *p_xidata = NULL;
3024
0
    }
3025
0
    else {
3026
0
        xidata = _create_sharedns(session->_preserved);
3027
0
        if (xidata == NULL) {
3028
0
            failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3029
0
            goto error;
3030
0
        }
3031
0
        if (_fill_sharedns(xidata, session->_preserved,
3032
0
                           _PyXIDATA_FULL_FALLBACK, &failure) < 0)
3033
0
        {
3034
0
            if (failure.code != _PyXI_ERR_NOT_SHAREABLE) {
3035
0
                assert(failure.msg != NULL);
3036
0
                failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3037
0
            }
3038
0
            goto error;
3039
0
        }
3040
0
        *p_xidata = xidata;
3041
0
    }
3042
0
    Py_CLEAR(session->_preserved);
3043
0
    return 0;
3044
3045
0
error:
3046
0
    if (p_failure != NULL) {
3047
0
        *p_failure = failure;
3048
0
    }
3049
0
    if (xidata != NULL) {
3050
0
        _destroy_sharedns(xidata);
3051
0
    }
3052
0
    return -1;
3053
0
}
3054
3055
static int
3056
_finish_preserved(_PyXI_namespace *xidata, PyObject **p_preserved)
3057
0
{
3058
0
    if (xidata == NULL) {
3059
0
        return 0;
3060
0
    }
3061
0
    int res = -1;
3062
0
    if (p_preserved != NULL) {
3063
0
        PyObject *ns = PyDict_New();
3064
0
        if (ns == NULL) {
3065
0
            goto finally;
3066
0
        }
3067
0
        if (_apply_sharedns(xidata, ns, NULL) < 0) {
3068
0
            Py_CLEAR(ns);
3069
0
            goto finally;
3070
0
        }
3071
0
        *p_preserved = ns;
3072
0
    }
3073
0
    res = 0;
3074
3075
0
finally:
3076
0
    _destroy_sharedns(xidata);
3077
0
    return res;
3078
0
}
3079
3080
int
3081
_PyXI_Preserve(_PyXI_session *session, const char *name, PyObject *value,
3082
               _PyXI_failure *p_failure)
3083
0
{
3084
0
    _PyXI_failure failure = XI_FAILURE_INIT;
3085
0
    if (!_session_is_active(session)) {
3086
0
        PyErr_SetString(PyExc_RuntimeError, "session not active");
3087
0
        return -1;
3088
0
    }
3089
0
    if (session->_preserved == NULL) {
3090
0
        session->_preserved = PyDict_New();
3091
0
        if (session->_preserved == NULL) {
3092
0
            set_exc_with_cause(PyExc_RuntimeError,
3093
0
                               "failed to initialize preserved objects");
3094
0
            failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3095
0
            goto error;
3096
0
        }
3097
0
    }
3098
0
    if (PyDict_SetItemString(session->_preserved, name, value) < 0) {
3099
0
        set_exc_with_cause(PyExc_RuntimeError, "failed to preserve object");
3100
0
        failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3101
0
        goto error;
3102
0
    }
3103
0
    return 0;
3104
3105
0
error:
3106
0
    if (p_failure != NULL) {
3107
0
        *p_failure = failure;
3108
0
    }
3109
0
    return -1;
3110
0
}
3111
3112
PyObject *
3113
_PyXI_GetPreserved(_PyXI_session_result *result, const char *name)
3114
0
{
3115
0
    PyObject *value = NULL;
3116
0
    if (result->preserved != NULL) {
3117
0
        (void)PyDict_GetItemStringRef(result->preserved, name, &value);
3118
0
    }
3119
0
    return value;
3120
0
}
3121
3122
void
3123
_PyXI_ClearResult(_PyXI_session_result *result)
3124
0
{
3125
0
    Py_CLEAR(result->preserved);
3126
0
    Py_CLEAR(result->excinfo);
3127
0
}
3128
3129
3130
/*********************/
3131
/* runtime lifecycle */
3132
/*********************/
3133
3134
int
3135
_Py_xi_global_state_init(_PyXI_global_state_t *state)
3136
37
{
3137
37
    assert(state != NULL);
3138
37
    xid_lookup_init(&state->data_lookup);
3139
37
    return 0;
3140
37
}
3141
3142
void
3143
_Py_xi_global_state_fini(_PyXI_global_state_t *state)
3144
0
{
3145
0
    assert(state != NULL);
3146
0
    xid_lookup_fini(&state->data_lookup);
3147
0
}
3148
3149
int
3150
_Py_xi_state_init(_PyXI_state_t *state, PyInterpreterState *interp)
3151
37
{
3152
37
    assert(state != NULL);
3153
37
    assert(interp == NULL || state == _PyXI_GET_STATE(interp));
3154
3155
    // Initialize pickle function cache (before any fallible ops).
3156
37
    state->pickle.dumps = NULL;
3157
37
    state->pickle.loads = NULL;
3158
3159
37
    xid_lookup_init(&state->data_lookup);
3160
3161
    // Initialize exceptions.
3162
37
    if (interp != NULL) {
3163
0
        if (init_static_exctypes(&state->exceptions, interp) < 0) {
3164
0
            fini_heap_exctypes(&state->exceptions);
3165
0
            return -1;
3166
0
        }
3167
0
    }
3168
37
    if (init_heap_exctypes(&state->exceptions) < 0) {
3169
0
        return -1;
3170
0
    }
3171
3172
37
    return 0;
3173
37
}
3174
3175
void
3176
_Py_xi_state_fini(_PyXI_state_t *state, PyInterpreterState *interp)
3177
0
{
3178
0
    assert(state != NULL);
3179
0
    assert(interp == NULL || state == _PyXI_GET_STATE(interp));
3180
3181
    // Clear pickle function cache first: the cached functions may hold
3182
    // references to modules cleaned up by later finalization steps.
3183
0
    Py_CLEAR(state->pickle.dumps);
3184
0
    Py_CLEAR(state->pickle.loads);
3185
3186
0
    fini_heap_exctypes(&state->exceptions);
3187
0
    if (interp != NULL) {
3188
0
        fini_static_exctypes(&state->exceptions, interp);
3189
0
    }
3190
3191
0
    xid_lookup_fini(&state->data_lookup);
3192
0
}
3193
3194
3195
PyStatus
3196
_PyXI_Init(PyInterpreterState *interp)
3197
37
{
3198
37
    if (_Py_IsMainInterpreter(interp)) {
3199
37
        _PyXI_global_state_t *global_state = _PyXI_GET_GLOBAL_STATE(interp);
3200
37
        if (global_state == NULL) {
3201
0
            PyErr_PrintEx(0);
3202
0
            return _PyStatus_ERR(
3203
0
                    "failed to get global cross-interpreter state");
3204
0
        }
3205
37
        if (_Py_xi_global_state_init(global_state) < 0) {
3206
0
            PyErr_PrintEx(0);
3207
0
            return _PyStatus_ERR(
3208
0
                    "failed to initialize  global cross-interpreter state");
3209
0
        }
3210
37
    }
3211
3212
37
    _PyXI_state_t *state = _PyXI_GET_STATE(interp);
3213
37
    if (state == NULL) {
3214
0
        PyErr_PrintEx(0);
3215
0
        return _PyStatus_ERR(
3216
0
                "failed to get interpreter's cross-interpreter state");
3217
0
    }
3218
    // The static types were already initialized in _PyXI_InitTypes(),
3219
    // so we pass in NULL here to avoid initializing them again.
3220
37
    if (_Py_xi_state_init(state, NULL) < 0) {
3221
0
        PyErr_PrintEx(0);
3222
0
        return _PyStatus_ERR(
3223
0
                "failed to initialize interpreter's cross-interpreter state");
3224
0
    }
3225
3226
37
    return _PyStatus_OK();
3227
37
}
3228
3229
// _PyXI_Fini() must be called before the interpreter is cleared,
3230
// since we must clear some heap objects.
3231
3232
void
3233
_PyXI_Fini(PyInterpreterState *interp)
3234
0
{
3235
0
    _PyXI_state_t *state = _PyXI_GET_STATE(interp);
3236
#ifndef NDEBUG
3237
    if (state == NULL) {
3238
        PyErr_PrintEx(0);
3239
        return;
3240
    }
3241
#endif
3242
    // The static types will be finalized soon in _PyXI_FiniTypes(),
3243
    // so we pass in NULL here to avoid finalizing them right now.
3244
0
    _Py_xi_state_fini(state, NULL);
3245
3246
0
    if (_Py_IsMainInterpreter(interp)) {
3247
0
        _PyXI_global_state_t *global_state = _PyXI_GET_GLOBAL_STATE(interp);
3248
0
        _Py_xi_global_state_fini(global_state);
3249
0
    }
3250
0
}
3251
3252
PyStatus
3253
_PyXI_InitTypes(PyInterpreterState *interp)
3254
37
{
3255
37
    if (init_static_exctypes(&_PyXI_GET_STATE(interp)->exceptions, interp) < 0) {
3256
0
        PyErr_PrintEx(0);
3257
0
        return _PyStatus_ERR(
3258
0
                "failed to initialize the cross-interpreter exception types");
3259
0
    }
3260
    // We would initialize heap types here too but that leads to ref leaks.
3261
    // Instead, we initialize them in _PyXI_Init().
3262
37
    return _PyStatus_OK();
3263
37
}
3264
3265
void
3266
_PyXI_FiniTypes(PyInterpreterState *interp)
3267
0
{
3268
    // We would finalize heap types here too but that leads to ref leaks.
3269
    // Instead, we finalize them in _PyXI_Fini().
3270
0
    fini_static_exctypes(&_PyXI_GET_STATE(interp)->exceptions, interp);
3271
0
}
3272
3273
3274
/*************/
3275
/* other API */
3276
/*************/
3277
3278
PyInterpreterState *
3279
_PyXI_NewInterpreter(PyInterpreterConfig *config, long *maybe_whence,
3280
                     PyThreadState **p_tstate, PyThreadState **p_save_tstate)
3281
0
{
3282
0
    PyThreadState *save_tstate = PyThreadState_Swap(NULL);
3283
0
    assert(save_tstate != NULL);
3284
3285
0
    PyThreadState *tstate;
3286
0
    PyStatus status = Py_NewInterpreterFromConfig(&tstate, config);
3287
0
    if (PyStatus_Exception(status)) {
3288
        // Since no new thread state was created, there is no exception
3289
        // to propagate; raise a fresh one after swapping back in the
3290
        // old thread state.
3291
0
        PyThreadState_Swap(save_tstate);
3292
0
        _PyErr_SetFromPyStatus(status);
3293
0
        PyObject *exc = PyErr_GetRaisedException();
3294
0
        PyErr_SetString(PyExc_InterpreterError,
3295
0
                        "sub-interpreter creation failed");
3296
0
        _PyErr_ChainExceptions1(exc);
3297
0
        return NULL;
3298
0
    }
3299
0
    assert(tstate != NULL);
3300
0
    PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
3301
3302
0
    long whence = _PyInterpreterState_WHENCE_XI;
3303
0
    if (maybe_whence != NULL) {
3304
0
        whence = *maybe_whence;
3305
0
    }
3306
0
    _PyInterpreterState_SetWhence(interp, whence);
3307
3308
0
    if (p_tstate != NULL) {
3309
        // We leave the new thread state as the current one.
3310
0
        *p_tstate = tstate;
3311
0
    }
3312
0
    else {
3313
        // Throw away the initial tstate.
3314
0
        PyThreadState_Clear(tstate);
3315
0
        PyThreadState_Swap(save_tstate);
3316
0
        PyThreadState_Delete(tstate);
3317
0
        save_tstate = NULL;
3318
0
    }
3319
0
    if (p_save_tstate != NULL) {
3320
0
        *p_save_tstate = save_tstate;
3321
0
    }
3322
0
    return interp;
3323
0
}
3324
3325
void
3326
_PyXI_EndInterpreter(PyInterpreterState *interp,
3327
                     PyThreadState *tstate, PyThreadState **p_save_tstate)
3328
0
{
3329
#ifndef NDEBUG
3330
    long whence = _PyInterpreterState_GetWhence(interp);
3331
#endif
3332
0
    assert(whence != _PyInterpreterState_WHENCE_RUNTIME);
3333
3334
0
    if (!_PyInterpreterState_IsReady(interp)) {
3335
0
        assert(whence == _PyInterpreterState_WHENCE_UNKNOWN);
3336
        // PyInterpreterState_Clear() requires the GIL,
3337
        // which a not-ready does not have, so we don't clear it.
3338
        // That means there may be leaks here until clearing the
3339
        // interpreter is fixed.
3340
0
        PyInterpreterState_Delete(interp);
3341
0
        return;
3342
0
    }
3343
0
    assert(whence != _PyInterpreterState_WHENCE_UNKNOWN);
3344
3345
0
    PyThreadState *save_tstate = NULL;
3346
0
    PyThreadState *cur_tstate = PyThreadState_GET();
3347
0
    if (tstate == NULL) {
3348
0
        if (PyThreadState_GetInterpreter(cur_tstate) == interp) {
3349
0
            tstate = cur_tstate;
3350
0
        }
3351
0
        else {
3352
0
            tstate = _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_FINI);
3353
0
            assert(tstate != NULL);
3354
0
            save_tstate = PyThreadState_Swap(tstate);
3355
0
        }
3356
0
    }
3357
0
    else {
3358
0
        assert(PyThreadState_GetInterpreter(tstate) == interp);
3359
0
        if (tstate != cur_tstate) {
3360
0
            assert(PyThreadState_GetInterpreter(cur_tstate) != interp);
3361
0
            save_tstate = PyThreadState_Swap(tstate);
3362
0
        }
3363
0
    }
3364
3365
0
    Py_EndInterpreter(tstate);
3366
3367
0
    if (p_save_tstate != NULL) {
3368
0
        save_tstate = *p_save_tstate;
3369
0
    }
3370
0
    PyThreadState_Swap(save_tstate);
3371
0
}