Coverage Report

Created: 2026-03-08 06:40

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