Coverage Report

Created: 2026-02-26 06:53

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