Coverage Report

Created: 2026-04-12 06:54

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