Coverage Report

Created: 2025-07-04 06:49

/src/cpython/Python/crossinterp.c
Line
Count
Source (jump to first uncovered line)
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 const 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
    const char *formatted = _copy_string_obj_raw(formatted_obj, &size);
1143
0
    Py_DECREF(formatted_obj);
1144
    // We remove trailing the newline added by TracebackException.format().
1145
0
    assert(formatted[size-1] == '\n');
1146
0
    ((char *)formatted)[size-1] = '\0';
1147
0
    return formatted;
1148
0
}
1149
1150
1151
static int
1152
_release_xid_data(_PyXIData_t *xidata, int rawfree)
1153
0
{
1154
0
    PyObject *exc = PyErr_GetRaisedException();
1155
0
    int res = rawfree
1156
0
        ? _PyXIData_Release(xidata)
1157
0
        : _PyXIData_ReleaseAndRawFree(xidata);
1158
0
    if (res < 0) {
1159
        /* The owning interpreter is already destroyed. */
1160
0
        _PyXIData_Clear(NULL, xidata);
1161
        // XXX Emit a warning?
1162
0
        PyErr_Clear();
1163
0
    }
1164
0
    PyErr_SetRaisedException(exc);
1165
0
    return res;
1166
0
}
1167
1168
1169
/***********************/
1170
/* exception snapshots */
1171
/***********************/
1172
1173
static int
1174
_excinfo_init_type_from_exception(struct _excinfo_type *info, PyObject *exc)
1175
0
{
1176
    /* Note that this copies directly rather than into an intermediate
1177
       struct and does not clear on error.  If we need that then we
1178
       should have a separate function to wrap this one
1179
       and do all that there. */
1180
0
    PyObject *strobj = NULL;
1181
1182
0
    PyTypeObject *type = Py_TYPE(exc);
1183
0
    if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
1184
0
        assert(_Py_IsImmortal((PyObject *)type));
1185
0
        info->builtin = type;
1186
0
    }
1187
0
    else {
1188
        // Only builtin types are preserved.
1189
0
        info->builtin = NULL;
1190
0
    }
1191
1192
    // __name__
1193
0
    strobj = PyType_GetName(type);
1194
0
    if (strobj == NULL) {
1195
0
        return -1;
1196
0
    }
1197
0
    info->name = _copy_string_obj_raw(strobj, NULL);
1198
0
    Py_DECREF(strobj);
1199
0
    if (info->name == NULL) {
1200
0
        return -1;
1201
0
    }
1202
1203
    // __qualname__
1204
0
    strobj = PyType_GetQualName(type);
1205
0
    if (strobj == NULL) {
1206
0
        return -1;
1207
0
    }
1208
0
    info->qualname = _copy_string_obj_raw(strobj, NULL);
1209
0
    Py_DECREF(strobj);
1210
0
    if (info->qualname == NULL) {
1211
0
        return -1;
1212
0
    }
1213
1214
    // __module__
1215
0
    strobj = PyType_GetModuleName(type);
1216
0
    if (strobj == NULL) {
1217
0
        return -1;
1218
0
    }
1219
0
    info->module = _copy_string_obj_raw(strobj, NULL);
1220
0
    Py_DECREF(strobj);
1221
0
    if (info->module == NULL) {
1222
0
        return -1;
1223
0
    }
1224
1225
0
    return 0;
1226
0
}
1227
1228
static int
1229
_excinfo_init_type_from_object(struct _excinfo_type *info, PyObject *exctype)
1230
0
{
1231
0
    PyObject *strobj = NULL;
1232
1233
    // __name__
1234
0
    strobj = PyObject_GetAttrString(exctype, "__name__");
1235
0
    if (strobj == NULL) {
1236
0
        return -1;
1237
0
    }
1238
0
    info->name = _copy_string_obj_raw(strobj, NULL);
1239
0
    Py_DECREF(strobj);
1240
0
    if (info->name == NULL) {
1241
0
        return -1;
1242
0
    }
1243
1244
    // __qualname__
1245
0
    strobj = PyObject_GetAttrString(exctype, "__qualname__");
1246
0
    if (strobj == NULL) {
1247
0
        return -1;
1248
0
    }
1249
0
    info->qualname = _copy_string_obj_raw(strobj, NULL);
1250
0
    Py_DECREF(strobj);
1251
0
    if (info->qualname == NULL) {
1252
0
        return -1;
1253
0
    }
1254
1255
    // __module__
1256
0
    strobj = PyObject_GetAttrString(exctype, "__module__");
1257
0
    if (strobj == NULL) {
1258
0
        return -1;
1259
0
    }
1260
0
    info->module = _copy_string_obj_raw(strobj, NULL);
1261
0
    Py_DECREF(strobj);
1262
0
    if (info->module == NULL) {
1263
0
        return -1;
1264
0
    }
1265
1266
0
    return 0;
1267
0
}
1268
1269
static void
1270
_excinfo_clear_type(struct _excinfo_type *info)
1271
0
{
1272
0
    if (info->builtin != NULL) {
1273
0
        assert(info->builtin->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
1274
0
        assert(_Py_IsImmortal((PyObject *)info->builtin));
1275
0
    }
1276
0
    if (info->name != NULL) {
1277
0
        PyMem_RawFree((void *)info->name);
1278
0
    }
1279
0
    if (info->qualname != NULL) {
1280
0
        PyMem_RawFree((void *)info->qualname);
1281
0
    }
1282
0
    if (info->module != NULL) {
1283
0
        PyMem_RawFree((void *)info->module);
1284
0
    }
1285
0
    *info = (struct _excinfo_type){NULL};
1286
0
}
1287
1288
static void
1289
_excinfo_normalize_type(struct _excinfo_type *info,
1290
                        const char **p_module, const char **p_qualname)
1291
0
{
1292
0
    if (info->name == NULL) {
1293
0
        assert(info->builtin == NULL);
1294
0
        assert(info->qualname == NULL);
1295
0
        assert(info->module == NULL);
1296
        // This is inspired by TracebackException.format_exception_only().
1297
0
        *p_module = NULL;
1298
0
        *p_qualname = NULL;
1299
0
        return;
1300
0
    }
1301
1302
0
    const char *module = info->module;
1303
0
    const char *qualname = info->qualname;
1304
0
    if (qualname == NULL) {
1305
0
        qualname = info->name;
1306
0
    }
1307
0
    assert(module != NULL);
1308
0
    if (strcmp(module, "builtins") == 0) {
1309
0
        module = NULL;
1310
0
    }
1311
0
    else if (strcmp(module, "__main__") == 0) {
1312
0
        module = NULL;
1313
0
    }
1314
0
    *p_qualname = qualname;
1315
0
    *p_module = module;
1316
0
}
1317
1318
static int
1319
excinfo_is_set(_PyXI_excinfo *info)
1320
0
{
1321
0
    return info->type.name != NULL || info->msg != NULL;
1322
0
}
1323
1324
static void
1325
_PyXI_excinfo_clear(_PyXI_excinfo *info)
1326
0
{
1327
0
    _excinfo_clear_type(&info->type);
1328
0
    if (info->msg != NULL) {
1329
0
        PyMem_RawFree((void *)info->msg);
1330
0
    }
1331
0
    if (info->errdisplay != NULL) {
1332
0
        PyMem_RawFree((void *)info->errdisplay);
1333
0
    }
1334
0
    *info = (_PyXI_excinfo){{NULL}};
1335
0
}
1336
1337
PyObject *
1338
_PyXI_excinfo_format(_PyXI_excinfo *info)
1339
0
{
1340
0
    const char *module, *qualname;
1341
0
    _excinfo_normalize_type(&info->type, &module, &qualname);
1342
0
    if (qualname != NULL) {
1343
0
        if (module != NULL) {
1344
0
            if (info->msg != NULL) {
1345
0
                return PyUnicode_FromFormat("%s.%s: %s",
1346
0
                                            module, qualname, info->msg);
1347
0
            }
1348
0
            else {
1349
0
                return PyUnicode_FromFormat("%s.%s", module, qualname);
1350
0
            }
1351
0
        }
1352
0
        else {
1353
0
            if (info->msg != NULL) {
1354
0
                return PyUnicode_FromFormat("%s: %s", qualname, info->msg);
1355
0
            }
1356
0
            else {
1357
0
                return PyUnicode_FromString(qualname);
1358
0
            }
1359
0
        }
1360
0
    }
1361
0
    else if (info->msg != NULL) {
1362
0
        return PyUnicode_FromString(info->msg);
1363
0
    }
1364
0
    else {
1365
0
        Py_RETURN_NONE;
1366
0
    }
1367
0
}
1368
1369
static const char *
1370
_PyXI_excinfo_InitFromException(_PyXI_excinfo *info, PyObject *exc)
1371
0
{
1372
0
    assert(exc != NULL);
1373
1374
0
    if (PyErr_GivenExceptionMatches(exc, PyExc_MemoryError)) {
1375
0
        _PyXI_excinfo_clear(info);
1376
0
        return NULL;
1377
0
    }
1378
0
    const char *failure = NULL;
1379
1380
0
    if (_excinfo_init_type_from_exception(&info->type, exc) < 0) {
1381
0
        failure = "error while initializing exception type snapshot";
1382
0
        goto error;
1383
0
    }
1384
1385
    // Extract the exception message.
1386
0
    PyObject *msgobj = PyObject_Str(exc);
1387
0
    if (msgobj == NULL) {
1388
0
        failure = "error while formatting exception";
1389
0
        goto error;
1390
0
    }
1391
0
    info->msg = _copy_string_obj_raw(msgobj, NULL);
1392
0
    Py_DECREF(msgobj);
1393
0
    if (info->msg == NULL) {
1394
0
        failure = "error while copying exception message";
1395
0
        goto error;
1396
0
    }
1397
1398
    // Pickle a traceback.TracebackException.
1399
0
    PyObject *tbexc = NULL;
1400
0
    if (_convert_exc_to_TracebackException(exc, &tbexc) < 0) {
1401
#ifdef Py_DEBUG
1402
        PyErr_FormatUnraisable("Exception ignored while creating TracebackException");
1403
#endif
1404
0
        PyErr_Clear();
1405
0
    }
1406
0
    else {
1407
0
        info->errdisplay = _format_TracebackException(tbexc);
1408
0
        Py_DECREF(tbexc);
1409
0
        if (info->errdisplay == NULL) {
1410
#ifdef Py_DEBUG
1411
            PyErr_FormatUnraisable("Exception ignored while formatting TracebackException");
1412
#endif
1413
0
            PyErr_Clear();
1414
0
        }
1415
0
    }
1416
1417
0
    return NULL;
1418
1419
0
error:
1420
0
    assert(failure != NULL);
1421
0
    _PyXI_excinfo_clear(info);
1422
0
    return failure;
1423
0
}
1424
1425
static const char *
1426
_PyXI_excinfo_InitFromObject(_PyXI_excinfo *info, PyObject *obj)
1427
0
{
1428
0
    const char *failure = NULL;
1429
1430
0
    PyObject *exctype = PyObject_GetAttrString(obj, "type");
1431
0
    if (exctype == NULL) {
1432
0
        failure = "exception snapshot missing 'type' attribute";
1433
0
        goto error;
1434
0
    }
1435
0
    int res = _excinfo_init_type_from_object(&info->type, exctype);
1436
0
    Py_DECREF(exctype);
1437
0
    if (res < 0) {
1438
0
        failure = "error while initializing exception type snapshot";
1439
0
        goto error;
1440
0
    }
1441
1442
    // Extract the exception message.
1443
0
    PyObject *msgobj = PyObject_GetAttrString(obj, "msg");
1444
0
    if (msgobj == NULL) {
1445
0
        failure = "exception snapshot missing 'msg' attribute";
1446
0
        goto error;
1447
0
    }
1448
0
    info->msg = _copy_string_obj_raw(msgobj, NULL);
1449
0
    Py_DECREF(msgobj);
1450
0
    if (info->msg == NULL) {
1451
0
        failure = "error while copying exception message";
1452
0
        goto error;
1453
0
    }
1454
1455
    // Pickle a traceback.TracebackException.
1456
0
    PyObject *errdisplay = PyObject_GetAttrString(obj, "errdisplay");
1457
0
    if (errdisplay == NULL) {
1458
0
        failure = "exception snapshot missing 'errdisplay' attribute";
1459
0
        goto error;
1460
0
    }
1461
0
    info->errdisplay = _copy_string_obj_raw(errdisplay, NULL);
1462
0
    Py_DECREF(errdisplay);
1463
0
    if (info->errdisplay == NULL) {
1464
0
        failure = "error while copying exception error display";
1465
0
        goto error;
1466
0
    }
1467
1468
0
    return NULL;
1469
1470
0
error:
1471
0
    assert(failure != NULL);
1472
0
    _PyXI_excinfo_clear(info);
1473
0
    return failure;
1474
0
}
1475
1476
static void
1477
_PyXI_excinfo_Apply(_PyXI_excinfo *info, PyObject *exctype)
1478
0
{
1479
0
    PyObject *tbexc = NULL;
1480
0
    if (info->errdisplay != NULL) {
1481
0
        tbexc = PyUnicode_FromString(info->errdisplay);
1482
0
        if (tbexc == NULL) {
1483
0
            PyErr_Clear();
1484
0
        }
1485
0
        else {
1486
0
            PyErr_SetObject(exctype, tbexc);
1487
0
            Py_DECREF(tbexc);
1488
0
            return;
1489
0
        }
1490
0
    }
1491
1492
0
    PyObject *formatted = _PyXI_excinfo_format(info);
1493
0
    PyErr_SetObject(exctype, formatted);
1494
0
    Py_DECREF(formatted);
1495
1496
0
    if (tbexc != NULL) {
1497
0
        PyObject *exc = PyErr_GetRaisedException();
1498
0
        if (PyObject_SetAttrString(exc, "_errdisplay", tbexc) < 0) {
1499
#ifdef Py_DEBUG
1500
            PyErr_FormatUnraisable("Exception ignored while "
1501
                                   "setting _errdisplay");
1502
#endif
1503
0
            PyErr_Clear();
1504
0
        }
1505
0
        Py_DECREF(tbexc);
1506
0
        PyErr_SetRaisedException(exc);
1507
0
    }
1508
0
}
1509
1510
static PyObject *
1511
_PyXI_excinfo_TypeAsObject(_PyXI_excinfo *info)
1512
0
{
1513
0
    PyObject *ns = _PyNamespace_New(NULL);
1514
0
    if (ns == NULL) {
1515
0
        return NULL;
1516
0
    }
1517
0
    int empty = 1;
1518
1519
0
    if (info->type.name != NULL) {
1520
0
        PyObject *name = PyUnicode_FromString(info->type.name);
1521
0
        if (name == NULL) {
1522
0
            goto error;
1523
0
        }
1524
0
        int res = PyObject_SetAttrString(ns, "__name__", name);
1525
0
        Py_DECREF(name);
1526
0
        if (res < 0) {
1527
0
            goto error;
1528
0
        }
1529
0
        empty = 0;
1530
0
    }
1531
1532
0
    if (info->type.qualname != NULL) {
1533
0
        PyObject *qualname = PyUnicode_FromString(info->type.qualname);
1534
0
        if (qualname == NULL) {
1535
0
            goto error;
1536
0
        }
1537
0
        int res = PyObject_SetAttrString(ns, "__qualname__", qualname);
1538
0
        Py_DECREF(qualname);
1539
0
        if (res < 0) {
1540
0
            goto error;
1541
0
        }
1542
0
        empty = 0;
1543
0
    }
1544
1545
0
    if (info->type.module != NULL) {
1546
0
        PyObject *module = PyUnicode_FromString(info->type.module);
1547
0
        if (module == NULL) {
1548
0
            goto error;
1549
0
        }
1550
0
        int res = PyObject_SetAttrString(ns, "__module__", module);
1551
0
        Py_DECREF(module);
1552
0
        if (res < 0) {
1553
0
            goto error;
1554
0
        }
1555
0
        empty = 0;
1556
0
    }
1557
1558
0
    if (empty) {
1559
0
        Py_CLEAR(ns);
1560
0
    }
1561
1562
0
    return ns;
1563
1564
0
error:
1565
0
    Py_DECREF(ns);
1566
0
    return NULL;
1567
0
}
1568
1569
static PyObject *
1570
_PyXI_excinfo_AsObject(_PyXI_excinfo *info)
1571
0
{
1572
0
    PyObject *ns = _PyNamespace_New(NULL);
1573
0
    if (ns == NULL) {
1574
0
        return NULL;
1575
0
    }
1576
0
    int res;
1577
1578
0
    PyObject *type = _PyXI_excinfo_TypeAsObject(info);
1579
0
    if (type == NULL) {
1580
0
        if (PyErr_Occurred()) {
1581
0
            goto error;
1582
0
        }
1583
0
        type = Py_NewRef(Py_None);
1584
0
    }
1585
0
    res = PyObject_SetAttrString(ns, "type", type);
1586
0
    Py_DECREF(type);
1587
0
    if (res < 0) {
1588
0
        goto error;
1589
0
    }
1590
1591
0
    PyObject *msg = info->msg != NULL
1592
0
        ? PyUnicode_FromString(info->msg)
1593
0
        : Py_NewRef(Py_None);
1594
0
    if (msg == NULL) {
1595
0
        goto error;
1596
0
    }
1597
0
    res = PyObject_SetAttrString(ns, "msg", msg);
1598
0
    Py_DECREF(msg);
1599
0
    if (res < 0) {
1600
0
        goto error;
1601
0
    }
1602
1603
0
    PyObject *formatted = _PyXI_excinfo_format(info);
1604
0
    if (formatted == NULL) {
1605
0
        goto error;
1606
0
    }
1607
0
    res = PyObject_SetAttrString(ns, "formatted", formatted);
1608
0
    Py_DECREF(formatted);
1609
0
    if (res < 0) {
1610
0
        goto error;
1611
0
    }
1612
1613
0
    if (info->errdisplay != NULL) {
1614
0
        PyObject *tbexc = PyUnicode_FromString(info->errdisplay);
1615
0
        if (tbexc == NULL) {
1616
0
            PyErr_Clear();
1617
0
        }
1618
0
        else {
1619
0
            res = PyObject_SetAttrString(ns, "errdisplay", tbexc);
1620
0
            Py_DECREF(tbexc);
1621
0
            if (res < 0) {
1622
0
                goto error;
1623
0
            }
1624
0
        }
1625
0
    }
1626
1627
0
    return ns;
1628
1629
0
error:
1630
0
    Py_DECREF(ns);
1631
0
    return NULL;
1632
0
}
1633
1634
1635
_PyXI_excinfo *
1636
_PyXI_NewExcInfo(PyObject *exc)
1637
0
{
1638
0
    assert(!PyErr_Occurred());
1639
0
    if (exc == NULL || exc == Py_None) {
1640
0
        PyErr_SetString(PyExc_ValueError, "missing exc");
1641
0
        return NULL;
1642
0
    }
1643
0
    _PyXI_excinfo *info = PyMem_RawCalloc(1, sizeof(_PyXI_excinfo));
1644
0
    if (info == NULL) {
1645
0
        return NULL;
1646
0
    }
1647
0
    const char *failure;
1648
0
    if (PyExceptionInstance_Check(exc) || PyExceptionClass_Check(exc)) {
1649
0
        failure = _PyXI_excinfo_InitFromException(info, exc);
1650
0
    }
1651
0
    else {
1652
0
        failure = _PyXI_excinfo_InitFromObject(info, exc);
1653
0
    }
1654
0
    if (failure != NULL) {
1655
0
        PyMem_RawFree(info);
1656
0
        set_exc_with_cause(PyExc_Exception, failure);
1657
0
        return NULL;
1658
0
    }
1659
0
    return info;
1660
0
}
1661
1662
void
1663
_PyXI_FreeExcInfo(_PyXI_excinfo *info)
1664
0
{
1665
0
    _PyXI_excinfo_clear(info);
1666
0
    PyMem_RawFree(info);
1667
0
}
1668
1669
PyObject *
1670
_PyXI_FormatExcInfo(_PyXI_excinfo *info)
1671
0
{
1672
0
    return _PyXI_excinfo_format(info);
1673
0
}
1674
1675
PyObject *
1676
_PyXI_ExcInfoAsObject(_PyXI_excinfo *info)
1677
0
{
1678
0
    return _PyXI_excinfo_AsObject(info);
1679
0
}
1680
1681
1682
/***************************/
1683
/* short-term data sharing */
1684
/***************************/
1685
1686
/* error codes */
1687
1688
static int
1689
_PyXI_ApplyErrorCode(_PyXI_errcode code, PyInterpreterState *interp)
1690
0
{
1691
0
    PyThreadState *tstate = _PyThreadState_GET();
1692
1693
0
    assert(!PyErr_Occurred());
1694
0
    assert(code != _PyXI_ERR_NO_ERROR);
1695
0
    assert(code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1696
0
    switch (code) {
1697
0
    case _PyXI_ERR_OTHER:
1698
        // XXX msg?
1699
0
        PyErr_SetNone(PyExc_InterpreterError);
1700
0
        break;
1701
0
    case _PyXI_ERR_NO_MEMORY:
1702
0
        PyErr_NoMemory();
1703
0
        break;
1704
0
    case _PyXI_ERR_ALREADY_RUNNING:
1705
0
        assert(interp != NULL);
1706
0
        _PyErr_SetInterpreterAlreadyRunning();
1707
0
        break;
1708
0
    case _PyXI_ERR_MAIN_NS_FAILURE:
1709
0
        PyErr_SetString(PyExc_InterpreterError,
1710
0
                        "failed to get __main__ namespace");
1711
0
        break;
1712
0
    case _PyXI_ERR_APPLY_NS_FAILURE:
1713
0
        PyErr_SetString(PyExc_InterpreterError,
1714
0
                        "failed to apply namespace to __main__");
1715
0
        break;
1716
0
    case _PyXI_ERR_PRESERVE_FAILURE:
1717
0
        PyErr_SetString(PyExc_InterpreterError,
1718
0
                        "failed to preserve objects across session");
1719
0
        break;
1720
0
    case _PyXI_ERR_EXC_PROPAGATION_FAILURE:
1721
0
        PyErr_SetString(PyExc_InterpreterError,
1722
0
                        "failed to transfer exception between interpreters");
1723
0
        break;
1724
0
    case _PyXI_ERR_NOT_SHAREABLE:
1725
0
        _set_xid_lookup_failure(tstate, NULL, NULL, NULL);
1726
0
        break;
1727
0
    default:
1728
#ifdef Py_DEBUG
1729
        Py_FatalError("unsupported error code");
1730
#else
1731
0
        PyErr_Format(PyExc_RuntimeError, "unsupported error code %d", code);
1732
0
#endif
1733
0
    }
1734
0
    assert(PyErr_Occurred());
1735
0
    return -1;
1736
0
}
1737
1738
/* basic failure info */
1739
1740
struct xi_failure {
1741
    // The kind of error to propagate.
1742
    _PyXI_errcode code;
1743
    // The propagated message.
1744
    const char *msg;
1745
    int msg_owned;
1746
};  // _PyXI_failure
1747
1748
0
#define XI_FAILURE_INIT (_PyXI_failure){ .code = _PyXI_ERR_NO_ERROR }
1749
1750
static void
1751
clear_xi_failure(_PyXI_failure *failure)
1752
0
{
1753
0
    if (failure->msg != NULL && failure->msg_owned) {
1754
0
        PyMem_RawFree((void*)failure->msg);
1755
0
    }
1756
0
    *failure = XI_FAILURE_INIT;
1757
0
}
1758
1759
static void
1760
copy_xi_failure(_PyXI_failure *dest, _PyXI_failure *src)
1761
0
{
1762
0
    *dest = *src;
1763
0
    dest->msg_owned = 0;
1764
0
}
1765
1766
_PyXI_failure *
1767
_PyXI_NewFailure(void)
1768
0
{
1769
0
    _PyXI_failure *failure = PyMem_RawMalloc(sizeof(_PyXI_failure));
1770
0
    if (failure == NULL) {
1771
0
        PyErr_NoMemory();
1772
0
        return NULL;
1773
0
    }
1774
0
    *failure = XI_FAILURE_INIT;
1775
0
    return failure;
1776
0
}
1777
1778
void
1779
_PyXI_FreeFailure(_PyXI_failure *failure)
1780
0
{
1781
0
    clear_xi_failure(failure);
1782
0
    PyMem_RawFree(failure);
1783
0
}
1784
1785
_PyXI_errcode
1786
_PyXI_GetFailureCode(_PyXI_failure *failure)
1787
0
{
1788
0
    if (failure == NULL) {
1789
0
        return _PyXI_ERR_NO_ERROR;
1790
0
    }
1791
0
    return failure->code;
1792
0
}
1793
1794
void
1795
_PyXI_InitFailureUTF8(_PyXI_failure *failure,
1796
                      _PyXI_errcode code, const char *msg)
1797
0
{
1798
0
    *failure = (_PyXI_failure){
1799
0
        .code = code,
1800
0
        .msg = msg,
1801
0
        .msg_owned = 0,
1802
0
    };
1803
0
}
1804
1805
int
1806
_PyXI_InitFailure(_PyXI_failure *failure, _PyXI_errcode code, PyObject *obj)
1807
0
{
1808
0
    PyObject *msgobj = PyObject_Str(obj);
1809
0
    if (msgobj == NULL) {
1810
0
        return -1;
1811
0
    }
1812
    // This will leak if not paired with clear_xi_failure().
1813
    // That happens automatically in _capture_current_exception().
1814
0
    const char *msg = _copy_string_obj_raw(msgobj, NULL);
1815
0
    Py_DECREF(msgobj);
1816
0
    if (PyErr_Occurred()) {
1817
0
        return -1;
1818
0
    }
1819
0
    *failure = (_PyXI_failure){
1820
0
        .code = code,
1821
0
        .msg = msg,
1822
0
        .msg_owned = 1,
1823
0
    };
1824
0
    return 0;
1825
0
}
1826
1827
/* shared exceptions */
1828
1829
typedef struct {
1830
    // The originating interpreter.
1831
    PyInterpreterState *interp;
1832
    // The error to propagate, if different from the uncaught exception.
1833
    _PyXI_failure *override;
1834
    _PyXI_failure _override;
1835
    // The exception information to propagate, if applicable.
1836
    // This is populated only for some error codes,
1837
    // but always for _PyXI_ERR_UNCAUGHT_EXCEPTION.
1838
    _PyXI_excinfo uncaught;
1839
} _PyXI_error;
1840
1841
static void
1842
xi_error_clear(_PyXI_error *err)
1843
0
{
1844
0
    err->interp = NULL;
1845
0
    if (err->override != NULL) {
1846
0
        clear_xi_failure(err->override);
1847
0
    }
1848
0
    _PyXI_excinfo_clear(&err->uncaught);
1849
0
}
1850
1851
static int
1852
xi_error_is_set(_PyXI_error *error)
1853
0
{
1854
0
    if (error->override != NULL) {
1855
0
        assert(error->override->code != _PyXI_ERR_NO_ERROR);
1856
0
        assert(error->override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION
1857
0
               || excinfo_is_set(&error->uncaught));
1858
0
        return 1;
1859
0
    }
1860
0
    return excinfo_is_set(&error->uncaught);
1861
0
}
1862
1863
static int
1864
xi_error_has_override(_PyXI_error *err)
1865
0
{
1866
0
    if (err->override == NULL) {
1867
0
        return 0;
1868
0
    }
1869
0
    return (err->override->code != _PyXI_ERR_NO_ERROR
1870
0
            && err->override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1871
0
}
1872
1873
static PyObject *
1874
xi_error_resolve_current_exc(PyThreadState *tstate,
1875
                             _PyXI_failure *override)
1876
0
{
1877
0
    assert(override == NULL || override->code != _PyXI_ERR_NO_ERROR);
1878
1879
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
1880
0
    if (exc == NULL) {
1881
0
        assert(override == NULL
1882
0
               || override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1883
0
    }
1884
0
    else if (override == NULL) {
1885
        // This is equivalent to _PyXI_ERR_UNCAUGHT_EXCEPTION.
1886
0
    }
1887
0
    else if (override->code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
1888
        // We want to actually capture the current exception.
1889
0
    }
1890
0
    else if (exc != NULL) {
1891
        // It might make sense to do similarly for other codes.
1892
0
        if (override->code == _PyXI_ERR_ALREADY_RUNNING) {
1893
            // We don't need the exception info.
1894
0
            Py_CLEAR(exc);
1895
0
        }
1896
        // ...else we want to actually capture the current exception.
1897
0
    }
1898
0
    return exc;
1899
0
}
1900
1901
static void
1902
xi_error_set_override(PyThreadState *tstate, _PyXI_error *err,
1903
                      _PyXI_failure *override)
1904
0
{
1905
0
    assert(err->override == NULL);
1906
0
    assert(override != NULL);
1907
0
    assert(override->code != _PyXI_ERR_NO_ERROR);
1908
    // Use xi_error_set_exc() instead of setting _PyXI_ERR_UNCAUGHT_EXCEPTION..
1909
0
    assert(override->code != _PyXI_ERR_UNCAUGHT_EXCEPTION);
1910
0
    err->override = &err->_override;
1911
    // The caller still owns override->msg.
1912
0
    copy_xi_failure(&err->_override, override);
1913
0
    err->interp = tstate->interp;
1914
0
}
1915
1916
static void
1917
xi_error_set_override_code(PyThreadState *tstate, _PyXI_error *err,
1918
                           _PyXI_errcode code)
1919
0
{
1920
0
    _PyXI_failure override = XI_FAILURE_INIT;
1921
0
    override.code = code;
1922
0
    xi_error_set_override(tstate, err, &override);
1923
0
}
1924
1925
static const char *
1926
xi_error_set_exc(PyThreadState *tstate, _PyXI_error *err, PyObject *exc)
1927
0
{
1928
0
    assert(!_PyErr_Occurred(tstate));
1929
0
    assert(!xi_error_is_set(err));
1930
0
    assert(err->override == NULL);
1931
0
    assert(err->interp == NULL);
1932
0
    assert(exc != NULL);
1933
0
    const char *failure =
1934
0
                _PyXI_excinfo_InitFromException(&err->uncaught, exc);
1935
0
    if (failure != NULL) {
1936
        // We failed to initialize err->uncaught.
1937
        // XXX Print the excobj/traceback?  Emit a warning?
1938
        // XXX Print the current exception/traceback?
1939
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_MemoryError)) {
1940
0
            xi_error_set_override_code(tstate, err, _PyXI_ERR_NO_MEMORY);
1941
0
        }
1942
0
        else {
1943
0
            xi_error_set_override_code(tstate, err, _PyXI_ERR_OTHER);
1944
0
        }
1945
0
        PyErr_Clear();
1946
0
    }
1947
0
    return failure;
1948
0
}
1949
1950
static PyObject *
1951
_PyXI_ApplyError(_PyXI_error *error, const char *failure)
1952
0
{
1953
0
    PyThreadState *tstate = PyThreadState_Get();
1954
1955
0
    if (failure != NULL) {
1956
0
        xi_error_clear(error);
1957
0
        return NULL;
1958
0
    }
1959
1960
0
    _PyXI_errcode code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
1961
0
    if (error->override != NULL) {
1962
0
        code = error->override->code;
1963
0
        assert(code != _PyXI_ERR_NO_ERROR);
1964
0
    }
1965
1966
0
    if (code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
1967
        // We will raise an exception that proxies the propagated exception.
1968
0
       return _PyXI_excinfo_AsObject(&error->uncaught);
1969
0
    }
1970
0
    else if (code == _PyXI_ERR_NOT_SHAREABLE) {
1971
        // Propagate the exception directly.
1972
0
        assert(!_PyErr_Occurred(tstate));
1973
0
        PyObject *cause = NULL;
1974
0
        if (excinfo_is_set(&error->uncaught)) {
1975
            // Maybe instead set a PyExc_ExceptionSnapshot as __cause__?
1976
            // That type doesn't exist currently
1977
            // but would look like interpreters.ExecutionFailed.
1978
0
            _PyXI_excinfo_Apply(&error->uncaught, PyExc_Exception);
1979
0
            cause = _PyErr_GetRaisedException(tstate);
1980
0
        }
1981
0
        const char *msg = error->override != NULL
1982
0
            ? error->override->msg
1983
0
            : error->uncaught.msg;
1984
0
        _set_xid_lookup_failure(tstate, NULL, msg, cause);
1985
0
        Py_XDECREF(cause);
1986
0
    }
1987
0
    else {
1988
        // Raise an exception corresponding to the code.
1989
0
        (void)_PyXI_ApplyErrorCode(code, error->interp);
1990
0
        assert(error->override == NULL || error->override->msg == NULL);
1991
0
        if (excinfo_is_set(&error->uncaught)) {
1992
            // __context__ will be set to a proxy of the propagated exception.
1993
            // (or use PyExc_ExceptionSnapshot like _PyXI_ERR_NOT_SHAREABLE?)
1994
0
            PyObject *exc = _PyErr_GetRaisedException(tstate);
1995
0
            _PyXI_excinfo_Apply(&error->uncaught, PyExc_InterpreterError);
1996
0
            PyObject *exc2 = _PyErr_GetRaisedException(tstate);
1997
0
            PyException_SetContext(exc, exc2);
1998
0
            _PyErr_SetRaisedException(tstate, exc);
1999
0
        }
2000
0
    }
2001
0
    assert(PyErr_Occurred());
2002
0
    return NULL;
2003
0
}
2004
2005
/* shared namespaces */
2006
2007
/* Shared namespaces are expected to have relatively short lifetimes.
2008
   This means dealloc of a shared namespace will normally happen "soon".
2009
   Namespace items hold cross-interpreter data, which must get released.
2010
   If the namespace/items are cleared in a different interpreter than
2011
   where the items' cross-interpreter data was set then that will cause
2012
   pending calls to be used to release the cross-interpreter data.
2013
   The tricky bit is that the pending calls can happen sufficiently
2014
   later that the namespace/items might already be deallocated.  This is
2015
   a problem if the cross-interpreter data is allocated as part of a
2016
   namespace item.  If that's the case then we must ensure the shared
2017
   namespace is only cleared/freed *after* that data has been released. */
2018
2019
typedef struct _sharednsitem {
2020
    const char *name;
2021
    _PyXIData_t *xidata;
2022
    // We could have a "PyXIData _data" field, so it would
2023
    // be allocated as part of the item and avoid an extra allocation.
2024
    // However, doing so adds a bunch of complexity because we must
2025
    // ensure the item isn't freed before a pending call might happen
2026
    // in a different interpreter to release the XI data.
2027
} _PyXI_namespace_item;
2028
2029
#ifndef NDEBUG
2030
static int
2031
_sharednsitem_is_initialized(_PyXI_namespace_item *item)
2032
{
2033
    if (item->name != NULL) {
2034
        return 1;
2035
    }
2036
    return 0;
2037
}
2038
#endif
2039
2040
static int
2041
_sharednsitem_init(_PyXI_namespace_item *item, PyObject *key)
2042
0
{
2043
0
    item->name = _copy_string_obj_raw(key, NULL);
2044
0
    if (item->name == NULL) {
2045
0
        assert(!_sharednsitem_is_initialized(item));
2046
0
        return -1;
2047
0
    }
2048
0
    item->xidata = NULL;
2049
0
    assert(_sharednsitem_is_initialized(item));
2050
0
    return 0;
2051
0
}
2052
2053
static int
2054
_sharednsitem_has_value(_PyXI_namespace_item *item, int64_t *p_interpid)
2055
0
{
2056
0
    if (item->xidata == NULL) {
2057
0
        return 0;
2058
0
    }
2059
0
    if (p_interpid != NULL) {
2060
0
        *p_interpid = _PyXIData_INTERPID(item->xidata);
2061
0
    }
2062
0
    return 1;
2063
0
}
2064
2065
static int
2066
_sharednsitem_set_value(_PyXI_namespace_item *item, PyObject *value,
2067
                        xidata_fallback_t fallback)
2068
0
{
2069
0
    assert(_sharednsitem_is_initialized(item));
2070
0
    assert(item->xidata == NULL);
2071
0
    item->xidata = _PyXIData_New();
2072
0
    if (item->xidata == NULL) {
2073
0
        return -1;
2074
0
    }
2075
0
    PyThreadState *tstate = PyThreadState_Get();
2076
0
    if (_PyObject_GetXIData(tstate, value, fallback, item->xidata) < 0) {
2077
0
        PyMem_RawFree(item->xidata);
2078
0
        item->xidata = NULL;
2079
        // The caller may want to propagate PyExc_NotShareableError
2080
        // if currently switched between interpreters.
2081
0
        return -1;
2082
0
    }
2083
0
    return 0;
2084
0
}
2085
2086
static void
2087
_sharednsitem_clear_value(_PyXI_namespace_item *item)
2088
0
{
2089
0
    _PyXIData_t *xidata = item->xidata;
2090
0
    if (xidata != NULL) {
2091
0
        item->xidata = NULL;
2092
0
        int rawfree = 1;
2093
0
        (void)_release_xid_data(xidata, rawfree);
2094
0
    }
2095
0
}
2096
2097
static void
2098
_sharednsitem_clear(_PyXI_namespace_item *item)
2099
0
{
2100
0
    if (item->name != NULL) {
2101
0
        PyMem_RawFree((void *)item->name);
2102
0
        item->name = NULL;
2103
0
    }
2104
0
    _sharednsitem_clear_value(item);
2105
0
}
2106
2107
static int
2108
_sharednsitem_copy_from_ns(struct _sharednsitem *item, PyObject *ns,
2109
                           xidata_fallback_t fallback)
2110
0
{
2111
0
    assert(item->name != NULL);
2112
0
    assert(item->xidata == NULL);
2113
0
    PyObject *value = PyDict_GetItemString(ns, item->name);  // borrowed
2114
0
    if (value == NULL) {
2115
0
        if (PyErr_Occurred()) {
2116
0
            return -1;
2117
0
        }
2118
        // When applied, this item will be set to the default (or fail).
2119
0
        return 0;
2120
0
    }
2121
0
    if (_sharednsitem_set_value(item, value, fallback) < 0) {
2122
0
        return -1;
2123
0
    }
2124
0
    return 0;
2125
0
}
2126
2127
static int
2128
_sharednsitem_apply(_PyXI_namespace_item *item, PyObject *ns, PyObject *dflt)
2129
0
{
2130
0
    PyObject *name = PyUnicode_FromString(item->name);
2131
0
    if (name == NULL) {
2132
0
        return -1;
2133
0
    }
2134
0
    PyObject *value;
2135
0
    if (item->xidata != NULL) {
2136
0
        value = _PyXIData_NewObject(item->xidata);
2137
0
        if (value == NULL) {
2138
0
            Py_DECREF(name);
2139
0
            return -1;
2140
0
        }
2141
0
    }
2142
0
    else {
2143
0
        value = Py_NewRef(dflt);
2144
0
    }
2145
0
    int res = PyDict_SetItem(ns, name, value);
2146
0
    Py_DECREF(name);
2147
0
    Py_DECREF(value);
2148
0
    return res;
2149
0
}
2150
2151
2152
typedef struct {
2153
    Py_ssize_t maxitems;
2154
    Py_ssize_t numnames;
2155
    Py_ssize_t numvalues;
2156
    _PyXI_namespace_item items[1];
2157
} _PyXI_namespace;
2158
2159
#ifndef NDEBUG
2160
static int
2161
_sharedns_check_counts(_PyXI_namespace *ns)
2162
{
2163
    if (ns->maxitems <= 0) {
2164
        return 0;
2165
    }
2166
    if (ns->numnames < 0) {
2167
        return 0;
2168
    }
2169
    if (ns->numnames > ns->maxitems) {
2170
        return 0;
2171
    }
2172
    if (ns->numvalues < 0) {
2173
        return 0;
2174
    }
2175
    if (ns->numvalues > ns->numnames) {
2176
        return 0;
2177
    }
2178
    return 1;
2179
}
2180
2181
static int
2182
_sharedns_check_consistency(_PyXI_namespace *ns)
2183
{
2184
    if (!_sharedns_check_counts(ns)) {
2185
        return 0;
2186
    }
2187
2188
    Py_ssize_t i = 0;
2189
    _PyXI_namespace_item *item;
2190
    if (ns->numvalues > 0) {
2191
        item = &ns->items[0];
2192
        if (!_sharednsitem_is_initialized(item)) {
2193
            return 0;
2194
        }
2195
        int64_t interpid0 = -1;
2196
        if (!_sharednsitem_has_value(item, &interpid0)) {
2197
            return 0;
2198
        }
2199
        i += 1;
2200
        for (; i < ns->numvalues; i++) {
2201
            item = &ns->items[i];
2202
            if (!_sharednsitem_is_initialized(item)) {
2203
                return 0;
2204
            }
2205
            int64_t interpid = -1;
2206
            if (!_sharednsitem_has_value(item, &interpid)) {
2207
                return 0;
2208
            }
2209
            if (interpid != interpid0) {
2210
                return 0;
2211
            }
2212
        }
2213
    }
2214
    for (; i < ns->numnames; i++) {
2215
        item = &ns->items[i];
2216
        if (!_sharednsitem_is_initialized(item)) {
2217
            return 0;
2218
        }
2219
        if (_sharednsitem_has_value(item, NULL)) {
2220
            return 0;
2221
        }
2222
    }
2223
    for (; i < ns->maxitems; i++) {
2224
        item = &ns->items[i];
2225
        if (_sharednsitem_is_initialized(item)) {
2226
            return 0;
2227
        }
2228
        if (_sharednsitem_has_value(item, NULL)) {
2229
            return 0;
2230
        }
2231
    }
2232
    return 1;
2233
}
2234
#endif
2235
2236
static _PyXI_namespace *
2237
_sharedns_alloc(Py_ssize_t maxitems)
2238
0
{
2239
0
    if (maxitems < 0) {
2240
0
        if (!PyErr_Occurred()) {
2241
0
            PyErr_BadInternalCall();
2242
0
        }
2243
0
        return NULL;
2244
0
    }
2245
0
    else if (maxitems == 0) {
2246
0
        PyErr_SetString(PyExc_ValueError, "empty namespaces not allowed");
2247
0
        return NULL;
2248
0
    }
2249
2250
    // Check for overflow.
2251
0
    size_t fixedsize = sizeof(_PyXI_namespace) - sizeof(_PyXI_namespace_item);
2252
0
    if ((size_t)maxitems >
2253
0
        ((size_t)PY_SSIZE_T_MAX - fixedsize) / sizeof(_PyXI_namespace_item))
2254
0
    {
2255
0
        PyErr_NoMemory();
2256
0
        return NULL;
2257
0
    }
2258
2259
    // Allocate the value, including items.
2260
0
    size_t size = fixedsize + sizeof(_PyXI_namespace_item) * maxitems;
2261
2262
0
    _PyXI_namespace *ns = PyMem_RawCalloc(size, 1);
2263
0
    if (ns == NULL) {
2264
0
        PyErr_NoMemory();
2265
0
        return NULL;
2266
0
    }
2267
0
    ns->maxitems = maxitems;
2268
0
    assert(_sharedns_check_consistency(ns));
2269
0
    return ns;
2270
0
}
2271
2272
static void
2273
_sharedns_free(_PyXI_namespace *ns)
2274
0
{
2275
    // If we weren't always dynamically allocating the cross-interpreter
2276
    // data in each item then we would need to use a pending call
2277
    // to call _sharedns_free(), to avoid the race between freeing
2278
    // the shared namespace and releasing the XI data.
2279
0
    assert(_sharedns_check_counts(ns));
2280
0
    Py_ssize_t i = 0;
2281
0
    _PyXI_namespace_item *item;
2282
0
    if (ns->numvalues > 0) {
2283
        // One or more items may have interpreter-specific data.
2284
#ifndef NDEBUG
2285
        int64_t interpid = PyInterpreterState_GetID(PyInterpreterState_Get());
2286
        int64_t interpid_i;
2287
#endif
2288
0
        for (; i < ns->numvalues; i++) {
2289
0
            item = &ns->items[i];
2290
0
            assert(_sharednsitem_is_initialized(item));
2291
            // While we do want to ensure consistency across items,
2292
            // technically they don't need to match the current
2293
            // interpreter.  However, we keep the constraint for
2294
            // simplicity, by giving _PyXI_FreeNamespace() the exclusive
2295
            // responsibility of dealing with the owning interpreter.
2296
0
            assert(_sharednsitem_has_value(item, &interpid_i));
2297
0
            assert(interpid_i == interpid);
2298
0
            _sharednsitem_clear(item);
2299
0
        }
2300
0
    }
2301
0
    for (; i < ns->numnames; i++) {
2302
0
        item = &ns->items[i];
2303
0
        assert(_sharednsitem_is_initialized(item));
2304
0
        assert(!_sharednsitem_has_value(item, NULL));
2305
0
        _sharednsitem_clear(item);
2306
0
    }
2307
#ifndef NDEBUG
2308
    for (; i < ns->maxitems; i++) {
2309
        item = &ns->items[i];
2310
        assert(!_sharednsitem_is_initialized(item));
2311
        assert(!_sharednsitem_has_value(item, NULL));
2312
    }
2313
#endif
2314
2315
0
    PyMem_RawFree(ns);
2316
0
}
2317
2318
static _PyXI_namespace *
2319
_create_sharedns(PyObject *names)
2320
0
{
2321
0
    assert(names != NULL);
2322
0
    Py_ssize_t numnames = PyDict_CheckExact(names)
2323
0
        ? PyDict_Size(names)
2324
0
        : PySequence_Size(names);
2325
2326
0
    _PyXI_namespace *ns = _sharedns_alloc(numnames);
2327
0
    if (ns == NULL) {
2328
0
        return NULL;
2329
0
    }
2330
0
    _PyXI_namespace_item *items = ns->items;
2331
2332
    // Fill in the names.
2333
0
    if (PyDict_CheckExact(names)) {
2334
0
        Py_ssize_t i = 0;
2335
0
        Py_ssize_t pos = 0;
2336
0
        PyObject *name;
2337
0
        while(PyDict_Next(names, &pos, &name, NULL)) {
2338
0
            if (_sharednsitem_init(&items[i], name) < 0) {
2339
0
                goto error;
2340
0
            }
2341
0
            ns->numnames += 1;
2342
0
            i += 1;
2343
0
        }
2344
0
    }
2345
0
    else if (PySequence_Check(names)) {
2346
0
        for (Py_ssize_t i = 0; i < numnames; i++) {
2347
0
            PyObject *name = PySequence_GetItem(names, i);
2348
0
            if (name == NULL) {
2349
0
                goto error;
2350
0
            }
2351
0
            int res = _sharednsitem_init(&items[i], name);
2352
0
            Py_DECREF(name);
2353
0
            if (res < 0) {
2354
0
                goto error;
2355
0
            }
2356
0
            ns->numnames += 1;
2357
0
        }
2358
0
    }
2359
0
    else {
2360
0
        PyErr_SetString(PyExc_NotImplementedError,
2361
0
                        "non-sequence namespace not supported");
2362
0
        goto error;
2363
0
    }
2364
0
    assert(ns->numnames == ns->maxitems);
2365
0
    return ns;
2366
2367
0
error:
2368
0
    _sharedns_free(ns);
2369
0
    return NULL;
2370
0
}
2371
2372
static void _propagate_not_shareable_error(PyThreadState *,
2373
                                           _PyXI_failure *);
2374
2375
static int
2376
_fill_sharedns(_PyXI_namespace *ns, PyObject *nsobj,
2377
               xidata_fallback_t fallback, _PyXI_failure *p_err)
2378
0
{
2379
    // All items are expected to be shareable.
2380
0
    assert(_sharedns_check_counts(ns));
2381
0
    assert(ns->numnames == ns->maxitems);
2382
0
    assert(ns->numvalues == 0);
2383
0
    PyThreadState *tstate = PyThreadState_Get();
2384
0
    for (Py_ssize_t i=0; i < ns->maxitems; i++) {
2385
0
        if (_sharednsitem_copy_from_ns(&ns->items[i], nsobj, fallback) < 0) {
2386
0
            if (p_err != NULL) {
2387
0
                _propagate_not_shareable_error(tstate, p_err);
2388
0
            }
2389
            // Clear out the ones we set so far.
2390
0
            for (Py_ssize_t j=0; j < i; j++) {
2391
0
                _sharednsitem_clear_value(&ns->items[j]);
2392
0
                ns->numvalues -= 1;
2393
0
            }
2394
0
            return -1;
2395
0
        }
2396
0
        ns->numvalues += 1;
2397
0
    }
2398
0
    return 0;
2399
0
}
2400
2401
static int
2402
_sharedns_free_pending(void *data)
2403
0
{
2404
0
    _sharedns_free((_PyXI_namespace *)data);
2405
0
    return 0;
2406
0
}
2407
2408
static void
2409
_destroy_sharedns(_PyXI_namespace *ns)
2410
0
{
2411
0
    assert(_sharedns_check_counts(ns));
2412
0
    assert(ns->numnames == ns->maxitems);
2413
0
    if (ns->numvalues == 0) {
2414
0
        _sharedns_free(ns);
2415
0
        return;
2416
0
    }
2417
2418
0
    int64_t interpid0;
2419
0
    if (!_sharednsitem_has_value(&ns->items[0], &interpid0)) {
2420
        // This shouldn't have been possible.
2421
        // We can deal with it in _sharedns_free().
2422
0
        _sharedns_free(ns);
2423
0
        return;
2424
0
    }
2425
0
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(interpid0);
2426
0
    if (interp == PyInterpreterState_Get()) {
2427
0
        _sharedns_free(ns);
2428
0
        return;
2429
0
    }
2430
2431
    // One or more items may have interpreter-specific data.
2432
    // Currently the xidata for each value is dynamically allocated,
2433
    // so technically we don't need to worry about that.
2434
    // However, explicitly adding a pending call here is simpler.
2435
0
    (void)_Py_CallInInterpreter(interp, _sharedns_free_pending, ns);
2436
0
}
2437
2438
static int
2439
_apply_sharedns(_PyXI_namespace *ns, PyObject *nsobj, PyObject *dflt)
2440
0
{
2441
0
    for (Py_ssize_t i=0; i < ns->maxitems; i++) {
2442
0
        if (_sharednsitem_apply(&ns->items[i], nsobj, dflt) != 0) {
2443
0
            return -1;
2444
0
        }
2445
0
    }
2446
0
    return 0;
2447
0
}
2448
2449
2450
/*********************************/
2451
/* switched-interpreter sessions */
2452
/*********************************/
2453
2454
struct xi_session {
2455
#define SESSION_UNUSED 0
2456
0
#define SESSION_ACTIVE 1
2457
    int status;
2458
    int switched;
2459
2460
    // Once a session has been entered, this is the tstate that was
2461
    // current before the session.  If it is different from cur_tstate
2462
    // then we must have switched interpreters.  Either way, this will
2463
    // be the current tstate once we exit the session.
2464
    PyThreadState *prev_tstate;
2465
    // Once a session has been entered, this is the current tstate.
2466
    // It must be current when the session exits.
2467
    PyThreadState *init_tstate;
2468
    // This is true if init_tstate needs cleanup during exit.
2469
    int own_init_tstate;
2470
2471
    // This is true if, while entering the session, init_thread took
2472
    // "ownership" of the interpreter's __main__ module.  This means
2473
    // it is the only thread that is allowed to run code there.
2474
    // (Caveat: for now, users may still run exec() against the
2475
    // __main__ module's dict, though that isn't advisable.)
2476
    int running;
2477
    // This is a cached reference to the __dict__ of the entered
2478
    // interpreter's __main__ module.  It is looked up when at the
2479
    // beginning of the session as a convenience.
2480
    PyObject *main_ns;
2481
2482
    // This is a dict of objects that will be available (via sharing)
2483
    // once the session exits.  Do not access this directly; use
2484
    // _PyXI_Preserve() and _PyXI_GetPreserved() instead;
2485
    PyObject *_preserved;
2486
};
2487
2488
_PyXI_session *
2489
_PyXI_NewSession(void)
2490
0
{
2491
0
    _PyXI_session *session = PyMem_RawCalloc(1, sizeof(_PyXI_session));
2492
0
    if (session == NULL) {
2493
0
        PyErr_NoMemory();
2494
0
        return NULL;
2495
0
    }
2496
0
    return session;
2497
0
}
2498
2499
void
2500
_PyXI_FreeSession(_PyXI_session *session)
2501
0
{
2502
0
    assert(session->status == SESSION_UNUSED);
2503
0
    PyMem_RawFree(session);
2504
0
}
2505
2506
2507
static inline int
2508
_session_is_active(_PyXI_session *session)
2509
0
{
2510
0
    return session->status == SESSION_ACTIVE;
2511
0
}
2512
2513
2514
/* enter/exit a cross-interpreter session */
2515
2516
static void
2517
_enter_session(_PyXI_session *session, PyInterpreterState *interp)
2518
0
{
2519
    // Set here and cleared in _exit_session().
2520
0
    assert(session->status == SESSION_UNUSED);
2521
0
    assert(!session->own_init_tstate);
2522
0
    assert(session->init_tstate == NULL);
2523
0
    assert(session->prev_tstate == NULL);
2524
    // Set elsewhere and cleared in _exit_session().
2525
0
    assert(!session->running);
2526
0
    assert(session->main_ns == NULL);
2527
2528
    // Switch to interpreter.
2529
0
    PyThreadState *tstate = PyThreadState_Get();
2530
0
    PyThreadState *prev = tstate;
2531
0
    int same_interp = (interp == tstate->interp);
2532
0
    if (!same_interp) {
2533
0
        tstate = _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_EXEC);
2534
        // XXX Possible GILState issues?
2535
0
        PyThreadState *swapped = PyThreadState_Swap(tstate);
2536
0
        assert(swapped == prev);
2537
0
        (void)swapped;
2538
0
    }
2539
2540
0
    *session = (_PyXI_session){
2541
0
        .status = SESSION_ACTIVE,
2542
0
        .switched = !same_interp,
2543
0
        .init_tstate = tstate,
2544
0
        .prev_tstate = prev,
2545
0
        .own_init_tstate = !same_interp,
2546
0
    };
2547
0
}
2548
2549
static void
2550
_exit_session(_PyXI_session *session)
2551
0
{
2552
0
    PyThreadState *tstate = session->init_tstate;
2553
0
    assert(tstate != NULL);
2554
0
    assert(PyThreadState_Get() == tstate);
2555
0
    assert(!_PyErr_Occurred(tstate));
2556
2557
    // Release any of the entered interpreters resources.
2558
0
    Py_CLEAR(session->main_ns);
2559
0
    Py_CLEAR(session->_preserved);
2560
2561
    // Ensure this thread no longer owns __main__.
2562
0
    if (session->running) {
2563
0
        _PyInterpreterState_SetNotRunningMain(tstate->interp);
2564
0
        assert(!_PyErr_Occurred(tstate));
2565
0
        session->running = 0;
2566
0
    }
2567
2568
    // Switch back.
2569
0
    assert(session->prev_tstate != NULL);
2570
0
    if (session->prev_tstate != session->init_tstate) {
2571
0
        assert(session->own_init_tstate);
2572
0
        session->own_init_tstate = 0;
2573
0
        PyThreadState_Clear(tstate);
2574
0
        PyThreadState_Swap(session->prev_tstate);
2575
0
        PyThreadState_Delete(tstate);
2576
0
    }
2577
0
    else {
2578
0
        assert(!session->own_init_tstate);
2579
0
    }
2580
2581
0
    *session = (_PyXI_session){0};
2582
0
}
2583
2584
static void
2585
_propagate_not_shareable_error(PyThreadState *tstate,
2586
                               _PyXI_failure *override)
2587
0
{
2588
0
    assert(override != NULL);
2589
0
    PyObject *exctype = get_notshareableerror_type(tstate);
2590
0
    if (exctype == NULL) {
2591
0
        PyErr_FormatUnraisable(
2592
0
                "Exception ignored while propagating not shareable error");
2593
0
        return;
2594
0
    }
2595
0
    if (PyErr_ExceptionMatches(exctype)) {
2596
        // We want to propagate the exception directly.
2597
0
        *override = (_PyXI_failure){
2598
0
            .code = _PyXI_ERR_NOT_SHAREABLE,
2599
0
        };
2600
0
    }
2601
0
}
2602
2603
2604
static int _ensure_main_ns(_PyXI_session *, _PyXI_failure *);
2605
static const char * capture_session_error(_PyXI_session *, _PyXI_error *,
2606
                                          _PyXI_failure *);
2607
2608
int
2609
_PyXI_Enter(_PyXI_session *session,
2610
            PyInterpreterState *interp, PyObject *nsupdates,
2611
            _PyXI_session_result *result)
2612
0
{
2613
#ifndef NDEBUG
2614
    PyThreadState *tstate = _PyThreadState_GET();  // Only used for asserts
2615
#endif
2616
2617
    // Convert the attrs for cross-interpreter use.
2618
0
    _PyXI_namespace *sharedns = NULL;
2619
0
    if (nsupdates != NULL) {
2620
0
        assert(PyDict_Check(nsupdates));
2621
0
        Py_ssize_t len = PyDict_Size(nsupdates);
2622
0
        if (len < 0) {
2623
0
            if (result != NULL) {
2624
0
                result->errcode = _PyXI_ERR_APPLY_NS_FAILURE;
2625
0
            }
2626
0
            return -1;
2627
0
        }
2628
0
        if (len > 0) {
2629
0
            sharedns = _create_sharedns(nsupdates);
2630
0
            if (sharedns == NULL) {
2631
0
                if (result != NULL) {
2632
0
                    result->errcode = _PyXI_ERR_APPLY_NS_FAILURE;
2633
0
                }
2634
0
                return -1;
2635
0
            }
2636
            // For now we limit it to shareable objects.
2637
0
            xidata_fallback_t fallback = _PyXIDATA_XIDATA_ONLY;
2638
0
            _PyXI_failure _err = XI_FAILURE_INIT;
2639
0
            if (_fill_sharedns(sharedns, nsupdates, fallback, &_err) < 0) {
2640
0
                assert(_PyErr_Occurred(tstate));
2641
0
                if (_err.code == _PyXI_ERR_NO_ERROR) {
2642
0
                    _err.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2643
0
                }
2644
0
                _destroy_sharedns(sharedns);
2645
0
                if (result != NULL) {
2646
0
                    assert(_err.msg == NULL);
2647
0
                    result->errcode = _err.code;
2648
0
                }
2649
0
                return -1;
2650
0
            }
2651
0
        }
2652
0
    }
2653
2654
    // Switch to the requested interpreter (if necessary).
2655
0
    _enter_session(session, interp);
2656
0
    _PyXI_failure override = XI_FAILURE_INIT;
2657
0
    override.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2658
#ifndef NDEBUG
2659
    tstate = _PyThreadState_GET();
2660
#endif
2661
2662
    // Ensure this thread owns __main__.
2663
0
    if (_PyInterpreterState_SetRunningMain(interp) < 0) {
2664
        // In the case where we didn't switch interpreters, it would
2665
        // be more efficient to leave the exception in place and return
2666
        // immediately.  However, life is simpler if we don't.
2667
0
        override.code = _PyXI_ERR_ALREADY_RUNNING;
2668
0
        goto error;
2669
0
    }
2670
0
    session->running = 1;
2671
2672
    // Apply the cross-interpreter data.
2673
0
    if (sharedns != NULL) {
2674
0
        if (_ensure_main_ns(session, &override) < 0) {
2675
0
            goto error;
2676
0
        }
2677
0
        if (_apply_sharedns(sharedns, session->main_ns, NULL) < 0) {
2678
0
            override.code = _PyXI_ERR_APPLY_NS_FAILURE;
2679
0
            goto error;
2680
0
        }
2681
0
        _destroy_sharedns(sharedns);
2682
0
    }
2683
2684
0
    override.code = _PyXI_ERR_NO_ERROR;
2685
0
    assert(!_PyErr_Occurred(tstate));
2686
0
    return 0;
2687
2688
0
error:
2689
    // We want to propagate all exceptions here directly (best effort).
2690
0
    assert(override.code != _PyXI_ERR_NO_ERROR);
2691
0
    _PyXI_error err = {0};
2692
0
    const char *failure = capture_session_error(session, &err, &override);
2693
2694
    // Exit the session.
2695
0
    _exit_session(session);
2696
#ifndef NDEBUG
2697
    tstate = _PyThreadState_GET();
2698
#endif
2699
2700
0
    if (sharedns != NULL) {
2701
0
        _destroy_sharedns(sharedns);
2702
0
    }
2703
2704
    // Apply the error from the other interpreter.
2705
0
    PyObject *excinfo = _PyXI_ApplyError(&err, failure);
2706
0
    xi_error_clear(&err);
2707
0
    if (excinfo != NULL) {
2708
0
        if (result != NULL) {
2709
0
            result->excinfo = excinfo;
2710
0
        }
2711
0
        else {
2712
#ifdef Py_DEBUG
2713
            fprintf(stderr, "_PyXI_Enter(): uncaught exception discarded");
2714
#endif
2715
0
            Py_DECREF(excinfo);
2716
0
        }
2717
0
    }
2718
0
    assert(_PyErr_Occurred(tstate));
2719
2720
0
    return -1;
2721
0
}
2722
2723
static int _pop_preserved(_PyXI_session *, _PyXI_namespace **, PyObject **,
2724
                          _PyXI_failure *);
2725
static int _finish_preserved(_PyXI_namespace *, PyObject **);
2726
2727
int
2728
_PyXI_Exit(_PyXI_session *session, _PyXI_failure *override,
2729
           _PyXI_session_result *result)
2730
0
{
2731
0
    PyThreadState *tstate = _PyThreadState_GET();
2732
0
    int res = 0;
2733
2734
    // Capture the raised exception, if any.
2735
0
    _PyXI_error err = {0};
2736
0
    const char *failure = NULL;
2737
0
    if (override != NULL && override->code == _PyXI_ERR_NO_ERROR) {
2738
0
        assert(override->msg == NULL);
2739
0
        override = NULL;
2740
0
    }
2741
0
    if (_PyErr_Occurred(tstate)) {
2742
0
        failure = capture_session_error(session, &err, override);
2743
0
    }
2744
0
    else {
2745
0
        assert(override == NULL);
2746
0
    }
2747
2748
    // Capture the preserved namespace.
2749
0
    _PyXI_namespace *preserved = NULL;
2750
0
    PyObject *preservedobj = NULL;
2751
0
    if (result != NULL) {
2752
0
        assert(!_PyErr_Occurred(tstate));
2753
0
        _PyXI_failure _override = XI_FAILURE_INIT;
2754
0
        if (_pop_preserved(
2755
0
                    session, &preserved, &preservedobj, &_override) < 0)
2756
0
        {
2757
0
            assert(preserved == NULL);
2758
0
            assert(preservedobj == NULL);
2759
0
            if (xi_error_is_set(&err)) {
2760
                // XXX Chain the exception (i.e. set __context__)?
2761
0
                PyErr_FormatUnraisable(
2762
0
                    "Exception ignored while capturing preserved objects");
2763
0
                clear_xi_failure(&_override);
2764
0
            }
2765
0
            else {
2766
0
                if (_override.code == _PyXI_ERR_NO_ERROR) {
2767
0
                    _override.code = _PyXI_ERR_UNCAUGHT_EXCEPTION;
2768
0
                }
2769
0
                failure = capture_session_error(session, &err, &_override);
2770
0
            }
2771
0
        }
2772
0
    }
2773
2774
    // Exit the session.
2775
0
    assert(!_PyErr_Occurred(tstate));
2776
0
    _exit_session(session);
2777
0
    tstate = _PyThreadState_GET();
2778
2779
    // Restore the preserved namespace.
2780
0
    assert(preserved == NULL || preservedobj == NULL);
2781
0
    if (_finish_preserved(preserved, &preservedobj) < 0) {
2782
0
        assert(preservedobj == NULL);
2783
0
        if (xi_error_is_set(&err)) {
2784
            // XXX Chain the exception (i.e. set __context__)?
2785
0
            PyErr_FormatUnraisable(
2786
0
                "Exception ignored while capturing preserved objects");
2787
0
        }
2788
0
        else {
2789
0
            xi_error_set_override_code(
2790
0
                            tstate, &err, _PyXI_ERR_PRESERVE_FAILURE);
2791
0
            _propagate_not_shareable_error(tstate, err.override);
2792
0
        }
2793
0
    }
2794
0
    if (result != NULL) {
2795
0
        result->preserved = preservedobj;
2796
0
        result->errcode = err.override != NULL
2797
0
            ? err.override->code
2798
0
            : _PyXI_ERR_NO_ERROR;
2799
0
    }
2800
2801
    // Apply the error from the other interpreter, if any.
2802
0
    if (xi_error_is_set(&err)) {
2803
0
        res = -1;
2804
0
        assert(!_PyErr_Occurred(tstate));
2805
0
        PyObject *excinfo = _PyXI_ApplyError(&err, failure);
2806
0
        if (excinfo == NULL) {
2807
0
            assert(_PyErr_Occurred(tstate));
2808
0
            if (result != NULL && !xi_error_has_override(&err)) {
2809
0
                _PyXI_ClearResult(result);
2810
0
                *result = (_PyXI_session_result){
2811
0
                    .errcode = _PyXI_ERR_EXC_PROPAGATION_FAILURE,
2812
0
                };
2813
0
            }
2814
0
        }
2815
0
        else if (result != NULL) {
2816
0
            result->excinfo = excinfo;
2817
0
        }
2818
0
        else {
2819
#ifdef Py_DEBUG
2820
            fprintf(stderr, "_PyXI_Exit(): uncaught exception discarded");
2821
#endif
2822
0
            Py_DECREF(excinfo);
2823
0
        }
2824
0
        xi_error_clear(&err);
2825
0
    }
2826
0
    return res;
2827
0
}
2828
2829
2830
/* in an active cross-interpreter session */
2831
2832
static const char *
2833
capture_session_error(_PyXI_session *session, _PyXI_error *err,
2834
                      _PyXI_failure *override)
2835
0
{
2836
0
    assert(_session_is_active(session));
2837
0
    assert(!xi_error_is_set(err));
2838
0
    PyThreadState *tstate = session->init_tstate;
2839
2840
    // Normalize the exception override.
2841
0
    if (override != NULL) {
2842
0
        if (override->code == _PyXI_ERR_UNCAUGHT_EXCEPTION) {
2843
0
            assert(override->msg == NULL);
2844
0
            override = NULL;
2845
0
        }
2846
0
        else {
2847
0
            assert(override->code != _PyXI_ERR_NO_ERROR);
2848
0
        }
2849
0
    }
2850
2851
    // Handle the exception, if any.
2852
0
    const char *failure = NULL;
2853
0
    PyObject *exc = xi_error_resolve_current_exc(tstate, override);
2854
0
    if (exc != NULL) {
2855
        // There is an unhandled exception we need to preserve.
2856
0
        failure = xi_error_set_exc(tstate, err, exc);
2857
0
        Py_DECREF(exc);
2858
0
        if (_PyErr_Occurred(tstate)) {
2859
0
            PyErr_FormatUnraisable(failure);
2860
0
        }
2861
0
    }
2862
2863
    // Handle the override.
2864
0
    if (override != NULL && failure == NULL) {
2865
0
        xi_error_set_override(tstate, err, override);
2866
0
    }
2867
2868
    // Finished!
2869
0
    assert(!_PyErr_Occurred(tstate));
2870
0
    return failure;
2871
0
}
2872
2873
static int
2874
_ensure_main_ns(_PyXI_session *session, _PyXI_failure *failure)
2875
0
{
2876
0
    assert(_session_is_active(session));
2877
0
    PyThreadState *tstate = session->init_tstate;
2878
0
    if (session->main_ns != NULL) {
2879
0
        return 0;
2880
0
    }
2881
    // Cache __main__.__dict__.
2882
0
    PyObject *main_mod = _Py_GetMainModule(tstate);
2883
0
    if (_Py_CheckMainModule(main_mod) < 0) {
2884
0
        Py_XDECREF(main_mod);
2885
0
        if (failure != NULL) {
2886
0
            *failure = (_PyXI_failure){
2887
0
                .code = _PyXI_ERR_MAIN_NS_FAILURE,
2888
0
            };
2889
0
        }
2890
0
        return -1;
2891
0
    }
2892
0
    PyObject *ns = PyModule_GetDict(main_mod);  // borrowed
2893
0
    Py_DECREF(main_mod);
2894
0
    if (ns == NULL) {
2895
0
        if (failure != NULL) {
2896
0
            *failure = (_PyXI_failure){
2897
0
                .code = _PyXI_ERR_MAIN_NS_FAILURE,
2898
0
            };
2899
0
        }
2900
0
        return -1;
2901
0
    }
2902
0
    session->main_ns = Py_NewRef(ns);
2903
0
    return 0;
2904
0
}
2905
2906
PyObject *
2907
_PyXI_GetMainNamespace(_PyXI_session *session, _PyXI_failure *failure)
2908
0
{
2909
0
    if (!_session_is_active(session)) {
2910
0
        PyErr_SetString(PyExc_RuntimeError, "session not active");
2911
0
        return NULL;
2912
0
    }
2913
0
    if (_ensure_main_ns(session, failure) < 0) {
2914
0
        return NULL;
2915
0
    }
2916
0
    return session->main_ns;
2917
0
}
2918
2919
2920
static int
2921
_pop_preserved(_PyXI_session *session,
2922
               _PyXI_namespace **p_xidata, PyObject **p_obj,
2923
               _PyXI_failure *p_failure)
2924
0
{
2925
0
    _PyXI_failure failure = XI_FAILURE_INIT;
2926
0
    _PyXI_namespace *xidata = NULL;
2927
0
    assert(_PyThreadState_GET() == session->init_tstate);  // active session
2928
2929
0
    if (session->_preserved == NULL) {
2930
0
        *p_xidata = NULL;
2931
0
        *p_obj = NULL;
2932
0
        return 0;
2933
0
    }
2934
0
    if (session->init_tstate == session->prev_tstate) {
2935
        // We did not switch interpreters.
2936
0
        *p_xidata = NULL;
2937
0
        *p_obj = session->_preserved;
2938
0
        session->_preserved = NULL;
2939
0
        return 0;
2940
0
    }
2941
0
    *p_obj = NULL;
2942
2943
    // We did switch interpreters.
2944
0
    Py_ssize_t len = PyDict_Size(session->_preserved);
2945
0
    if (len < 0) {
2946
0
        failure.code = _PyXI_ERR_PRESERVE_FAILURE;
2947
0
        goto error;
2948
0
    }
2949
0
    else if (len == 0) {
2950
0
        *p_xidata = NULL;
2951
0
    }
2952
0
    else {
2953
0
        _PyXI_namespace *xidata = _create_sharedns(session->_preserved);
2954
0
        if (xidata == NULL) {
2955
0
            failure.code = _PyXI_ERR_PRESERVE_FAILURE;
2956
0
            goto error;
2957
0
        }
2958
0
        if (_fill_sharedns(xidata, session->_preserved,
2959
0
                           _PyXIDATA_FULL_FALLBACK, &failure) < 0)
2960
0
        {
2961
0
            if (failure.code != _PyXI_ERR_NOT_SHAREABLE) {
2962
0
                assert(failure.msg != NULL);
2963
0
                failure.code = _PyXI_ERR_PRESERVE_FAILURE;
2964
0
            }
2965
0
            goto error;
2966
0
        }
2967
0
        *p_xidata = xidata;
2968
0
    }
2969
0
    Py_CLEAR(session->_preserved);
2970
0
    return 0;
2971
2972
0
error:
2973
0
    if (p_failure != NULL) {
2974
0
        *p_failure = failure;
2975
0
    }
2976
0
    if (xidata != NULL) {
2977
0
        _destroy_sharedns(xidata);
2978
0
    }
2979
0
    return -1;
2980
0
}
2981
2982
static int
2983
_finish_preserved(_PyXI_namespace *xidata, PyObject **p_preserved)
2984
0
{
2985
0
    if (xidata == NULL) {
2986
0
        return 0;
2987
0
    }
2988
0
    int res = -1;
2989
0
    if (p_preserved != NULL) {
2990
0
        PyObject *ns = PyDict_New();
2991
0
        if (ns == NULL) {
2992
0
            goto finally;
2993
0
        }
2994
0
        if (_apply_sharedns(xidata, ns, NULL) < 0) {
2995
0
            Py_CLEAR(ns);
2996
0
            goto finally;
2997
0
        }
2998
0
        *p_preserved = ns;
2999
0
    }
3000
0
    res = 0;
3001
3002
0
finally:
3003
0
    _destroy_sharedns(xidata);
3004
0
    return res;
3005
0
}
3006
3007
int
3008
_PyXI_Preserve(_PyXI_session *session, const char *name, PyObject *value,
3009
               _PyXI_failure *p_failure)
3010
0
{
3011
0
    _PyXI_failure failure = XI_FAILURE_INIT;
3012
0
    if (!_session_is_active(session)) {
3013
0
        PyErr_SetString(PyExc_RuntimeError, "session not active");
3014
0
        return -1;
3015
0
    }
3016
0
    if (session->_preserved == NULL) {
3017
0
        session->_preserved = PyDict_New();
3018
0
        if (session->_preserved == NULL) {
3019
0
            set_exc_with_cause(PyExc_RuntimeError,
3020
0
                               "failed to initialize preserved objects");
3021
0
            failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3022
0
            goto error;
3023
0
        }
3024
0
    }
3025
0
    if (PyDict_SetItemString(session->_preserved, name, value) < 0) {
3026
0
        set_exc_with_cause(PyExc_RuntimeError, "failed to preserve object");
3027
0
        failure.code = _PyXI_ERR_PRESERVE_FAILURE;
3028
0
        goto error;
3029
0
    }
3030
0
    return 0;
3031
3032
0
error:
3033
0
    if (p_failure != NULL) {
3034
0
        *p_failure = failure;
3035
0
    }
3036
0
    return -1;
3037
0
}
3038
3039
PyObject *
3040
_PyXI_GetPreserved(_PyXI_session_result *result, const char *name)
3041
0
{
3042
0
    PyObject *value = NULL;
3043
0
    if (result->preserved != NULL) {
3044
0
        (void)PyDict_GetItemStringRef(result->preserved, name, &value);
3045
0
    }
3046
0
    return value;
3047
0
}
3048
3049
void
3050
_PyXI_ClearResult(_PyXI_session_result *result)
3051
0
{
3052
0
    Py_CLEAR(result->preserved);
3053
0
    Py_CLEAR(result->excinfo);
3054
0
}
3055
3056
3057
/*********************/
3058
/* runtime lifecycle */
3059
/*********************/
3060
3061
int
3062
_Py_xi_global_state_init(_PyXI_global_state_t *state)
3063
16
{
3064
16
    assert(state != NULL);
3065
16
    xid_lookup_init(&state->data_lookup);
3066
16
    return 0;
3067
16
}
3068
3069
void
3070
_Py_xi_global_state_fini(_PyXI_global_state_t *state)
3071
0
{
3072
0
    assert(state != NULL);
3073
0
    xid_lookup_fini(&state->data_lookup);
3074
0
}
3075
3076
int
3077
_Py_xi_state_init(_PyXI_state_t *state, PyInterpreterState *interp)
3078
16
{
3079
16
    assert(state != NULL);
3080
16
    assert(interp == NULL || state == _PyXI_GET_STATE(interp));
3081
3082
16
    xid_lookup_init(&state->data_lookup);
3083
3084
    // Initialize exceptions.
3085
16
    if (interp != NULL) {
3086
0
        if (init_static_exctypes(&state->exceptions, interp) < 0) {
3087
0
            fini_heap_exctypes(&state->exceptions);
3088
0
            return -1;
3089
0
        }
3090
0
    }
3091
16
    if (init_heap_exctypes(&state->exceptions) < 0) {
3092
0
        return -1;
3093
0
    }
3094
3095
16
    return 0;
3096
16
}
3097
3098
void
3099
_Py_xi_state_fini(_PyXI_state_t *state, PyInterpreterState *interp)
3100
0
{
3101
0
    assert(state != NULL);
3102
0
    assert(interp == NULL || state == _PyXI_GET_STATE(interp));
3103
3104
0
    fini_heap_exctypes(&state->exceptions);
3105
0
    if (interp != NULL) {
3106
0
        fini_static_exctypes(&state->exceptions, interp);
3107
0
    }
3108
3109
0
    xid_lookup_fini(&state->data_lookup);
3110
0
}
3111
3112
3113
PyStatus
3114
_PyXI_Init(PyInterpreterState *interp)
3115
16
{
3116
16
    if (_Py_IsMainInterpreter(interp)) {
3117
16
        _PyXI_global_state_t *global_state = _PyXI_GET_GLOBAL_STATE(interp);
3118
16
        if (global_state == NULL) {
3119
0
            PyErr_PrintEx(0);
3120
0
            return _PyStatus_ERR(
3121
0
                    "failed to get global cross-interpreter state");
3122
0
        }
3123
16
        if (_Py_xi_global_state_init(global_state) < 0) {
3124
0
            PyErr_PrintEx(0);
3125
0
            return _PyStatus_ERR(
3126
0
                    "failed to initialize  global cross-interpreter state");
3127
0
        }
3128
16
    }
3129
3130
16
    _PyXI_state_t *state = _PyXI_GET_STATE(interp);
3131
16
    if (state == NULL) {
3132
0
        PyErr_PrintEx(0);
3133
0
        return _PyStatus_ERR(
3134
0
                "failed to get interpreter's cross-interpreter state");
3135
0
    }
3136
    // The static types were already initialized in _PyXI_InitTypes(),
3137
    // so we pass in NULL here to avoid initializing them again.
3138
16
    if (_Py_xi_state_init(state, NULL) < 0) {
3139
0
        PyErr_PrintEx(0);
3140
0
        return _PyStatus_ERR(
3141
0
                "failed to initialize interpreter's cross-interpreter state");
3142
0
    }
3143
3144
16
    return _PyStatus_OK();
3145
16
}
3146
3147
// _PyXI_Fini() must be called before the interpreter is cleared,
3148
// since we must clear some heap objects.
3149
3150
void
3151
_PyXI_Fini(PyInterpreterState *interp)
3152
0
{
3153
0
    _PyXI_state_t *state = _PyXI_GET_STATE(interp);
3154
#ifndef NDEBUG
3155
    if (state == NULL) {
3156
        PyErr_PrintEx(0);
3157
        return;
3158
    }
3159
#endif
3160
    // The static types will be finalized soon in _PyXI_FiniTypes(),
3161
    // so we pass in NULL here to avoid finalizing them right now.
3162
0
    _Py_xi_state_fini(state, NULL);
3163
3164
0
    if (_Py_IsMainInterpreter(interp)) {
3165
0
        _PyXI_global_state_t *global_state = _PyXI_GET_GLOBAL_STATE(interp);
3166
0
        _Py_xi_global_state_fini(global_state);
3167
0
    }
3168
0
}
3169
3170
PyStatus
3171
_PyXI_InitTypes(PyInterpreterState *interp)
3172
16
{
3173
16
    if (init_static_exctypes(&_PyXI_GET_STATE(interp)->exceptions, interp) < 0) {
3174
0
        PyErr_PrintEx(0);
3175
0
        return _PyStatus_ERR(
3176
0
                "failed to initialize the cross-interpreter exception types");
3177
0
    }
3178
    // We would initialize heap types here too but that leads to ref leaks.
3179
    // Instead, we intialize them in _PyXI_Init().
3180
16
    return _PyStatus_OK();
3181
16
}
3182
3183
void
3184
_PyXI_FiniTypes(PyInterpreterState *interp)
3185
0
{
3186
    // We would finalize heap types here too but that leads to ref leaks.
3187
    // Instead, we finalize them in _PyXI_Fini().
3188
0
    fini_static_exctypes(&_PyXI_GET_STATE(interp)->exceptions, interp);
3189
0
}
3190
3191
3192
/*************/
3193
/* other API */
3194
/*************/
3195
3196
PyInterpreterState *
3197
_PyXI_NewInterpreter(PyInterpreterConfig *config, long *maybe_whence,
3198
                     PyThreadState **p_tstate, PyThreadState **p_save_tstate)
3199
0
{
3200
0
    PyThreadState *save_tstate = PyThreadState_Swap(NULL);
3201
0
    assert(save_tstate != NULL);
3202
3203
0
    PyThreadState *tstate;
3204
0
    PyStatus status = Py_NewInterpreterFromConfig(&tstate, config);
3205
0
    if (PyStatus_Exception(status)) {
3206
        // Since no new thread state was created, there is no exception
3207
        // to propagate; raise a fresh one after swapping back in the
3208
        // old thread state.
3209
0
        PyThreadState_Swap(save_tstate);
3210
0
        _PyErr_SetFromPyStatus(status);
3211
0
        PyObject *exc = PyErr_GetRaisedException();
3212
0
        PyErr_SetString(PyExc_InterpreterError,
3213
0
                        "sub-interpreter creation failed");
3214
0
        _PyErr_ChainExceptions1(exc);
3215
0
        return NULL;
3216
0
    }
3217
0
    assert(tstate != NULL);
3218
0
    PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
3219
3220
0
    long whence = _PyInterpreterState_WHENCE_XI;
3221
0
    if (maybe_whence != NULL) {
3222
0
        whence = *maybe_whence;
3223
0
    }
3224
0
    _PyInterpreterState_SetWhence(interp, whence);
3225
3226
0
    if (p_tstate != NULL) {
3227
        // We leave the new thread state as the current one.
3228
0
        *p_tstate = tstate;
3229
0
    }
3230
0
    else {
3231
        // Throw away the initial tstate.
3232
0
        PyThreadState_Clear(tstate);
3233
0
        PyThreadState_Swap(save_tstate);
3234
0
        PyThreadState_Delete(tstate);
3235
0
        save_tstate = NULL;
3236
0
    }
3237
0
    if (p_save_tstate != NULL) {
3238
0
        *p_save_tstate = save_tstate;
3239
0
    }
3240
0
    return interp;
3241
0
}
3242
3243
void
3244
_PyXI_EndInterpreter(PyInterpreterState *interp,
3245
                     PyThreadState *tstate, PyThreadState **p_save_tstate)
3246
0
{
3247
#ifndef NDEBUG
3248
    long whence = _PyInterpreterState_GetWhence(interp);
3249
#endif
3250
0
    assert(whence != _PyInterpreterState_WHENCE_RUNTIME);
3251
3252
0
    if (!_PyInterpreterState_IsReady(interp)) {
3253
0
        assert(whence == _PyInterpreterState_WHENCE_UNKNOWN);
3254
        // PyInterpreterState_Clear() requires the GIL,
3255
        // which a not-ready does not have, so we don't clear it.
3256
        // That means there may be leaks here until clearing the
3257
        // interpreter is fixed.
3258
0
        PyInterpreterState_Delete(interp);
3259
0
        return;
3260
0
    }
3261
0
    assert(whence != _PyInterpreterState_WHENCE_UNKNOWN);
3262
3263
0
    PyThreadState *save_tstate = NULL;
3264
0
    PyThreadState *cur_tstate = PyThreadState_GET();
3265
0
    if (tstate == NULL) {
3266
0
        if (PyThreadState_GetInterpreter(cur_tstate) == interp) {
3267
0
            tstate = cur_tstate;
3268
0
        }
3269
0
        else {
3270
0
            tstate = _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_FINI);
3271
0
            assert(tstate != NULL);
3272
0
            save_tstate = PyThreadState_Swap(tstate);
3273
0
        }
3274
0
    }
3275
0
    else {
3276
0
        assert(PyThreadState_GetInterpreter(tstate) == interp);
3277
0
        if (tstate != cur_tstate) {
3278
0
            assert(PyThreadState_GetInterpreter(cur_tstate) != interp);
3279
0
            save_tstate = PyThreadState_Swap(tstate);
3280
0
        }
3281
0
    }
3282
3283
0
    Py_EndInterpreter(tstate);
3284
3285
0
    if (p_save_tstate != NULL) {
3286
0
        save_tstate = *p_save_tstate;
3287
0
    }
3288
0
    PyThreadState_Swap(save_tstate);
3289
0
}