Coverage Report

Created: 2026-02-26 06:53

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