Coverage Report

Created: 2026-03-08 06:40

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
336k
    (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
154k
{
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
154k
}
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
2.02k
{
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
2.02k
    assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
137
2.02k
    if (def->m_base.m_index == 0) {
138
1.08k
        Py_SET_REFCNT(def, 1);
139
1.08k
        Py_SET_TYPE(def, &PyModuleDef_Type);
140
1.08k
        def->m_base.m_index = _PyImport_GetNextModuleIndex();
141
1.08k
    }
142
2.02k
    return (PyObject*)def;
143
2.02k
}
144
145
static int
146
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
147
                 PyObject *name, PyObject *doc)
148
9.27k
{
149
9.27k
    assert(md_dict != NULL);
150
9.27k
    if (doc == NULL)
151
1.19k
        doc = Py_None;
152
153
9.27k
    if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
154
0
        return -1;
155
9.27k
    if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
156
0
        return -1;
157
9.27k
    if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
158
0
        return -1;
159
9.27k
    if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
160
0
        return -1;
161
9.27k
    if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
162
0
        return -1;
163
9.27k
    if (PyUnicode_CheckExact(name)) {
164
9.27k
        Py_XSETREF(mod->md_name, Py_NewRef(name));
165
9.27k
    }
166
167
9.27k
    return 0;
168
9.27k
}
169
170
static PyModuleObject *
171
new_module_notrack(PyTypeObject *mt)
172
9.27k
{
173
9.27k
    PyModuleObject *m;
174
9.27k
    m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
175
9.27k
    if (m == NULL)
176
0
        return NULL;
177
9.27k
    m->md_state = NULL;
178
9.27k
    m->md_weaklist = NULL;
179
9.27k
    m->md_name = NULL;
180
9.27k
    m->md_token_is_def = false;
181
#ifdef Py_GIL_DISABLED
182
    m->md_requires_gil = true;
183
#endif
184
9.27k
    m->md_state_size = 0;
185
9.27k
    m->md_state_traverse = NULL;
186
9.27k
    m->md_state_clear = NULL;
187
9.27k
    m->md_state_free = NULL;
188
9.27k
    m->md_exec = NULL;
189
9.27k
    m->md_token = NULL;
190
9.27k
    m->md_dict = PyDict_New();
191
9.27k
    if (m->md_dict == NULL) {
192
0
        Py_DECREF(m);
193
0
        return NULL;
194
0
    }
195
9.27k
    return m;
196
9.27k
}
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
356k
{
206
356k
    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
356k
    if (event == PyDict_EVENT_MODIFIED &&
210
117k
        new_value != NULL &&
211
117k
        PyLazyImport_CheckExact(new_value)) {
212
0
        _PyDict_ClearKeysVersionLockHeld(dict);
213
0
    }
214
356k
    return 0;
215
356k
}
216
217
int
218
_PyModule_InitModuleDictWatcher(PyInterpreterState *interp)
219
34
{
220
    // This is a reserved watcher for CPython so there's no need to check for non-NULL.
221
34
    assert(interp->dict_state.watchers[MODULE_WATCHER_ID] == NULL);
222
34
    interp->dict_state.watchers[MODULE_WATCHER_ID] = &module_dict_watcher;
223
34
    return 0;
224
34
}
225
226
static void
227
track_module(PyModuleObject *m)
228
9.27k
{
229
9.27k
    _PyDict_EnablePerThreadRefcounting(m->md_dict);
230
9.27k
    _PyObject_SetDeferredRefcount((PyObject *)m);
231
9.27k
    PyDict_Watch(MODULE_WATCHER_ID, m->md_dict);
232
9.27k
    PyObject_GC_Track(m);
233
9.27k
}
234
235
static PyObject *
236
new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
237
8.08k
{
238
8.08k
    PyModuleObject *m = new_module_notrack(mt);
239
8.08k
    if (m != NULL) {
240
8.08k
        track_module(m);
241
8.08k
    }
242
8.08k
    return (PyObject *)m;
243
8.08k
}
244
245
PyObject *
246
PyModule_NewObject(PyObject *name)
247
1.19k
{
248
1.19k
    PyModuleObject *m = new_module_notrack(&PyModule_Type);
249
1.19k
    if (m == NULL)
250
0
        return NULL;
251
1.19k
    if (module_init_dict(m, m->md_dict, name, NULL) != 0)
252
0
        goto fail;
253
1.19k
    track_module(m);
254
1.19k
    return (PyObject *)m;
255
256
0
 fail:
257
0
    Py_DECREF(m);
258
0
    return NULL;
259
1.19k
}
260
261
PyObject *
262
PyModule_New(const char *name)
263
178
{
264
178
    PyObject *nameobj, *module;
265
178
    nameobj = PyUnicode_FromString(name);
266
178
    if (nameobj == NULL)
267
0
        return NULL;
268
178
    module = PyModule_NewObject(nameobj);
269
178
    Py_DECREF(nameobj);
270
178
    return module;
271
178
}
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
1.08k
{
280
1.08k
    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
1.08k
    return 1;
291
1.08k
}
292
293
static int
294
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
295
1.01k
{
296
1.01k
    PyObject *func;
297
1.01k
    PyMethodDef *fdef;
298
299
21.2k
    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
300
20.2k
        if ((fdef->ml_flags & METH_CLASS) ||
301
20.2k
            (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
20.2k
        func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
308
20.2k
        if (func == NULL) {
309
0
            return -1;
310
0
        }
311
20.2k
        _PyObject_SetDeferredRefcount(func);
312
20.2k
        if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
313
0
            Py_DECREF(func);
314
0
            return -1;
315
0
        }
316
20.2k
        Py_DECREF(func);
317
20.2k
    }
318
319
1.01k
    return 0;
320
1.01k
}
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
1.08k
{
338
1.08k
    md->md_state_size = def_like->m_size;
339
1.08k
    md->md_state_traverse = def_like->m_traverse;
340
1.08k
    md->md_state_clear = def_like->m_clear;
341
1.08k
    md->md_state_free = def_like->m_free;
342
1.08k
}
343
344
PyObject *
345
_PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
346
136
{
347
136
    const char* name;
348
136
    PyModuleObject *m;
349
350
136
    if (!PyModuleDef_Init(module))
351
0
        return NULL;
352
136
    name = module->m_name;
353
136
    if (!check_api_version(name, module_api_version)) {
354
0
        return NULL;
355
0
    }
356
136
    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
136
    name = _PyImport_ResolveNameWithPackageContext(name);
363
364
136
    m = (PyModuleObject*)PyModule_New(name);
365
136
    if (m == NULL)
366
0
        return NULL;
367
368
136
    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
136
    if (module->m_methods != NULL) {
379
136
        if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
380
0
            Py_DECREF(m);
381
0
            return NULL;
382
0
        }
383
136
    }
384
136
    if (module->m_doc != NULL) {
385
102
        if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
386
0
            Py_DECREF(m);
387
0
            return NULL;
388
0
        }
389
102
    }
390
136
    m->md_token = module;
391
136
    m->md_token_is_def = true;
392
136
    module_copy_members_from_deflike(m, module);
393
#ifdef Py_GIL_DISABLED
394
    m->md_requires_gil = true;
395
#endif
396
136
    return (PyObject*)m;
397
136
}
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
944
{
406
944
    PyModuleDef_Slot* cur_slot;
407
944
    PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
408
944
    PyObject *nameobj;
409
944
    PyObject *m = NULL;
410
944
    int has_multiple_interpreters_slot = 0;
411
944
    void *multiple_interpreters = (void *)0;
412
944
    int has_gil_slot = 0;
413
944
    bool requires_gil = true;
414
944
    int has_execution_slots = 0;
415
944
    const char *name;
416
944
    int ret;
417
944
    void *token = NULL;
418
944
    _Py_modexecfunc m_exec = NULL;
419
944
    PyInterpreterState *interp = _PyInterpreterState_GET();
420
421
944
    nameobj = PyObject_GetAttrString(spec, "name");
422
944
    if (nameobj == NULL) {
423
0
        return NULL;
424
0
    }
425
944
    name = PyUnicode_AsUTF8(nameobj);
426
944
    if (name == NULL) {
427
0
        goto error;
428
0
    }
429
430
944
    if (!check_api_version(name, module_api_version)) {
431
0
        goto error;
432
0
    }
433
434
944
    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
944
    bool seen_m_name_slot = false;
443
944
    bool seen_m_doc_slot = false;
444
944
    bool seen_m_size_slot = false;
445
944
    bool seen_m_methods_slot = false;
446
944
    bool seen_m_traverse_slot = false;
447
944
    bool seen_m_clear_slot = false;
448
944
    bool seen_m_free_slot = false;
449
3.83k
    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.89k
#define COPY_NONNULL_SLOT(SLOTNAME, TYPE, DEST)                         \
453
2.89k
        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.89k
#define COPY_DEF_SLOT(SLOTNAME, TYPE, MEMBER)                           \
467
2.89k
        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.89k
#define COPY_NONDEF_SLOT(SLOTNAME, TYPE, DEST)                          \
496
2.89k
        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.89k
#define DEF_SLOT_CASE(SLOT, TYPE, MEMBER)                               \
510
2.89k
        case SLOT:                                                      \
511
0
            COPY_DEF_SLOT(#SLOT, TYPE, MEMBER);                         \
512
0
            break;                                                      \
513
        /////////////////////////////////////////////////////////////////
514
2.89k
        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
989
            case Py_mod_exec:
526
989
                has_execution_slots = 1;
527
989
                if (!original_def) {
528
0
                    COPY_NONDEF_SLOT("Py_mod_exec", _Py_modexecfunc, m_exec);
529
0
                }
530
989
                break;
531
989
            case Py_mod_multiple_interpreters:
532
944
                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
944
                multiple_interpreters = cur_slot->value;
541
944
                has_multiple_interpreters_slot = 1;
542
944
                break;
543
944
            case Py_mod_gil:
544
944
                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
944
                requires_gil = (cur_slot->value != Py_MOD_GIL_NOT_USED);
552
944
                has_gil_slot = 1;
553
944
                break;
554
14
            case Py_mod_abi:
555
14
                if (PyABIInfo_Check((PyABIInfo *)cur_slot->value, name) < 0) {
556
0
                    goto error;
557
0
                }
558
14
                break;
559
14
            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.89k
        }
585
2.89k
#undef DEF_SLOT_CASE
586
2.89k
#undef COPY_DEF_SLOT
587
2.89k
#undef COPY_NONDEF_SLOT
588
2.89k
#undef COPY_NONNULL_SLOT
589
2.89k
    }
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
944
    if (!has_multiple_interpreters_slot) {
610
0
        multiple_interpreters = Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
611
0
    }
612
944
    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
944
    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
944
    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
944
    } else {
647
944
        m = PyModule_NewObject(nameobj);
648
944
        if (m == NULL) {
649
0
            goto error;
650
0
        }
651
944
    }
652
653
944
    if (PyModule_Check(m)) {
654
944
        PyModuleObject *mod = (PyModuleObject*)m;
655
944
        mod->md_state = NULL;
656
944
        module_copy_members_from_deflike(mod, def_like);
657
944
        if (original_def) {
658
944
            assert (!token || token == original_def);
659
944
            mod->md_token = original_def;
660
944
            mod->md_token_is_def = 1;
661
944
        }
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
944
        (void)requires_gil;
669
944
#endif
670
944
        mod->md_exec = m_exec;
671
944
    } 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
944
    if (def_like->m_methods != NULL) {
700
878
        ret = _add_methods_to_object(m, nameobj, def_like->m_methods);
701
878
        if (ret != 0) {
702
0
            goto error;
703
0
        }
704
878
    }
705
706
944
    if (def_like->m_doc != NULL) {
707
820
        ret = PyModule_SetDocString(m, def_like->m_doc);
708
820
        if (ret != 0) {
709
0
            goto error;
710
0
        }
711
820
    }
712
713
944
    Py_DECREF(nameobj);
714
944
    return m;
715
716
0
error:
717
0
    Py_DECREF(nameobj);
718
0
    Py_XDECREF(m);
719
0
    return NULL;
720
944
}
721
722
PyObject *
723
PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
724
944
{
725
944
    PyModuleDef_Init(def);
726
944
    return module_from_def_and_spec(def, spec, module_api_version, def);
727
944
}
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
989
{
762
989
    int ret = exec(module);
763
989
    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
989
    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
989
    return 0;
780
989
}
781
782
static int
783
alloc_state(PyObject *module)
784
1.88k
{
785
1.88k
    if (!PyModule_Check(module)) {
786
0
        PyErr_Format(PyExc_TypeError, "expected module, got %T", module);
787
0
        return -1;
788
0
    }
789
1.88k
    PyModuleObject *md = (PyModuleObject*)module;
790
791
1.88k
    if (md->md_state_size >= 0) {
792
1.88k
        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
944
            md->md_state = PyMem_Malloc(md->md_state_size);
796
944
            if (!md->md_state) {
797
0
                PyErr_NoMemory();
798
0
                return -1;
799
0
            }
800
944
            memset(md->md_state, 0, md->md_state_size);
801
944
        }
802
1.88k
    }
803
1.88k
    return 0;
804
1.88k
}
805
806
int
807
PyModule_Exec(PyObject *module)
808
944
{
809
944
    if (alloc_state(module) < 0) {
810
0
        return -1;
811
0
    }
812
944
    PyModuleObject *md = (PyModuleObject*)module;
813
944
    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
944
    PyModuleDef *def = _PyModule_GetDefOrNull(module);
819
944
    if (def) {
820
944
        return PyModule_ExecDef(module, def);
821
944
    }
822
0
    return 0;
823
944
}
824
825
int
826
PyModule_ExecDef(PyObject *module, PyModuleDef *def)
827
944
{
828
944
    PyModuleDef_Slot *cur_slot;
829
830
944
    if (alloc_state(module) < 0) {
831
0
        return -1;
832
0
    }
833
834
944
    assert(PyModule_Check(module));
835
836
944
    if (def->m_slots == NULL) {
837
0
        return 0;
838
0
    }
839
840
3.83k
    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
841
2.89k
        if (cur_slot->slot == Py_mod_exec) {
842
989
            int (*func)(PyObject *) = cur_slot->value;
843
989
            if (run_exec_func(module, func) < 0) {
844
0
                return -1;
845
0
            }
846
989
            continue;
847
989
        }
848
2.89k
    }
849
944
    return 0;
850
944
}
851
852
int
853
PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
854
136
{
855
136
    int res;
856
136
    PyObject *name = PyModule_GetNameObject(m);
857
136
    if (name == NULL) {
858
0
        return -1;
859
0
    }
860
861
136
    res = _add_methods_to_object(m, name, functions);
862
136
    Py_DECREF(name);
863
136
    return res;
864
136
}
865
866
int
867
PyModule_SetDocString(PyObject *m, const char *doc)
868
922
{
869
922
    PyObject *v;
870
871
922
    v = PyUnicode_FromString(doc);
872
922
    if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
873
0
        Py_XDECREF(v);
874
0
        return -1;
875
0
    }
876
922
    Py_DECREF(v);
877
922
    return 0;
878
922
}
879
880
PyObject *
881
PyModule_GetDict(PyObject *m)
882
21.8k
{
883
21.8k
    if (!PyModule_Check(m)) {
884
0
        PyErr_BadInternalCall();
885
0
        return NULL;
886
0
    }
887
21.8k
    return _PyModule_GetDict(m);  // borrowed reference
888
21.8k
}
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
136
{
918
136
    if (!PyModule_Check(mod)) {
919
0
        PyErr_BadArgument();
920
0
        return NULL;
921
0
    }
922
136
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
923
136
    if (dict == NULL || !PyDict_Check(dict)) {
924
0
        goto error;
925
0
    }
926
136
    PyObject *name;
927
136
    if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
928
        // error or not found
929
0
        goto error;
930
0
    }
931
136
    if (!PyUnicode_Check(name)) {
932
0
        Py_DECREF(name);
933
0
        goto error;
934
0
    }
935
136
    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
136
}
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
62
{
959
    // We return None to indicate "not found" or "bogus".
960
62
    if (!PyModule_Check(mod)) {
961
0
        PyErr_BadArgument();
962
0
        return NULL;
963
0
    }
964
62
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
965
62
    if (dict == NULL) {
966
        // The module has been tampered with.
967
0
        Py_RETURN_NONE;
968
0
    }
969
62
    PyObject *fileobj;
970
62
    int res = PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj);
971
62
    if (res < 0) {
972
0
        return NULL;
973
0
    }
974
62
    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
27
        Py_RETURN_NONE;
982
27
    }
983
35
    if (!PyUnicode_Check(fileobj)) {
984
0
        Py_DECREF(fileobj);
985
0
        Py_RETURN_NONE;
986
0
    }
987
35
    return fileobj;
988
35
}
989
990
PyObject*
991
PyModule_GetFilenameObject(PyObject *mod)
992
62
{
993
62
    PyObject *fileobj = _PyModule_GetFilenameObject(mod);
994
62
    if (fileobj == NULL) {
995
0
        return NULL;
996
0
    }
997
62
    if (fileobj == Py_None) {
998
27
        PyErr_SetString(PyExc_SystemError, "module filename missing");
999
27
        return NULL;
1000
27
    }
1001
35
    return fileobj;
1002
62
}
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
6
{
1051
6
    if (!PyModule_Check(m)) {
1052
0
        PyErr_BadArgument();
1053
0
        return NULL;
1054
0
    }
1055
6
    return _PyModule_GetDefOrNull(m);
1056
6
}
1057
1058
void*
1059
PyModule_GetState(PyObject* m)
1060
24.3M
{
1061
24.3M
    if (!PyModule_Check(m)) {
1062
0
        PyErr_BadArgument();
1063
0
        return NULL;
1064
0
    }
1065
24.3M
    return _PyModule_GetState(m);
1066
24.3M
}
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
8.08k
{
1163
8.08k
    return module_init_dict(self, self->md_dict, name, doc);
1164
8.08k
}
1165
1166
static void
1167
module_dealloc(PyObject *self)
1168
5.33k
{
1169
5.33k
    PyModuleObject *m = _PyModule_CAST(self);
1170
1171
5.33k
    PyObject_GC_UnTrack(m);
1172
1173
5.33k
    int verbose = _Py_GetConfig()->verbose;
1174
5.33k
    if (verbose && m->md_name) {
1175
0
        PySys_FormatStderr("# destroy %U\n", m->md_name);
1176
0
    }
1177
5.33k
    FT_CLEAR_WEAKREFS(self, m->md_weaklist);
1178
1179
5.33k
    assert_def_missing_or_redundant(m);
1180
    /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
1181
5.33k
    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
5.33k
    Py_XDECREF(m->md_dict);
1187
5.33k
    Py_XDECREF(m->md_name);
1188
5.33k
    if (m->md_state != NULL) {
1189
0
        PyMem_Free(m->md_state);
1190
0
    }
1191
5.33k
    Py_TYPE(m)->tp_free((PyObject *)m);
1192
5.33k
}
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
4.59M
{
1207
4.59M
    if (spec == NULL) {
1208
0
        return 0;
1209
0
    }
1210
4.59M
    PyObject *value;
1211
4.59M
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_initializing), &value);
1212
4.59M
    if (rc > 0) {
1213
4.39M
        rc = PyObject_IsTrue(value);
1214
4.39M
        Py_DECREF(value);
1215
4.39M
    }
1216
4.59M
    return rc;
1217
4.59M
}
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.00k
{
1225
6.00k
    if (spec == NULL) {
1226
0
         return 0;
1227
0
    }
1228
1229
6.00k
    PyObject *value;
1230
6.00k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_uninitialized_submodules), &value);
1231
6.00k
    if (rc > 0) {
1232
5.73k
        rc = PySequence_Contains(value, name);
1233
5.73k
        Py_DECREF(value);
1234
5.73k
    }
1235
6.00k
    return rc;
1236
6.00k
}
1237
1238
int
1239
_PyModuleSpec_GetFileOrigin(PyObject *spec, PyObject **p_origin)
1240
6.06k
{
1241
6.06k
    PyObject *has_location = NULL;
1242
6.06k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(has_location), &has_location);
1243
6.06k
    if (rc <= 0) {
1244
272
        return rc;
1245
272
    }
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.79k
    rc = PyObject_IsTrue(has_location);
1250
5.79k
    Py_DECREF(has_location);
1251
5.79k
    if (rc <= 0) {
1252
136
        return rc;
1253
136
    }
1254
    // has_location is true, so origin is a location
1255
5.65k
    PyObject *origin = NULL;
1256
5.65k
    rc = PyObject_GetOptionalAttr(spec, &_Py_ID(origin), &origin);
1257
5.65k
    if (rc <= 0) {
1258
0
        return rc;
1259
0
    }
1260
5.65k
    assert(origin != NULL);
1261
5.65k
    if (!PyUnicode_Check(origin)) {
1262
0
        Py_DECREF(origin);
1263
0
        return 0;
1264
0
    }
1265
5.65k
    *p_origin = origin;
1266
5.65k
    return 1;
1267
5.65k
}
1268
1269
int
1270
_PyModule_IsPossiblyShadowing(PyObject *origin)
1271
6.06k
{
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.06k
    if (origin == NULL) {
1280
408
        return 0;
1281
408
    }
1282
1283
    // not sys.flags.safe_path
1284
5.65k
    const PyConfig *config = _Py_GetConfig();
1285
5.65k
    if (config->safe_path) {
1286
0
        return 0;
1287
0
    }
1288
1289
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
1290
5.65k
    wchar_t root[MAXPATHLEN + 1];
1291
5.65k
    Py_ssize_t size = PyUnicode_AsWideChar(origin, root, MAXPATHLEN);
1292
5.65k
    if (size < 0) {
1293
0
        return -1;
1294
0
    }
1295
5.65k
    assert(size <= MAXPATHLEN);
1296
5.65k
    root[size] = L'\0';
1297
1298
5.65k
    wchar_t *sep = wcsrchr(root, SEP);
1299
5.65k
    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.65k
    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.65k
    *sep = L'\0';
1311
1312
    // sys.path[0] or os.getcwd()
1313
5.65k
    wchar_t *sys_path_0 = config->sys_path_0;
1314
5.65k
    if (!sys_path_0) {
1315
5.65k
        return 0;
1316
5.65k
    }
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
8.66M
{
1336
    // When suppress=1, this function suppresses AttributeError.
1337
8.66M
    PyObject *attr, *mod_name, *getattr;
1338
8.66M
    attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
1339
8.66M
    if (attr) {
1340
7.17M
        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
7.17M
        return attr;
1363
7.17M
    }
1364
1.49M
    if (suppress == 1) {
1365
1.48M
        if (PyErr_Occurred()) {
1366
            // pass up non-AttributeError exception
1367
0
            return NULL;
1368
0
        }
1369
1.48M
    }
1370
6.00k
    else {
1371
6.00k
        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1372
            // pass up non-AttributeError exception
1373
0
            return NULL;
1374
0
        }
1375
6.00k
        PyErr_Clear();
1376
6.00k
    }
1377
1.49M
    assert(m->md_dict != NULL);
1378
1.49M
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__getattr__), &getattr) < 0) {
1379
0
        return NULL;
1380
0
    }
1381
1.49M
    if (getattr) {
1382
812
        PyObject *result = PyObject_CallOneArg(getattr, name);
1383
812
        if (result == NULL && suppress == 1 && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1384
            // suppress AttributeError
1385
808
            PyErr_Clear();
1386
808
        }
1387
812
        Py_DECREF(getattr);
1388
812
        return result;
1389
812
    }
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
1.49M
    if (suppress == 1) {
1394
1.48M
        return NULL;
1395
1.48M
    }
1396
6.00k
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__name__), &mod_name) < 0) {
1397
0
        return NULL;
1398
0
    }
1399
6.00k
    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.00k
    PyObject *spec;
1406
6.00k
    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.00k
    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.00k
    PyObject *origin = NULL;
1419
6.00k
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
1420
0
        goto done;
1421
0
    }
1422
1423
6.00k
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
1424
6.00k
    if (is_possibly_shadowing < 0) {
1425
0
        goto done;
1426
0
    }
1427
6.00k
    int is_possibly_shadowing_stdlib = 0;
1428
6.00k
    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.00k
    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.00k
    else {
1453
6.00k
        int rc = _PyModuleSpec_IsInitializing(spec);
1454
6.00k
        if (rc < 0) {
1455
0
            goto done;
1456
0
        }
1457
6.00k
        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.00k
        else {
1484
6.00k
            assert(rc == 0);
1485
6.00k
            rc = _PyModuleSpec_IsUninitializedSubmodule(spec, name);
1486
6.00k
            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.00k
            else if (rc == 0) {
1493
6.00k
                PyErr_Format(PyExc_AttributeError,
1494
6.00k
                            "module '%U' has no attribute '%U'",
1495
6.00k
                            mod_name, name);
1496
6.00k
            }
1497
6.00k
        }
1498
6.00k
    }
1499
1500
6.00k
done:
1501
6.00k
    Py_XDECREF(origin);
1502
6.00k
    Py_DECREF(spec);
1503
6.00k
    Py_DECREF(mod_name);
1504
6.00k
    return NULL;
1505
6.00k
}
1506
1507
1508
PyObject*
1509
_Py_module_getattro(PyObject *self, PyObject *name)
1510
182k
{
1511
182k
    PyModuleObject *m = _PyModule_CAST(self);
1512
182k
    return _Py_module_getattro_impl(m, name, 0);
1513
182k
}
1514
1515
static int
1516
module_traverse(PyObject *self, visitproc visit, void *arg)
1517
148k
{
1518
148k
    PyModuleObject *m = _PyModule_CAST(self);
1519
1520
148k
    assert_def_missing_or_redundant(m);
1521
    /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
1522
148k
    if (m->md_state_traverse && (m->md_state_size <= 0 || m->md_state != NULL))
1523
20.6k
    {
1524
20.6k
        int res = m->md_state_traverse((PyObject*)m, visit, arg);
1525
20.6k
        if (res)
1526
0
            return res;
1527
20.6k
    }
1528
1529
148k
    Py_VISIT(m->md_dict);
1530
148k
    return 0;
1531
148k
}
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
46
{
1559
46
    PyObject *result = NULL;
1560
46
    PyObject *dict;
1561
46
    if (PyModule_CheckExact(self)) {
1562
46
        dict = Py_NewRef(((PyModuleObject *)self)->md_dict);
1563
46
    } else {
1564
0
        dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
1565
0
    }
1566
1567
46
    if (dict != NULL) {
1568
46
        if (PyDict_Check(dict)) {
1569
46
            PyObject *dirfunc = PyDict_GetItemWithError(dict, &_Py_ID(__dir__));
1570
46
            if (dirfunc) {
1571
0
                result = _PyObject_CallNoArgs(dirfunc);
1572
0
            }
1573
46
            else if (!PyErr_Occurred()) {
1574
46
                result = PyDict_Keys(dict);
1575
46
            }
1576
46
        }
1577
0
        else {
1578
0
            PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
1579
0
        }
1580
46
    }
1581
1582
46
    Py_XDECREF(dict);
1583
46
    return result;
1584
46
}
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
};