Coverage Report

Created: 2026-06-21 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/moduleobject.c
Line
Count
Source
1
/* Module object implementation */
2
3
#include "Python.h"
4
#include "pycore_call.h"          // _PyObject_CallNoArgs()
5
#include "pycore_ceval.h"         // _PyEval_EnableGILTransient()
6
#include "pycore_dict.h"          // _PyDict_EnablePerThreadRefcounting()
7
#include "pycore_fileutils.h"     // _Py_wgetcwd
8
#include "pycore_import.h"        // _PyImport_GetNextModuleIndex()
9
#include "pycore_interp.h"        // PyInterpreterState.importlib
10
#include "pycore_lazyimportobject.h" // _PyLazyImportObject_Check()
11
#include "pycore_long.h"          // _PyLong_GetOne()
12
#include "pycore_modsupport.h"    // _PyModule_CreateInitialized()
13
#include "pycore_moduleobject.h"  // _PyModule_GetDefOrNull()
14
#include "pycore_object.h"        // _PyType_AllocNoTrack
15
#include "pycore_pyerrors.h"      // _PyErr_FormatFromCause()
16
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
17
#include "pycore_slots.h"         // _PySlotIterator_Init
18
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
19
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
20
21
#include "osdefs.h"               // MAXPATHLEN
22
23
#define _PyModule_CAST(op) \
24
289k
    (assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
25
26
27
static PyMemberDef module_members[] = {
28
    {"__dict__", _Py_T_OBJECT, offsetof(PyModuleObject, md_dict), Py_READONLY},
29
    {0}
30
};
31
32
static void
33
assert_def_missing_or_redundant(PyModuleObject *m)
34
128k
{
35
    /* We copy all relevant info into the module object.
36
     * Modules created using a def keep a reference to that (statically
37
     * allocated) def; the info there should match what we have in the module.
38
     */
39
#ifndef NDEBUG
40
    if (m->md_token_is_def) {
41
        PyModuleDef *def = (PyModuleDef *)m->md_token;
42
        assert(def);
43
#define DO_ASSERT(F) assert (def->m_ ## F == m->md_state_ ## F);
44
        DO_ASSERT(size);
45
        DO_ASSERT(traverse);
46
        DO_ASSERT(clear);
47
        DO_ASSERT(free);
48
#undef DO_ASSERT
49
    }
50
#endif // NDEBUG
51
128k
}
52
53
54
PyTypeObject PyModuleDef_Type = {
55
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
56
    "moduledef",                                /* tp_name */
57
    sizeof(PyModuleDef),                        /* tp_basicsize */
58
    0,                                          /* tp_itemsize */
59
};
60
61
62
int
63
_PyModule_IsExtension(PyObject *obj)
64
0
{
65
0
    if (!PyModule_Check(obj)) {
66
0
        return 0;
67
0
    }
68
0
    PyModuleObject *module = (PyModuleObject*)obj;
69
70
0
    if (module->md_exec) {
71
0
        return 1;
72
0
    }
73
0
    if (module->md_token_is_def) {
74
0
        PyModuleDef *def = (PyModuleDef *)module->md_token;
75
0
        return (module->md_token_is_def && def->m_methods != NULL);
76
0
    }
77
0
    return 0;
78
0
}
79
80
81
PyObject*
82
PyModuleDef_Init(PyModuleDef* def)
83
2.02k
{
84
#ifdef Py_GIL_DISABLED
85
    // Check that this def does not come from a non-free-threading ABI.
86
    //
87
    // This is meant as a "sanity check"; users should never rely on it.
88
    // In particular, if we run out of ob_flags bits, or otherwise need to
89
    // change some of the internals, this check can go away. Still, it
90
    // would be nice to keep it for the free-threading transition.
91
    //
92
    // A PyModuleDef must be initialized with PyModuleDef_HEAD_INIT,
93
    // which (via PyObject_HEAD_INIT) sets _Py_STATICALLY_ALLOCATED_FLAG
94
    // and not _Py_LEGACY_ABI_CHECK_FLAG. For PyModuleDef, these flags never
95
    // change.
96
    // This means that the lower nibble of a valid PyModuleDef's ob_flags is
97
    // always `_10_` (in binary; `_` is don't care).
98
    //
99
    // So, a check for these bits won't reject valid PyModuleDef.
100
    // Rejecting incompatible extensions is slightly less important; here's
101
    // how that works:
102
    //
103
    // In the pre-free-threading stable ABI, PyModuleDef_HEAD_INIT is big
104
    // enough to overlap with free-threading ABI's ob_flags, is all zeros
105
    // except for the refcount field.
106
    // The refcount field can be:
107
    // - 1 (3.11 and below)
108
    // - UINT_MAX >> 2 (32-bit 3.12 & 3.13)
109
    // - UINT_MAX (64-bit 3.12 & 3.13)
110
    // - 7L << 28 (3.14)
111
    //
112
    // This means that the lower nibble of *any byte* in PyModuleDef_HEAD_INIT
113
    // is not `_10_` -- it can be:
114
    // - 0b0000
115
    // - 0b0001
116
    // - 0b0011 (from UINT_MAX >> 2)
117
    // - 0b0111 (from 7L << 28)
118
    // - 0b1111 (e.g. from UINT_MAX)
119
    // (The values may change at runtime as the PyModuleDef is used, but
120
    // PyModuleDef_Init is required before using the def as a Python object,
121
    // so we check at least once with the initial values.
122
    uint16_t flags = ((PyObject*)def)->ob_flags;
123
    uint16_t bits = _Py_STATICALLY_ALLOCATED_FLAG | _Py_LEGACY_ABI_CHECK_FLAG;
124
    if ((flags & bits) != _Py_STATICALLY_ALLOCATED_FLAG) {
125
        const char *message = "invalid PyModuleDef, extension possibly "
126
            "compiled for non-free-threaded Python";
127
        // Write the error as unraisable: if the extension tries calling
128
        // any API, it's likely to segfault and lose the exception.
129
        PyErr_SetString(PyExc_SystemError, message);
130
        PyErr_WriteUnraisable(NULL);
131
        // But also raise the exception normally -- this is technically
132
        // a recoverable state.
133
        PyErr_SetString(PyExc_SystemError, message);
134
        return NULL;
135
    }
136
#endif
137
2.02k
    assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
138
2.02k
    if (def->m_base.m_index == 0) {
139
1.08k
        Py_SET_REFCNT(def, 1);
140
1.08k
        Py_SET_TYPE(def, &PyModuleDef_Type);
141
1.08k
        def->m_base.m_index = _PyImport_GetNextModuleIndex();
142
1.08k
    }
143
2.02k
    return (PyObject*)def;
144
2.02k
}
145
146
static int
147
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
148
                 PyObject *name, PyObject *doc)
149
8.64k
{
150
8.64k
    assert(md_dict != NULL);
151
8.64k
    if (doc == NULL)
152
1.19k
        doc = Py_None;
153
154
8.64k
    if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
155
0
        return -1;
156
8.64k
    if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
157
0
        return -1;
158
8.64k
    if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
159
0
        return -1;
160
8.64k
    if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
161
0
        return -1;
162
8.64k
    if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
163
0
        return -1;
164
8.64k
    if (PyUnicode_CheckExact(name)) {
165
8.64k
        Py_XSETREF(mod->md_name, Py_NewRef(name));
166
8.64k
    }
167
168
8.64k
    return 0;
169
8.64k
}
170
171
static PyModuleObject *
172
new_module_notrack(PyTypeObject *mt)
173
8.64k
{
174
8.64k
    PyModuleObject *m;
175
8.64k
    m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
176
8.64k
    if (m == NULL)
177
0
        return NULL;
178
8.64k
    m->md_state = NULL;
179
8.64k
    m->md_weaklist = NULL;
180
8.64k
    m->md_name = NULL;
181
8.64k
    m->md_token_is_def = false;
182
#ifdef Py_GIL_DISABLED
183
    m->md_requires_gil = true;
184
#endif
185
8.64k
    m->md_state_size = 0;
186
8.64k
    m->md_state_traverse = NULL;
187
8.64k
    m->md_state_clear = NULL;
188
8.64k
    m->md_state_free = NULL;
189
8.64k
    m->md_exec = NULL;
190
8.64k
    m->md_token = NULL;
191
8.64k
    m->md_dict = PyDict_New();
192
8.64k
    if (m->md_dict == NULL) {
193
0
        Py_DECREF(m);
194
0
        return NULL;
195
0
    }
196
8.64k
    return m;
197
8.64k
}
198
199
/* Module dict watcher callback.
200
 * When a module dictionary is modified, we need to clear the keys version
201
 * to invalidate any cached lookups that depend on the dictionary structure.
202
 */
203
static int
204
module_dict_watcher(PyDict_WatchEvent event, PyObject *dict,
205
                    PyObject *key, PyObject *new_value)
206
325k
{
207
325k
    assert(PyDict_Check(dict));
208
    // Only if a new lazy object shows up do we need to clear the dictionary. If
209
    // this is adding a new key then the version will be reset anyway.
210
325k
    if (event == PyDict_EVENT_MODIFIED &&
211
97.1k
        new_value != NULL &&
212
97.1k
        PyLazyImport_CheckExact(new_value)) {
213
0
        _PyDict_ClearKeysVersionLockHeld(dict);
214
0
    }
215
325k
    return 0;
216
325k
}
217
218
int
219
_PyModule_InitModuleDictWatcher(PyInterpreterState *interp)
220
36
{
221
    // This is a reserved watcher for CPython so there's no need to check for non-NULL.
222
36
    assert(interp->dict_state.watchers[MODULE_WATCHER_ID] == NULL);
223
36
    interp->dict_state.watchers[MODULE_WATCHER_ID] = &module_dict_watcher;
224
36
    return 0;
225
36
}
226
227
static void
228
track_module(PyModuleObject *m)
229
8.64k
{
230
8.64k
    _PyDict_EnablePerThreadRefcounting(m->md_dict);
231
8.64k
    _PyObject_SetDeferredRefcount((PyObject *)m);
232
8.64k
    PyDict_Watch(MODULE_WATCHER_ID, m->md_dict);
233
8.64k
    PyObject_GC_Track(m);
234
8.64k
}
235
236
static PyObject *
237
new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
238
7.44k
{
239
7.44k
    PyModuleObject *m = new_module_notrack(mt);
240
7.44k
    if (m != NULL) {
241
7.44k
        track_module(m);
242
7.44k
    }
243
7.44k
    return (PyObject *)m;
244
7.44k
}
245
246
PyObject *
247
PyModule_NewObject(PyObject *name)
248
1.19k
{
249
1.19k
    PyModuleObject *m = new_module_notrack(&PyModule_Type);
250
1.19k
    if (m == NULL)
251
0
        return NULL;
252
1.19k
    if (module_init_dict(m, m->md_dict, name, NULL) != 0)
253
0
        goto fail;
254
1.19k
    track_module(m);
255
1.19k
    return (PyObject *)m;
256
257
0
 fail:
258
0
    Py_DECREF(m);
259
0
    return NULL;
260
1.19k
}
261
262
PyObject *
263
PyModule_New(const char *name)
264
188
{
265
188
    PyObject *nameobj, *module;
266
188
    nameobj = PyUnicode_FromString(name);
267
188
    if (nameobj == NULL)
268
0
        return NULL;
269
188
    module = PyModule_NewObject(nameobj);
270
188
    Py_DECREF(nameobj);
271
188
    return module;
272
188
}
273
274
/* Check API/ABI version
275
 * Issues a warning on mismatch, which is usually not fatal.
276
 * Returns 0 if an exception is raised.
277
 */
278
static int
279
check_api_version(const char *name, int module_api_version)
280
1.08k
{
281
1.08k
    if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
282
0
        int err;
283
0
        err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
284
0
            "Python C API version mismatch for module %.100s: "
285
0
            "This Python has API version %d, module %.100s has version %d.",
286
0
             name,
287
0
             PYTHON_API_VERSION, name, module_api_version);
288
0
        if (err)
289
0
            return 0;
290
0
    }
291
1.08k
    return 1;
292
1.08k
}
293
294
static int
295
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
296
1.02k
{
297
1.02k
    PyObject *func;
298
1.02k
    PyMethodDef *fdef;
299
300
21.8k
    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
301
20.8k
        if ((fdef->ml_flags & METH_CLASS) ||
302
20.8k
            (fdef->ml_flags & METH_STATIC)) {
303
0
            PyErr_SetString(PyExc_ValueError,
304
0
                            "module functions cannot set"
305
0
                            " METH_CLASS or METH_STATIC");
306
0
            return -1;
307
0
        }
308
20.8k
        func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
309
20.8k
        if (func == NULL) {
310
0
            return -1;
311
0
        }
312
20.8k
        _PyObject_SetDeferredRefcount(func);
313
20.8k
        if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
314
0
            Py_DECREF(func);
315
0
            return -1;
316
0
        }
317
20.8k
        Py_DECREF(func);
318
20.8k
    }
319
320
1.02k
    return 0;
321
1.02k
}
322
323
PyObject *
324
PyModule_Create2(PyModuleDef* module, int module_api_version)
325
0
{
326
0
    if (!_PyImport_IsInitialized(_PyInterpreterState_GET())) {
327
0
        PyErr_SetString(PyExc_SystemError,
328
0
                        "Python import machinery not initialized");
329
0
        return NULL;
330
0
    }
331
0
    return _PyModule_CreateInitialized(module, module_api_version);
332
0
}
333
334
static void
335
module_copy_members_from_deflike(
336
    PyModuleObject *md,
337
    PyModuleDef *def_like /* not necessarily a valid Python object */)
338
1.08k
{
339
1.08k
    md->md_state_size = def_like->m_size;
340
1.08k
    md->md_state_traverse = def_like->m_traverse;
341
1.08k
    md->md_state_clear = def_like->m_clear;
342
1.08k
    md->md_state_free = def_like->m_free;
343
1.08k
}
344
345
PyObject *
346
_PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
347
144
{
348
144
    const char* name;
349
144
    PyModuleObject *m;
350
351
144
    if (!PyModuleDef_Init(module))
352
0
        return NULL;
353
144
    name = module->m_name;
354
144
    if (!check_api_version(name, module_api_version)) {
355
0
        return NULL;
356
0
    }
357
144
    if (module->m_slots) {
358
0
        PyErr_Format(
359
0
            PyExc_SystemError,
360
0
            "module %s: PyModule_Create is incompatible with m_slots", name);
361
0
        return NULL;
362
0
    }
363
144
    name = _PyImport_ResolveNameWithPackageContext(name);
364
365
144
    m = (PyModuleObject*)PyModule_New(name);
366
144
    if (m == NULL)
367
0
        return NULL;
368
369
144
    if (module->m_size > 0) {
370
0
        m->md_state = PyMem_Malloc(module->m_size);
371
0
        if (!m->md_state) {
372
0
            PyErr_NoMemory();
373
0
            Py_DECREF(m);
374
0
            return NULL;
375
0
        }
376
0
        memset(m->md_state, 0, module->m_size);
377
0
    }
378
379
144
    if (module->m_methods != NULL) {
380
144
        if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
381
0
            Py_DECREF(m);
382
0
            return NULL;
383
0
        }
384
144
    }
385
144
    if (module->m_doc != NULL) {
386
108
        if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
387
0
            Py_DECREF(m);
388
0
            return NULL;
389
0
        }
390
108
    }
391
144
    m->md_token = module;
392
144
    m->md_token_is_def = true;
393
144
    module_copy_members_from_deflike(m, module);
394
#ifdef Py_GIL_DISABLED
395
    m->md_requires_gil = true;
396
#endif
397
144
    return (PyObject*)m;
398
144
}
399
400
typedef PyObject *(*createfunc_t)(PyObject *, PyModuleDef*);
401
402
static PyObject *
403
module_from_slots_and_spec(
404
    const PySlot *slots,
405
    PyObject *spec,
406
    int module_api_version,
407
    PyModuleDef* original_def /* NULL if not defined by a def */)
408
939
{
409
939
    createfunc_t create = NULL;
410
939
    PyObject *nameobj;
411
939
    PyObject *m = NULL;
412
939
    uint64_t multiple_interpreters = (uint64_t)Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
413
939
    bool requires_gil = true;
414
939
    const char *name;
415
939
    int ret;
416
939
    void *token = NULL;
417
939
    _Py_modexecfunc m_exec = NULL;
418
939
    PyInterpreterState *interp = _PyInterpreterState_GET();
419
420
939
    nameobj = PyObject_GetAttrString(spec, "name");
421
939
    if (nameobj == NULL) {
422
0
        return NULL;
423
0
    }
424
939
    name = PyUnicode_AsUTF8(nameobj);
425
939
    if (name == NULL) {
426
0
        goto error;
427
0
    }
428
429
939
    if (!check_api_version(name, module_api_version)) {
430
0
        goto error;
431
0
    }
432
433
939
    _PySlotIterator it;
434
435
939
    PyModuleDef _dummy_def = {0};
436
939
    PyModuleDef *def_like;
437
939
    if (slots) {
438
0
        assert(!original_def);
439
0
        def_like = &_dummy_def;
440
0
         _PySlotIterator_Init(&it, slots, _PySlot_KIND_MOD);
441
0
    }
442
939
    else {
443
939
        assert(original_def);
444
939
        def_like = original_def;
445
939
         _PySlotIterator_InitLegacy(&it, def_like->m_slots, _PySlot_KIND_MOD);
446
939
    }
447
939
    it.name = name;
448
449
4.63k
    while (_PySlotIterator_Next(&it)) {
450
3.70k
        switch (it.current.sl_id) {
451
0
            case Py_slot_invalid:
452
0
                goto error;
453
0
            case Py_mod_create:
454
0
                create = (createfunc_t)it.current.sl_func;
455
0
                break;
456
959
            case Py_mod_exec:
457
959
                if (!original_def) {
458
0
                    if (m_exec) {
459
0
                        PyErr_Format(
460
0
                            PyExc_SystemError,
461
0
                            "module %s has multiple Py_mod_exec slots",
462
0
                            name);
463
0
                        goto error;
464
0
                    }
465
0
                    m_exec = (_Py_modexecfunc)it.current.sl_func;
466
0
                }
467
959
                break;
468
959
            case Py_mod_multiple_interpreters:
469
939
                multiple_interpreters = it.current.sl_uint64;
470
939
                break;
471
939
            case Py_mod_gil:
472
939
                {
473
939
                    uint64_t val = it.current.sl_uint64;
474
939
                    requires_gil = (val != (uint64_t)Py_MOD_GIL_NOT_USED);
475
939
                }
476
939
                break;
477
863
            case Py_mod_abi:
478
863
                if (PyABIInfo_Check(it.current.sl_ptr, name) < 0) {
479
0
                    goto error;
480
0
                }
481
863
                break;
482
863
            case Py_mod_token:
483
0
                if (original_def && original_def != it.current.sl_ptr) {
484
0
                    PyErr_Format(
485
0
                        PyExc_SystemError,
486
0
                        "module %s: arbitrary Py_mod_token not "
487
0
                        "allowed with PyModuleDef",
488
0
                        name);
489
0
                    goto error;
490
0
                }
491
0
                token = it.current.sl_ptr;
492
0
                break;
493
            // Common case: Copy a PEP 793 slot to def_like
494
0
#define DEF_SLOT_CASE(SLOT, TYPE, SL_MEMBER, MEMBER)                        \
495
0
            case SLOT:                                                      \
496
0
                do {                                                        \
497
0
                    if (original_def) {                                     \
498
0
                        TYPE orig_value = (TYPE)original_def->MEMBER;       \
499
0
                        TYPE new_value = (TYPE)it.current.SL_MEMBER;        \
500
0
                        if (orig_value != new_value) {                      \
501
0
                            PyErr_Format(                                   \
502
0
                                PyExc_SystemError,                          \
503
0
                                "module %s: %s conflicts with "             \
504
0
                                "PyModuleDef." #MEMBER,                     \
505
0
                                name, _PySlot_GetName(it.current.sl_id));   \
506
0
                            goto error;                                     \
507
0
                        }                                                   \
508
0
                    }                                                       \
509
0
                    (def_like->MEMBER) = (TYPE)it.current.SL_MEMBER;        \
510
0
                } while (0);                                                \
511
0
                break;                                                      \
512
            /////////////////////////////////////////////////////////////////
513
0
            DEF_SLOT_CASE(Py_mod_name, char*, sl_ptr, m_name)
514
0
            DEF_SLOT_CASE(Py_mod_doc, char*, sl_ptr, m_doc)
515
0
            DEF_SLOT_CASE(Py_mod_state_size, Py_ssize_t, sl_size, m_size)
516
0
            DEF_SLOT_CASE(Py_mod_methods, PyMethodDef*, sl_ptr, m_methods)
517
0
            DEF_SLOT_CASE(Py_mod_state_traverse,
518
0
                          traverseproc, sl_func, m_traverse)
519
0
            DEF_SLOT_CASE(Py_mod_state_clear, inquiry, sl_func, m_clear)
520
3.70k
            DEF_SLOT_CASE(Py_mod_state_free, freefunc, sl_func, m_free)
521
3.70k
#undef DEF_SLOT_CASE
522
3.70k
        }
523
3.70k
    }
524
939
    if (!original_def && !_PySlotIterator_SawSlot(&it, Py_mod_abi)) {
525
0
        PyErr_Format(
526
0
            PyExc_SystemError,
527
0
            "module %s does not define Py_mod_abi,"
528
0
            " which is mandatory for modules defined from slots only.",
529
0
            name);
530
0
        goto error;
531
0
    }
532
533
#ifdef Py_GIL_DISABLED
534
    // For modules created directly from slots (not from a def), we enable
535
    // the GIL here (pairing `_PyEval_EnableGILTransient` with
536
    // an immediate `_PyImport_EnableGILAndWarn`).
537
    // For modules created from a def, the caller is responsible for this.
538
    if (!original_def && requires_gil) {
539
        PyThreadState *tstate = _PyThreadState_GET();
540
        if (_PyEval_EnableGILTransient(tstate) < 0) {
541
            goto error;
542
        }
543
        if (_PyImport_EnableGILAndWarn(tstate, nameobj) < 0) {
544
            goto error;
545
        }
546
    }
547
#endif
548
549
939
    if (def_like->m_size < 0) {
550
0
        PyErr_Format(
551
0
            PyExc_SystemError,
552
0
            "module %s: m_size may not be negative for multi-phase initialization",
553
0
            name);
554
0
        goto error;
555
0
    }
556
557
    /* By default, multi-phase init modules are expected
558
       to work under multiple interpreters. */
559
939
    if (multiple_interpreters == (int64_t)(intptr_t)Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED) {
560
0
        if (!_Py_IsMainInterpreter(interp)
561
0
            && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
562
0
        {
563
0
            goto error;
564
0
        }
565
0
    }
566
939
    else if (multiple_interpreters != (int64_t)(intptr_t)Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
567
0
             && interp->ceval.own_gil
568
0
             && !_Py_IsMainInterpreter(interp)
569
0
             && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
570
0
    {
571
0
        goto error;
572
0
    }
573
574
939
    if (create) {
575
0
        m = create(spec, original_def);
576
0
        if (m == NULL) {
577
0
            if (!PyErr_Occurred()) {
578
0
                PyErr_Format(
579
0
                    PyExc_SystemError,
580
0
                    "creation of module %s failed without setting an exception",
581
0
                    name);
582
0
            }
583
0
            goto error;
584
0
        } else {
585
0
            if (PyErr_Occurred()) {
586
0
                _PyErr_FormatFromCause(
587
0
                    PyExc_SystemError,
588
0
                    "creation of module %s raised unreported exception",
589
0
                    name);
590
0
                goto error;
591
0
            }
592
0
        }
593
939
    } else {
594
939
        m = PyModule_NewObject(nameobj);
595
939
        if (m == NULL) {
596
0
            goto error;
597
0
        }
598
939
    }
599
600
939
    if (PyModule_Check(m)) {
601
939
        PyModuleObject *mod = (PyModuleObject*)m;
602
939
        mod->md_state = NULL;
603
939
        module_copy_members_from_deflike(mod, def_like);
604
939
        if (original_def) {
605
939
            assert (!token || token == original_def);
606
939
            mod->md_token = original_def;
607
939
            mod->md_token_is_def = 1;
608
939
        }
609
0
        else {
610
0
            mod->md_token = token;
611
0
        }
612
#ifdef Py_GIL_DISABLED
613
        mod->md_requires_gil = requires_gil;
614
#else
615
939
        (void)requires_gil;
616
939
#endif
617
939
        mod->md_exec = m_exec;
618
939
    } else {
619
0
        if (def_like->m_size > 0 || def_like->m_traverse || def_like->m_clear
620
0
            || def_like->m_free)
621
0
        {
622
0
            PyErr_Format(
623
0
                PyExc_SystemError,
624
0
                "module %s is not a module object, but requests module state",
625
0
                name);
626
0
            goto error;
627
0
        }
628
0
        if (_PySlotIterator_SawSlot(&it, Py_mod_exec)) {
629
0
            PyErr_Format(
630
0
                PyExc_SystemError,
631
0
                "module %s specifies execution slots, but did not create "
632
0
                    "a ModuleType instance",
633
0
                name);
634
0
            goto error;
635
0
        }
636
0
        if (token) {
637
0
            PyErr_Format(
638
0
                PyExc_SystemError,
639
0
                "module %s specifies a token, but did not create "
640
0
                    "a ModuleType instance",
641
0
                name);
642
0
            goto error;
643
0
        }
644
0
    }
645
646
939
    if (def_like->m_methods != NULL) {
647
884
        ret = _add_methods_to_object(m, nameobj, def_like->m_methods);
648
884
        if (ret != 0) {
649
0
            goto error;
650
0
        }
651
884
    }
652
653
939
    if (def_like->m_doc != NULL) {
654
819
        ret = PyModule_SetDocString(m, def_like->m_doc);
655
819
        if (ret != 0) {
656
0
            goto error;
657
0
        }
658
819
    }
659
660
939
    Py_DECREF(nameobj);
661
939
    return m;
662
663
0
error:
664
0
    Py_DECREF(nameobj);
665
0
    Py_XDECREF(m);
666
0
    return NULL;
667
939
}
668
669
PyObject *
670
PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
671
939
{
672
939
    PyModuleDef_Init(def);
673
939
    return module_from_slots_and_spec(NULL, spec, module_api_version, def);
674
939
}
675
676
PyObject *
677
PyModule_FromSlotsAndSpec(const PySlot *slots, PyObject *spec)
678
0
{
679
0
    if (!slots) {
680
0
        PyErr_SetString(
681
0
            PyExc_SystemError,
682
0
            "PyModule_FromSlotsAndSpec called with NULL slots");
683
0
        return NULL;
684
0
    }
685
686
0
    return module_from_slots_and_spec(slots, spec, PYTHON_API_VERSION,
687
0
                                      NULL);
688
0
}
689
690
#ifdef Py_GIL_DISABLED
691
int
692
PyUnstable_Module_SetGIL(PyObject *module, void *gil)
693
{
694
    bool requires_gil = (gil != Py_MOD_GIL_NOT_USED);
695
    if (!PyModule_Check(module)) {
696
        PyErr_BadInternalCall();
697
        return -1;
698
    }
699
    ((PyModuleObject *)module)->md_requires_gil = requires_gil;
700
    return 0;
701
}
702
#endif
703
704
static int
705
run_exec_func(PyObject *module, int (*exec)(PyObject *))
706
959
{
707
959
    int ret = exec(module);
708
959
    if (ret != 0) {
709
0
        if (!PyErr_Occurred()) {
710
0
            PyErr_Format(
711
0
                PyExc_SystemError,
712
0
                "execution of %R failed without setting an exception",
713
0
                module);
714
0
        }
715
0
        return -1;
716
0
    }
717
959
    if (PyErr_Occurred()) {
718
0
        _PyErr_FormatFromCause(
719
0
            PyExc_SystemError,
720
0
            "execution of module %R raised unreported exception",
721
0
            module);
722
0
        return -1;
723
0
    }
724
959
    return 0;
725
959
}
726
727
static int
728
alloc_state(PyObject *module)
729
1.87k
{
730
1.87k
    if (!PyModule_Check(module)) {
731
0
        PyErr_Format(PyExc_TypeError, "expected module, got %T", module);
732
0
        return -1;
733
0
    }
734
1.87k
    PyModuleObject *md = (PyModuleObject*)module;
735
736
1.87k
    if (md->md_state_size >= 0) {
737
1.87k
        if (md->md_state == NULL) {
738
            /* Always set a state pointer; this serves as a marker to skip
739
             * multiple initialization (importlib.reload() is no-op) */
740
939
            md->md_state = PyMem_Malloc(md->md_state_size);
741
939
            if (!md->md_state) {
742
0
                PyErr_NoMemory();
743
0
                return -1;
744
0
            }
745
939
            memset(md->md_state, 0, md->md_state_size);
746
939
        }
747
1.87k
    }
748
1.87k
    return 0;
749
1.87k
}
750
751
int
752
PyModule_Exec(PyObject *module)
753
939
{
754
939
    if (alloc_state(module) < 0) {
755
0
        return -1;
756
0
    }
757
939
    PyModuleObject *md = (PyModuleObject*)module;
758
939
    if (md->md_exec) {
759
0
        assert(!md->md_token_is_def);
760
0
        return run_exec_func(module, md->md_exec);
761
0
    }
762
763
939
    PyModuleDef *def = _PyModule_GetDefOrNull(module);
764
939
    if (def) {
765
939
        return PyModule_ExecDef(module, def);
766
939
    }
767
0
    return 0;
768
939
}
769
770
int
771
PyModule_ExecDef(PyObject *module, PyModuleDef *def)
772
939
{
773
939
    if (alloc_state(module) < 0) {
774
0
        return -1;
775
0
    }
776
777
939
    assert(PyModule_Check(module));
778
779
939
    if (def->m_slots == NULL) {
780
0
        return 0;
781
0
    }
782
783
939
    _PySlotIterator it;
784
939
    _PySlotIterator_InitLegacy(&it, def->m_slots, _PySlot_KIND_MOD);
785
4.63k
    while (_PySlotIterator_Next(&it)) {
786
3.70k
        _Py_modexecfunc func;
787
3.70k
        switch (it.current.sl_id) {
788
0
            case Py_slot_invalid:
789
0
                return -1;
790
959
            case Py_mod_exec:
791
959
                func = (_Py_modexecfunc)it.current.sl_func;
792
959
                if (run_exec_func(module, func) < 0) {
793
0
                    return -1;
794
0
                }
795
959
                break;
796
3.70k
        }
797
3.70k
    }
798
939
    return 0;
799
939
}
800
801
int
802
PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
803
144
{
804
144
    int res;
805
144
    PyObject *name = PyModule_GetNameObject(m);
806
144
    if (name == NULL) {
807
0
        return -1;
808
0
    }
809
810
144
    res = _add_methods_to_object(m, name, functions);
811
144
    Py_DECREF(name);
812
144
    return res;
813
144
}
814
815
int
816
PyModule_SetDocString(PyObject *m, const char *doc)
817
927
{
818
927
    PyObject *v;
819
820
927
    v = PyUnicode_FromString(doc);
821
927
    if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
822
0
        Py_XDECREF(v);
823
0
        return -1;
824
0
    }
825
927
    Py_DECREF(v);
826
927
    return 0;
827
927
}
828
829
PyObject *
830
PyModule_GetDict(PyObject *m)
831
21.6k
{
832
21.6k
    if (!PyModule_Check(m)) {
833
0
        PyErr_BadInternalCall();
834
0
        return NULL;
835
0
    }
836
21.6k
    return _PyModule_GetDict(m);  // borrowed reference
837
21.6k
}
838
839
int
840
PyModule_GetStateSize(PyObject *m, Py_ssize_t *size_p)
841
0
{
842
0
    *size_p = -1;
843
0
    if (!PyModule_Check(m)) {
844
0
        PyErr_Format(PyExc_TypeError, "expected module, got %T", m);
845
0
        return -1;
846
0
    }
847
0
    PyModuleObject *mod = (PyModuleObject *)m;
848
0
    *size_p = mod->md_state_size;
849
0
    return 0;
850
0
}
851
852
int
853
PyModule_GetToken_DuringGC(PyObject *m, void **token_p)
854
0
{
855
0
    *token_p = NULL;
856
0
    if (!PyModule_Check(m)) {
857
0
        return -1;
858
0
    }
859
0
    *token_p = _PyModule_GetToken(m);
860
0
    return 0;
861
0
}
862
863
int
864
PyModule_GetToken(PyObject *m, void **token_p)
865
0
{
866
0
    *token_p = NULL;
867
0
    if (!PyModule_Check(m)) {
868
0
        PyErr_Format(PyExc_TypeError, "expected module, got %T", m);
869
0
        return -1;
870
0
    }
871
0
    *token_p = _PyModule_GetToken(m);
872
0
    return 0;
873
0
}
874
875
PyObject*
876
PyModule_GetNameObject(PyObject *mod)
877
144
{
878
144
    if (!PyModule_Check(mod)) {
879
0
        PyErr_BadArgument();
880
0
        return NULL;
881
0
    }
882
144
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
883
144
    if (dict == NULL || !PyDict_Check(dict)) {
884
0
        goto error;
885
0
    }
886
144
    PyObject *name;
887
144
    if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
888
        // error or not found
889
0
        goto error;
890
0
    }
891
144
    if (!PyUnicode_Check(name)) {
892
0
        Py_DECREF(name);
893
0
        goto error;
894
0
    }
895
144
    return name;
896
897
0
error:
898
0
    if (!PyErr_Occurred()) {
899
0
        PyErr_SetString(PyExc_SystemError, "nameless module");
900
0
    }
901
0
    return NULL;
902
144
}
903
904
const char *
905
PyModule_GetName(PyObject *m)
906
0
{
907
0
    PyObject *name = PyModule_GetNameObject(m);
908
0
    if (name == NULL) {
909
0
        return NULL;
910
0
    }
911
0
    assert(Py_REFCNT(name) >= 2);
912
0
    Py_DECREF(name);   /* module dict has still a reference */
913
0
    return PyUnicode_AsUTF8(name);
914
0
}
915
916
PyObject*
917
_PyModule_GetFilenameObject(PyObject *mod)
918
29
{
919
    // We return None to indicate "not found" or "bogus".
920
29
    if (!PyModule_Check(mod)) {
921
0
        PyErr_BadArgument();
922
0
        return NULL;
923
0
    }
924
29
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
925
29
    if (dict == NULL) {
926
        // The module has been tampered with.
927
0
        Py_RETURN_NONE;
928
0
    }
929
29
    PyObject *fileobj;
930
29
    int res = PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj);
931
29
    if (res < 0) {
932
0
        return NULL;
933
0
    }
934
29
    if (res == 0) {
935
        // __file__ isn't set.  There are several reasons why this might
936
        // be so, most of them valid reasons.  If it's the __main__
937
        // module then we're running the REPL or with -c.  Otherwise
938
        // it's a namespace package or other module with a loader that
939
        // isn't disk-based.  It could also be that a user created
940
        // a module manually but without manually setting __file__.
941
25
        Py_RETURN_NONE;
942
25
    }
943
4
    if (!PyUnicode_Check(fileobj)) {
944
0
        Py_DECREF(fileobj);
945
0
        Py_RETURN_NONE;
946
0
    }
947
4
    return fileobj;
948
4
}
949
950
PyObject*
951
PyModule_GetFilenameObject(PyObject *mod)
952
29
{
953
29
    PyObject *fileobj = _PyModule_GetFilenameObject(mod);
954
29
    if (fileobj == NULL) {
955
0
        return NULL;
956
0
    }
957
29
    if (fileobj == Py_None) {
958
25
        PyErr_SetString(PyExc_SystemError, "module filename missing");
959
25
        return NULL;
960
25
    }
961
4
    return fileobj;
962
29
}
963
964
const char *
965
PyModule_GetFilename(PyObject *m)
966
0
{
967
0
    PyObject *fileobj;
968
0
    const char *utf8;
969
0
    fileobj = PyModule_GetFilenameObject(m);
970
0
    if (fileobj == NULL)
971
0
        return NULL;
972
0
    utf8 = PyUnicode_AsUTF8(fileobj);
973
0
    Py_DECREF(fileobj);   /* module dict has still a reference */
974
0
    return utf8;
975
0
}
976
977
Py_ssize_t
978
_PyModule_GetFilenameUTF8(PyObject *mod, char *buffer, Py_ssize_t maxlen)
979
0
{
980
    // We "return" an empty string for an invalid module
981
    // and for a missing, empty, or invalid filename.
982
0
    assert(maxlen >= 0);
983
0
    Py_ssize_t size = -1;
984
0
    PyObject *filenameobj = _PyModule_GetFilenameObject(mod);
985
0
    if (filenameobj == NULL) {
986
0
        return -1;
987
0
    }
988
0
    if (filenameobj == Py_None) {
989
        // It is missing or invalid.
990
0
        buffer[0] = '\0';
991
0
        size = 0;
992
0
    }
993
0
    else {
994
0
        const char *filename = PyUnicode_AsUTF8AndSize(filenameobj, &size);
995
0
        assert(size >= 0);
996
0
        if (size > maxlen) {
997
0
            size = -1;
998
0
            PyErr_SetString(PyExc_ValueError, "__file__ too long");
999
0
        }
1000
0
        else {
1001
0
            (void)strcpy(buffer, filename);
1002
0
        }
1003
0
    }
1004
0
    Py_DECREF(filenameobj);
1005
0
    return size;
1006
0
}
1007
1008
PyModuleDef*
1009
PyModule_GetDef(PyObject* m)
1010
4
{
1011
4
    if (!PyModule_Check(m)) {
1012
0
        PyErr_BadArgument();
1013
0
        return NULL;
1014
0
    }
1015
4
    return _PyModule_GetDefOrNull(m);
1016
4
}
1017
1018
void*
1019
PyModule_GetState_DuringGC(PyObject* m)
1020
0
{
1021
0
    if (!PyModule_Check(m)) {
1022
0
        return NULL;
1023
0
    }
1024
0
    return _PyModule_GetState(m);
1025
0
}
1026
1027
void*
1028
PyModule_GetState(PyObject* m)
1029
28.5M
{
1030
28.5M
    if (!PyModule_Check(m)) {
1031
0
        PyErr_BadArgument();
1032
0
        return NULL;
1033
0
    }
1034
28.5M
    return _PyModule_GetState(m);
1035
28.5M
}
1036
1037
void
1038
_PyModule_Clear(PyObject *m)
1039
0
{
1040
0
    PyObject *d = ((PyModuleObject *)m)->md_dict;
1041
0
    if (d != NULL)
1042
0
        _PyModule_ClearDict(d);
1043
0
}
1044
1045
void
1046
_PyModule_ClearDict(PyObject *d)
1047
0
{
1048
    /* To make the execution order of destructors for global
1049
       objects a bit more predictable, we first zap all objects
1050
       whose name starts with a single underscore, before we clear
1051
       the entire dictionary.  We zap them by replacing them with
1052
       None, rather than deleting them from the dictionary, to
1053
       avoid rehashing the dictionary (to some extent). */
1054
1055
0
    Py_ssize_t pos;
1056
0
    PyObject *key, *value;
1057
1058
0
    int verbose = _Py_GetConfig()->verbose;
1059
1060
    /* First, clear only names starting with a single underscore */
1061
0
    pos = 0;
1062
0
    while (PyDict_Next(d, &pos, &key, &value)) {
1063
0
        if (value != Py_None && PyUnicode_Check(key)) {
1064
0
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
1065
0
                PyUnicode_READ_CHAR(key, 1) != '_') {
1066
0
                if (verbose > 1) {
1067
0
                    const char *s = PyUnicode_AsUTF8(key);
1068
0
                    if (s != NULL)
1069
0
                        PySys_WriteStderr("#   clear[1] %s\n", s);
1070
0
                    else
1071
0
                        PyErr_Clear();
1072
0
                }
1073
0
                if (PyDict_SetItem(d, key, Py_None) != 0) {
1074
0
                    PyErr_FormatUnraisable("Exception ignored while "
1075
0
                                           "clearing module dict");
1076
0
                }
1077
0
            }
1078
0
        }
1079
0
    }
1080
1081
    /* Next, clear all names except for __builtins__ */
1082
0
    pos = 0;
1083
0
    while (PyDict_Next(d, &pos, &key, &value)) {
1084
0
        if (value != Py_None && PyUnicode_Check(key)) {
1085
0
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
1086
0
                !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
1087
0
            {
1088
0
                if (verbose > 1) {
1089
0
                    const char *s = PyUnicode_AsUTF8(key);
1090
0
                    if (s != NULL)
1091
0
                        PySys_WriteStderr("#   clear[2] %s\n", s);
1092
0
                    else
1093
0
                        PyErr_Clear();
1094
0
                }
1095
0
                if (PyDict_SetItem(d, key, Py_None) != 0) {
1096
0
                    PyErr_FormatUnraisable("Exception ignored while "
1097
0
                                           "clearing module dict");
1098
0
                }
1099
0
            }
1100
0
        }
1101
0
    }
1102
1103
    /* Note: we leave __builtins__ in place, so that destructors
1104
       of non-global objects defined in this module can still use
1105
       builtins, in particularly 'None'. */
1106
1107
0
}
1108
1109
/*[clinic input]
1110
class module "PyModuleObject *" "&PyModule_Type"
1111
[clinic start generated code]*/
1112
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
1113
1114
#include "clinic/moduleobject.c.h"
1115
1116
/* Methods */
1117
1118
/*[clinic input]
1119
module.__init__
1120
    name: unicode
1121
    doc: object = None
1122
1123
Create a module object.
1124
1125
The name must be a string; the optional doc argument can have any type.
1126
[clinic start generated code]*/
1127
1128
static int
1129
module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
1130
/*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
1131
7.44k
{
1132
7.44k
    return module_init_dict(self, self->md_dict, name, doc);
1133
7.44k
}
1134
1135
static void
1136
module_dealloc(PyObject *self)
1137
4.88k
{
1138
4.88k
    PyModuleObject *m = _PyModule_CAST(self);
1139
1140
4.88k
    PyObject_GC_UnTrack(m);
1141
1142
4.88k
    int verbose = _Py_GetConfig()->verbose;
1143
4.88k
    if (verbose && m->md_name) {
1144
0
        PySys_FormatStderr("# destroy %U\n", m->md_name);
1145
0
    }
1146
4.88k
    FT_CLEAR_WEAKREFS(self, m->md_weaklist);
1147
1148
4.88k
    assert_def_missing_or_redundant(m);
1149
    /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
1150
4.88k
    if (m->md_state_free && (m->md_state_size <= 0 || m->md_state != NULL))
1151
0
    {
1152
0
        m->md_state_free(m);
1153
0
    }
1154
1155
4.88k
    Py_XDECREF(m->md_dict);
1156
4.88k
    Py_XDECREF(m->md_name);
1157
4.88k
    if (m->md_state != NULL) {
1158
0
        PyMem_Free(m->md_state);
1159
0
    }
1160
4.88k
    Py_TYPE(m)->tp_free((PyObject *)m);
1161
4.88k
}
1162
1163
static PyObject *
1164
module_repr(PyObject *self)
1165
0
{
1166
0
    PyModuleObject *m = _PyModule_CAST(self);
1167
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1168
0
    return _PyImport_ImportlibModuleRepr(interp, (PyObject *)m);
1169
0
}
1170
1171
/* Check if the "_initializing" attribute of the module spec is set to true.
1172
 */
1173
int
1174
_PyModuleSpec_IsInitializing(PyObject *spec)
1175
4.88M
{
1176
4.88M
    if (spec == NULL) {
1177
0
        return 0;
1178
0
    }
1179
4.88M
    PyObject *value;
1180
4.88M
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_initializing), &value);
1181
4.88M
    if (rc > 0) {
1182
4.63M
        rc = PyObject_IsTrue(value);
1183
4.63M
        Py_DECREF(value);
1184
4.63M
    }
1185
4.88M
    return rc;
1186
4.88M
}
1187
1188
/* Check if the submodule name is in the "_uninitialized_submodules" attribute
1189
   of the module spec.
1190
 */
1191
int
1192
_PyModuleSpec_IsUninitializedSubmodule(PyObject *spec, PyObject *name)
1193
2.46k
{
1194
2.46k
    if (spec == NULL) {
1195
0
         return 0;
1196
0
    }
1197
1198
2.46k
    PyObject *value;
1199
2.46k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_uninitialized_submodules), &value);
1200
2.46k
    if (rc > 0) {
1201
2.18k
        rc = PySequence_Contains(value, name);
1202
2.18k
        Py_DECREF(value);
1203
2.18k
    }
1204
2.46k
    return rc;
1205
2.46k
}
1206
1207
int
1208
_PyModuleSpec_GetFileOrigin(PyObject *spec, PyObject **p_origin)
1209
2.49k
{
1210
2.49k
    PyObject *has_location = NULL;
1211
2.49k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(has_location), &has_location);
1212
2.49k
    if (rc <= 0) {
1213
288
        return rc;
1214
288
    }
1215
    // If origin is not a location, or doesn't exist, or is not a str, we could consider falling
1216
    // back to module.__file__. But the cases in which module.__file__ is not __spec__.origin
1217
    // are cases in which we probably shouldn't be guessing.
1218
2.21k
    rc = PyObject_IsTrue(has_location);
1219
2.21k
    Py_DECREF(has_location);
1220
2.21k
    if (rc <= 0) {
1221
786
        return rc;
1222
786
    }
1223
    // has_location is true, so origin is a location
1224
1.42k
    PyObject *origin = NULL;
1225
1.42k
    rc = PyObject_GetOptionalAttr(spec, &_Py_ID(origin), &origin);
1226
1.42k
    if (rc <= 0) {
1227
0
        return rc;
1228
0
    }
1229
1.42k
    assert(origin != NULL);
1230
1.42k
    if (!PyUnicode_Check(origin)) {
1231
0
        Py_DECREF(origin);
1232
0
        return 0;
1233
0
    }
1234
1.42k
    *p_origin = origin;
1235
1.42k
    return 1;
1236
1.42k
}
1237
1238
int
1239
_PyModule_IsPossiblyShadowing(PyObject *origin)
1240
2.49k
{
1241
    // origin must be a unicode subtype
1242
    // Returns 1 if the module at origin could be shadowing a module of the
1243
    // same name later in the module search path. The condition we check is basically:
1244
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
1245
    // return not sys.flags.safe_path and root == (sys.path[0] or os.getcwd())
1246
    // Returns 0 otherwise (or if we aren't sure)
1247
    // Returns -1 if an error occurred that should be propagated
1248
2.49k
    if (origin == NULL) {
1249
1.07k
        return 0;
1250
1.07k
    }
1251
1252
    // not sys.flags.safe_path
1253
1.42k
    const PyConfig *config = _Py_GetConfig();
1254
1.42k
    if (config->safe_path) {
1255
0
        return 0;
1256
0
    }
1257
1258
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
1259
1.42k
    wchar_t root[MAXPATHLEN + 1];
1260
1.42k
    Py_ssize_t size = PyUnicode_AsWideChar(origin, root, MAXPATHLEN);
1261
1.42k
    if (size < 0) {
1262
0
        return -1;
1263
0
    }
1264
1.42k
    assert(size <= MAXPATHLEN);
1265
1.42k
    root[size] = L'\0';
1266
1267
1.42k
    wchar_t *sep = wcsrchr(root, SEP);
1268
1.42k
    if (sep == NULL) {
1269
0
        return 0;
1270
0
    }
1271
    // If it's a package then we need to look one directory further up
1272
1.42k
    if (wcscmp(sep + 1, L"__init__.py") == 0) {
1273
0
        *sep = L'\0';
1274
0
        sep = wcsrchr(root, SEP);
1275
0
        if (sep == NULL) {
1276
0
            return 0;
1277
0
        }
1278
0
    }
1279
1.42k
    *sep = L'\0';
1280
1281
    // sys.path[0] or os.getcwd()
1282
1.42k
    wchar_t *sys_path_0 = config->sys_path_0;
1283
1.42k
    if (!sys_path_0) {
1284
1.42k
        return 0;
1285
1.42k
    }
1286
1287
0
    wchar_t sys_path_0_buf[MAXPATHLEN];
1288
0
    if (sys_path_0[0] == L'\0') {
1289
        // if sys.path[0] == "", treat it as if it were the current directory
1290
0
        if (!_Py_wgetcwd(sys_path_0_buf, MAXPATHLEN)) {
1291
            // If we failed to getcwd, don't raise an exception and instead
1292
            // let the caller proceed assuming no shadowing
1293
0
            return 0;
1294
0
        }
1295
0
        sys_path_0 = sys_path_0_buf;
1296
0
    }
1297
1298
0
    int result = wcscmp(sys_path_0, root) == 0;
1299
0
    return result;
1300
0
}
1301
1302
// Check if `name` is a lazily pending submodule of module `m`.
1303
// Returns a new reference on success, or NULL with no error set.
1304
static PyObject *
1305
try_load_lazy_submodule(PyModuleObject *m, PyObject *name)
1306
1.36M
{
1307
1.36M
    PyObject *mod_name;
1308
1.36M
    int rc = PyDict_GetItemRef(m->md_dict, &_Py_ID(__name__), &mod_name);
1309
1.36M
    if (rc <= 0) {
1310
0
        return NULL;
1311
0
    }
1312
1.36M
    if (!PyUnicode_Check(mod_name)) {
1313
0
        Py_DECREF(mod_name);
1314
0
        return NULL;
1315
0
    }
1316
1.36M
    PyObject *result = _PyImport_TryLoadLazySubmodule(mod_name, name);
1317
1.36M
    Py_DECREF(mod_name);
1318
1.36M
    if (result == NULL) {
1319
1.36M
        PyErr_Clear();
1320
1.36M
        return NULL;
1321
1.36M
    }
1322
0
    if (PyDict_SetItem(m->md_dict, name, result) < 0) {
1323
0
        Py_DECREF(result);
1324
0
        return NULL;
1325
0
    }
1326
0
    return result;
1327
0
}
1328
1329
PyObject*
1330
_Py_module_getattro_impl(PyModuleObject *m, PyObject *name, int suppress)
1331
8.93M
{
1332
    // When suppress=1, this function suppresses AttributeError.
1333
8.93M
    PyObject *attr, *mod_name, *getattr;
1334
8.93M
    attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
1335
8.93M
    if (attr) {
1336
7.56M
        if (PyLazyImport_CheckExact(attr)) {
1337
            // gh-144957: Module __getattr__ should get a chance to provide
1338
            // the attribute before resolving a lazy import placeholder.
1339
0
            if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__getattr__), &getattr) < 0) {
1340
0
                Py_DECREF(attr);
1341
0
                return NULL;
1342
0
            }
1343
0
            if (getattr) {
1344
0
                PyObject *result = PyObject_CallOneArg(getattr, name);
1345
0
                Py_DECREF(getattr);
1346
0
                if (result != NULL) {
1347
0
                    Py_DECREF(attr);
1348
0
                    return result;
1349
0
                }
1350
0
                if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1351
0
                    Py_DECREF(attr);
1352
0
                    return NULL;
1353
0
                }
1354
0
                PyErr_Clear();
1355
0
            }
1356
0
            PyObject *new_value = _PyImport_LoadLazyImportTstate(
1357
0
                PyThreadState_GET(), attr);
1358
0
            if (new_value == NULL) {
1359
0
                if (suppress &&
1360
0
                    PyErr_ExceptionMatches(PyExc_ImportCycleError)) {
1361
                    // ImportCycleError is raised when a lazy object tries
1362
                    // to import itself. In this case, the error should not
1363
                    // propagate to the caller and instead treated as if the
1364
                    // attribute doesn't exist.
1365
0
                    PyErr_Clear();
1366
0
                }
1367
0
                Py_DECREF(attr);
1368
0
                return NULL;
1369
0
            }
1370
1371
0
            if (PyDict_SetItem(m->md_dict, name, new_value) < 0) {
1372
0
                Py_CLEAR(new_value);
1373
0
            }
1374
0
            Py_DECREF(attr);
1375
0
            return new_value;
1376
0
        }
1377
7.56M
        return attr;
1378
7.56M
    }
1379
1.36M
    if (suppress == 1) {
1380
1.36M
        if (PyErr_Occurred()) {
1381
            // pass up non-AttributeError exception
1382
0
            return NULL;
1383
0
        }
1384
1.36M
    }
1385
2.46k
    else {
1386
2.46k
        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1387
            // pass up non-AttributeError exception
1388
0
            return NULL;
1389
0
        }
1390
2.46k
        PyErr_Clear();
1391
2.46k
    }
1392
1.36M
    assert(m->md_dict != NULL);
1393
1.36M
    attr = try_load_lazy_submodule(m, name);
1394
1.36M
    if (attr != NULL) {
1395
0
        return attr;
1396
0
    }
1397
1.36M
    if (PyErr_Occurred()) {
1398
0
        return NULL;
1399
0
    }
1400
1.36M
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__getattr__), &getattr) < 0) {
1401
0
        return NULL;
1402
0
    }
1403
1.36M
    if (getattr) {
1404
816
        PyObject *result = PyObject_CallOneArg(getattr, name);
1405
816
        if (result == NULL && suppress == 1 && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1406
            // suppress AttributeError
1407
812
            PyErr_Clear();
1408
812
        }
1409
816
        Py_DECREF(getattr);
1410
816
        return result;
1411
816
    }
1412
1413
    // The attribute was not found.  We make a best effort attempt at a useful error message,
1414
    // but only if we're not suppressing AttributeError.
1415
1.36M
    if (suppress == 1) {
1416
1.36M
        return NULL;
1417
1.36M
    }
1418
2.46k
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__name__), &mod_name) < 0) {
1419
0
        return NULL;
1420
0
    }
1421
2.46k
    if (!mod_name || !PyUnicode_Check(mod_name)) {
1422
0
        Py_XDECREF(mod_name);
1423
0
        PyErr_Format(PyExc_AttributeError,
1424
0
                    "module has no attribute '%U'", name);
1425
0
        return NULL;
1426
0
    }
1427
2.46k
    PyObject *spec;
1428
2.46k
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__spec__), &spec) < 0) {
1429
0
        Py_DECREF(mod_name);
1430
0
        return NULL;
1431
0
    }
1432
2.46k
    if (spec == NULL) {
1433
0
        PyErr_Format(PyExc_AttributeError,
1434
0
                     "module '%U' has no attribute '%U'",
1435
0
                     mod_name, name);
1436
0
        Py_DECREF(mod_name);
1437
0
        return NULL;
1438
0
    }
1439
1440
2.46k
    PyObject *origin = NULL;
1441
2.46k
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
1442
0
        goto done;
1443
0
    }
1444
1445
2.46k
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
1446
2.46k
    if (is_possibly_shadowing < 0) {
1447
0
        goto done;
1448
0
    }
1449
2.46k
    int is_possibly_shadowing_stdlib = 0;
1450
2.46k
    if (is_possibly_shadowing) {
1451
0
        PyObject *stdlib_modules;
1452
0
        if (PySys_GetOptionalAttrString("stdlib_module_names", &stdlib_modules) < 0) {
1453
0
            goto done;
1454
0
        }
1455
0
        if (stdlib_modules && PyAnySet_Check(stdlib_modules)) {
1456
0
            is_possibly_shadowing_stdlib = PySet_Contains(stdlib_modules, mod_name);
1457
0
            if (is_possibly_shadowing_stdlib < 0) {
1458
0
                Py_DECREF(stdlib_modules);
1459
0
                goto done;
1460
0
            }
1461
0
        }
1462
0
        Py_XDECREF(stdlib_modules);
1463
0
    }
1464
1465
2.46k
    if (is_possibly_shadowing_stdlib) {
1466
0
        assert(origin);
1467
0
        PyErr_Format(PyExc_AttributeError,
1468
0
                    "module '%U' has no attribute '%U' "
1469
0
                    "(consider renaming '%U' since it has the same "
1470
0
                    "name as the standard library module named '%U' "
1471
0
                    "and prevents importing that standard library module)",
1472
0
                    mod_name, name, origin, mod_name);
1473
0
    }
1474
2.46k
    else {
1475
2.46k
        int rc = _PyModuleSpec_IsInitializing(spec);
1476
2.46k
        if (rc < 0) {
1477
0
            goto done;
1478
0
        }
1479
2.46k
        else if (rc > 0) {
1480
0
            if (is_possibly_shadowing) {
1481
0
                assert(origin);
1482
                // For non-stdlib modules, only mention the possibility of
1483
                // shadowing if the module is being initialized.
1484
0
                PyErr_Format(PyExc_AttributeError,
1485
0
                            "module '%U' has no attribute '%U' "
1486
0
                            "(consider renaming '%U' if it has the same name "
1487
0
                            "as a library you intended to import)",
1488
0
                            mod_name, name, origin);
1489
0
            }
1490
0
            else if (origin) {
1491
0
                PyErr_Format(PyExc_AttributeError,
1492
0
                            "partially initialized "
1493
0
                            "module '%U' from '%U' has no attribute '%U' "
1494
0
                            "(most likely due to a circular import)",
1495
0
                            mod_name, origin, name);
1496
0
            }
1497
0
            else {
1498
0
                PyErr_Format(PyExc_AttributeError,
1499
0
                            "partially initialized "
1500
0
                            "module '%U' has no attribute '%U' "
1501
0
                            "(most likely due to a circular import)",
1502
0
                            mod_name, name);
1503
0
            }
1504
0
        }
1505
2.46k
        else {
1506
2.46k
            assert(rc == 0);
1507
2.46k
            rc = _PyModuleSpec_IsUninitializedSubmodule(spec, name);
1508
2.46k
            if (rc > 0) {
1509
0
                PyErr_Format(PyExc_AttributeError,
1510
0
                            "cannot access submodule '%U' of module '%U' "
1511
0
                            "(most likely due to a circular import)",
1512
0
                            name, mod_name);
1513
0
            }
1514
2.46k
            else if (rc == 0) {
1515
2.46k
                PyErr_Format(PyExc_AttributeError,
1516
2.46k
                            "module '%U' has no attribute '%U'",
1517
2.46k
                            mod_name, name);
1518
2.46k
            }
1519
2.46k
        }
1520
2.46k
    }
1521
1522
2.46k
done:
1523
2.46k
    Py_XDECREF(origin);
1524
2.46k
    Py_DECREF(spec);
1525
2.46k
    Py_DECREF(mod_name);
1526
2.46k
    return NULL;
1527
2.46k
}
1528
1529
1530
PyObject*
1531
_Py_module_getattro(PyObject *self, PyObject *name)
1532
161k
{
1533
161k
    PyModuleObject *m = _PyModule_CAST(self);
1534
161k
    return _Py_module_getattro_impl(m, name, 0);
1535
161k
}
1536
1537
static int
1538
module_traverse(PyObject *self, visitproc visit, void *arg)
1539
123k
{
1540
123k
    PyModuleObject *m = _PyModule_CAST(self);
1541
1542
123k
    assert_def_missing_or_redundant(m);
1543
    /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
1544
123k
    if (m->md_state_traverse && (m->md_state_size <= 0 || m->md_state != NULL))
1545
18.5k
    {
1546
18.5k
        int res = m->md_state_traverse((PyObject*)m, visit, arg);
1547
18.5k
        if (res)
1548
0
            return res;
1549
18.5k
    }
1550
1551
123k
    Py_VISIT(m->md_dict);
1552
123k
    return 0;
1553
123k
}
1554
1555
static int
1556
module_clear(PyObject *self)
1557
0
{
1558
0
    PyModuleObject *m = _PyModule_CAST(self);
1559
1560
0
    assert_def_missing_or_redundant(m);
1561
    /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
1562
0
    if (m->md_state_clear && (m->md_state_size <= 0 || m->md_state != NULL))
1563
0
    {
1564
0
        int res = m->md_state_clear((PyObject*)m);
1565
0
        if (PyErr_Occurred()) {
1566
0
            PyErr_FormatUnraisable("Exception ignored in m_clear of module%s%V",
1567
0
                                   m->md_name ? " " : "",
1568
0
                                   m->md_name, "");
1569
0
        }
1570
0
        if (res) {
1571
0
            return res;
1572
0
        }
1573
0
    }
1574
0
    Py_CLEAR(m->md_dict);
1575
0
    return 0;
1576
0
}
1577
1578
static PyObject *
1579
module_dir(PyObject *self, PyObject *args)
1580
46
{
1581
46
    PyObject *result = NULL;
1582
46
    PyObject *dict;
1583
46
    if (PyModule_CheckExact(self)) {
1584
46
        dict = Py_NewRef(((PyModuleObject *)self)->md_dict);
1585
46
    } else {
1586
0
        dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
1587
0
    }
1588
1589
46
    if (dict != NULL) {
1590
46
        if (PyDict_Check(dict)) {
1591
46
            PyObject *dirfunc = PyDict_GetItemWithError(dict, &_Py_ID(__dir__));
1592
46
            if (dirfunc) {
1593
0
                result = _PyObject_CallNoArgs(dirfunc);
1594
0
            }
1595
46
            else if (!PyErr_Occurred()) {
1596
46
                result = PyDict_Keys(dict);
1597
46
            }
1598
46
        }
1599
0
        else {
1600
0
            PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
1601
0
        }
1602
46
    }
1603
1604
46
    Py_XDECREF(dict);
1605
46
    return result;
1606
46
}
1607
1608
static PyMethodDef module_methods[] = {
1609
    {"__dir__", module_dir, METH_NOARGS,
1610
     PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
1611
    {0}
1612
};
1613
1614
static PyObject *
1615
module_load_dict(PyModuleObject *m)
1616
0
{
1617
0
    PyObject *dict = PyObject_GetAttr((PyObject *)m, &_Py_ID(__dict__));
1618
0
    if (dict == NULL) {
1619
0
        return NULL;
1620
0
    }
1621
0
    if (!PyDict_Check(dict)) {
1622
0
        PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
1623
0
        Py_DECREF(dict);
1624
0
        return NULL;
1625
0
    }
1626
0
    return dict;
1627
0
}
1628
1629
static PyObject *
1630
module_get_annotate(PyObject *self, void *Py_UNUSED(ignored))
1631
0
{
1632
0
    PyModuleObject *m = _PyModule_CAST(self);
1633
1634
0
    PyObject *dict = module_load_dict(m);
1635
0
    if (dict == NULL) {
1636
0
        return NULL;
1637
0
    }
1638
1639
0
    PyObject *annotate;
1640
0
    if (PyDict_GetItemRef(dict, &_Py_ID(__annotate__), &annotate) == 0) {
1641
0
        annotate = Py_None;
1642
0
        if (PyDict_SetItem(dict, &_Py_ID(__annotate__), annotate) == -1) {
1643
0
            Py_CLEAR(annotate);
1644
0
        }
1645
0
    }
1646
0
    Py_DECREF(dict);
1647
0
    return annotate;
1648
0
}
1649
1650
static int
1651
module_set_annotate(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
1652
0
{
1653
0
    PyModuleObject *m = _PyModule_CAST(self);
1654
0
    if (value == NULL) {
1655
0
        PyErr_SetString(PyExc_TypeError, "cannot delete __annotate__ attribute");
1656
0
        return -1;
1657
0
    }
1658
1659
0
    PyObject *dict = module_load_dict(m);
1660
0
    if (dict == NULL) {
1661
0
        return -1;
1662
0
    }
1663
1664
0
    if (!Py_IsNone(value) && !PyCallable_Check(value)) {
1665
0
        PyErr_SetString(PyExc_TypeError, "__annotate__ must be callable or None");
1666
0
        Py_DECREF(dict);
1667
0
        return -1;
1668
0
    }
1669
1670
0
    if (PyDict_SetItem(dict, &_Py_ID(__annotate__), value) == -1) {
1671
0
        Py_DECREF(dict);
1672
0
        return -1;
1673
0
    }
1674
0
    if (!Py_IsNone(value)) {
1675
0
        if (PyDict_Pop(dict, &_Py_ID(__annotations__), NULL) == -1) {
1676
0
            Py_DECREF(dict);
1677
0
            return -1;
1678
0
        }
1679
0
    }
1680
0
    Py_DECREF(dict);
1681
0
    return 0;
1682
0
}
1683
1684
static PyObject *
1685
module_get_annotations(PyObject *self, void *Py_UNUSED(ignored))
1686
0
{
1687
0
    PyModuleObject *m = _PyModule_CAST(self);
1688
1689
0
    PyObject *dict = module_load_dict(m);
1690
0
    if (dict == NULL) {
1691
0
        return NULL;
1692
0
    }
1693
1694
0
    PyObject *annotations;
1695
0
    if (PyDict_GetItemRef(dict, &_Py_ID(__annotations__), &annotations) == 0) {
1696
0
        PyObject *spec;
1697
0
        if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__spec__), &spec) < 0) {
1698
0
            Py_DECREF(dict);
1699
0
            return NULL;
1700
0
        }
1701
0
        bool is_initializing = false;
1702
0
        if (spec != NULL) {
1703
0
            int rc = _PyModuleSpec_IsInitializing(spec);
1704
0
            if (rc < 0) {
1705
0
                Py_DECREF(spec);
1706
0
                Py_DECREF(dict);
1707
0
                return NULL;
1708
0
            }
1709
0
            Py_DECREF(spec);
1710
0
            if (rc) {
1711
0
                is_initializing = true;
1712
0
            }
1713
0
        }
1714
1715
0
        PyObject *annotate;
1716
0
        int annotate_result = PyDict_GetItemRef(dict, &_Py_ID(__annotate__), &annotate);
1717
0
        if (annotate_result < 0) {
1718
0
            Py_DECREF(dict);
1719
0
            return NULL;
1720
0
        }
1721
0
        if (annotate_result == 1 && PyCallable_Check(annotate)) {
1722
0
            PyObject *one = _PyLong_GetOne();
1723
0
            annotations = _PyObject_CallOneArg(annotate, one);
1724
0
            if (annotations == NULL) {
1725
0
                Py_DECREF(annotate);
1726
0
                Py_DECREF(dict);
1727
0
                return NULL;
1728
0
            }
1729
0
            if (!PyDict_Check(annotations)) {
1730
0
                PyErr_Format(PyExc_TypeError,
1731
0
                             "__annotate__() must return a dict, not %T",
1732
0
                             annotations);
1733
0
                Py_DECREF(annotate);
1734
0
                Py_DECREF(annotations);
1735
0
                Py_DECREF(dict);
1736
0
                return NULL;
1737
0
            }
1738
0
        }
1739
0
        else {
1740
0
            annotations = PyDict_New();
1741
0
        }
1742
0
        Py_XDECREF(annotate);
1743
        // Do not cache annotations if the module is still initializing
1744
0
        if (annotations && !is_initializing) {
1745
0
            int result = PyDict_SetItem(
1746
0
                    dict, &_Py_ID(__annotations__), annotations);
1747
0
            if (result) {
1748
0
                Py_CLEAR(annotations);
1749
0
            }
1750
0
        }
1751
0
    }
1752
0
    Py_DECREF(dict);
1753
0
    return annotations;
1754
0
}
1755
1756
static int
1757
module_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
1758
0
{
1759
0
    PyModuleObject *m = _PyModule_CAST(self);
1760
1761
0
    PyObject *dict = module_load_dict(m);
1762
0
    if (dict == NULL) {
1763
0
        return -1;
1764
0
    }
1765
1766
0
    int ret = -1;
1767
0
    if (value != NULL) {
1768
        /* set */
1769
0
        ret = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
1770
0
    }
1771
0
    else {
1772
        /* delete */
1773
0
        ret = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
1774
0
        if (ret == 0) {
1775
0
            PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__annotations__));
1776
0
            ret = -1;
1777
0
        }
1778
0
        else if (ret > 0) {
1779
0
            ret = 0;
1780
0
        }
1781
0
    }
1782
0
    if (ret == 0 && PyDict_Pop(dict, &_Py_ID(__annotate__), NULL) < 0) {
1783
0
        ret = -1;
1784
0
    }
1785
1786
0
    Py_DECREF(dict);
1787
0
    return ret;
1788
0
}
1789
1790
static PyGetSetDef module_getsets[] = {
1791
    {"__annotations__", module_get_annotations, module_set_annotations},
1792
    {"__annotate__", module_get_annotate, module_set_annotate},
1793
    {NULL}
1794
};
1795
1796
PyTypeObject PyModule_Type = {
1797
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1798
    "module",                                   /* tp_name */
1799
    sizeof(PyModuleObject),                     /* tp_basicsize */
1800
    0,                                          /* tp_itemsize */
1801
    module_dealloc,                             /* tp_dealloc */
1802
    0,                                          /* tp_vectorcall_offset */
1803
    0,                                          /* tp_getattr */
1804
    0,                                          /* tp_setattr */
1805
    0,                                          /* tp_as_async */
1806
    module_repr,                                /* tp_repr */
1807
    0,                                          /* tp_as_number */
1808
    0,                                          /* tp_as_sequence */
1809
    0,                                          /* tp_as_mapping */
1810
    0,                                          /* tp_hash */
1811
    0,                                          /* tp_call */
1812
    0,                                          /* tp_str */
1813
    _Py_module_getattro,                        /* tp_getattro */
1814
    PyObject_GenericSetAttr,                    /* tp_setattro */
1815
    0,                                          /* tp_as_buffer */
1816
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1817
        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
1818
    module___init____doc__,                     /* tp_doc */
1819
    module_traverse,                            /* tp_traverse */
1820
    module_clear,                               /* tp_clear */
1821
    0,                                          /* tp_richcompare */
1822
    offsetof(PyModuleObject, md_weaklist),      /* tp_weaklistoffset */
1823
    0,                                          /* tp_iter */
1824
    0,                                          /* tp_iternext */
1825
    module_methods,                             /* tp_methods */
1826
    module_members,                             /* tp_members */
1827
    module_getsets,                             /* tp_getset */
1828
    0,                                          /* tp_base */
1829
    0,                                          /* tp_dict */
1830
    0,                                          /* tp_descr_get */
1831
    0,                                          /* tp_descr_set */
1832
    offsetof(PyModuleObject, md_dict),          /* tp_dictoffset */
1833
    module___init__,                            /* tp_init */
1834
    0,                                          /* tp_alloc */
1835
    new_module,                                 /* tp_new */
1836
    PyObject_GC_Del,                            /* tp_free */
1837
};