Coverage Report

Created: 2025-08-26 06:26

/src/cpython/Objects/moduleobject.c
Line
Count
Source (jump to first uncovered line)
1
/* Module object implementation */
2
3
#include "Python.h"
4
#include "pycore_call.h"          // _PyObject_CallNoArgs()
5
#include "pycore_dict.h"          // _PyDict_EnablePerThreadRefcounting()
6
#include "pycore_fileutils.h"     // _Py_wgetcwd
7
#include "pycore_import.h"        // _PyImport_GetNextModuleIndex()
8
#include "pycore_interp.h"        // PyInterpreterState.importlib
9
#include "pycore_long.h"          // _PyLong_GetOne()
10
#include "pycore_modsupport.h"    // _PyModule_CreateInitialized()
11
#include "pycore_moduleobject.h"  // _PyModule_GetDef()
12
#include "pycore_object.h"        // _PyType_AllocNoTrack
13
#include "pycore_pyerrors.h"      // _PyErr_FormatFromCause()
14
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
15
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
16
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
17
18
#include "osdefs.h"               // MAXPATHLEN
19
20
21
#define _PyModule_CAST(op) \
22
590k
    (assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
23
24
25
static PyMemberDef module_members[] = {
26
    {"__dict__", _Py_T_OBJECT, offsetof(PyModuleObject, md_dict), Py_READONLY},
27
    {0}
28
};
29
30
31
PyTypeObject PyModuleDef_Type = {
32
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
33
    "moduledef",                                /* tp_name */
34
    sizeof(PyModuleDef),                        /* tp_basicsize */
35
    0,                                          /* tp_itemsize */
36
};
37
38
39
int
40
_PyModule_IsExtension(PyObject *obj)
41
0
{
42
0
    if (!PyModule_Check(obj)) {
43
0
        return 0;
44
0
    }
45
0
    PyModuleObject *module = (PyModuleObject*)obj;
46
47
0
    PyModuleDef *def = module->md_def;
48
0
    return (def != NULL && def->m_methods != NULL);
49
0
}
50
51
52
PyObject*
53
PyModuleDef_Init(PyModuleDef* def)
54
830
{
55
830
    assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
56
830
    if (def->m_base.m_index == 0) {
57
447
        Py_SET_REFCNT(def, 1);
58
447
        Py_SET_TYPE(def, &PyModuleDef_Type);
59
447
        def->m_base.m_index = _PyImport_GetNextModuleIndex();
60
447
    }
61
830
    return (PyObject*)def;
62
830
}
63
64
static int
65
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
66
                 PyObject *name, PyObject *doc)
67
1.45k
{
68
1.45k
    assert(md_dict != NULL);
69
1.45k
    if (doc == NULL)
70
495
        doc = Py_None;
71
72
1.45k
    if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
73
0
        return -1;
74
1.45k
    if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
75
0
        return -1;
76
1.45k
    if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
77
0
        return -1;
78
1.45k
    if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
79
0
        return -1;
80
1.45k
    if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
81
0
        return -1;
82
1.45k
    if (PyUnicode_CheckExact(name)) {
83
1.45k
        Py_XSETREF(mod->md_name, Py_NewRef(name));
84
1.45k
    }
85
86
1.45k
    return 0;
87
1.45k
}
88
89
static PyModuleObject *
90
new_module_notrack(PyTypeObject *mt)
91
1.45k
{
92
1.45k
    PyModuleObject *m;
93
1.45k
    m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
94
1.45k
    if (m == NULL)
95
0
        return NULL;
96
1.45k
    m->md_def = NULL;
97
1.45k
    m->md_state = NULL;
98
1.45k
    m->md_weaklist = NULL;
99
1.45k
    m->md_name = NULL;
100
1.45k
    m->md_dict = PyDict_New();
101
1.45k
    if (m->md_dict == NULL) {
102
0
        Py_DECREF(m);
103
0
        return NULL;
104
0
    }
105
1.45k
    return m;
106
1.45k
}
107
108
static void
109
track_module(PyModuleObject *m)
110
1.45k
{
111
1.45k
    _PyDict_EnablePerThreadRefcounting(m->md_dict);
112
1.45k
    _PyObject_SetDeferredRefcount((PyObject *)m);
113
1.45k
    PyObject_GC_Track(m);
114
1.45k
}
115
116
static PyObject *
117
new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
118
957
{
119
957
    PyModuleObject *m = new_module_notrack(mt);
120
957
    if (m != NULL) {
121
957
        track_module(m);
122
957
    }
123
957
    return (PyObject *)m;
124
957
}
125
126
PyObject *
127
PyModule_NewObject(PyObject *name)
128
495
{
129
495
    PyModuleObject *m = new_module_notrack(&PyModule_Type);
130
495
    if (m == NULL)
131
0
        return NULL;
132
495
    if (module_init_dict(m, m->md_dict, name, NULL) != 0)
133
0
        goto fail;
134
495
    track_module(m);
135
495
    return (PyObject *)m;
136
137
0
 fail:
138
0
    Py_DECREF(m);
139
0
    return NULL;
140
495
}
141
142
PyObject *
143
PyModule_New(const char *name)
144
80
{
145
80
    PyObject *nameobj, *module;
146
80
    nameobj = PyUnicode_FromString(name);
147
80
    if (nameobj == NULL)
148
0
        return NULL;
149
80
    module = PyModule_NewObject(nameobj);
150
80
    Py_DECREF(nameobj);
151
80
    return module;
152
80
}
153
154
/* Check API/ABI version
155
 * Issues a warning on mismatch, which is usually not fatal.
156
 * Returns 0 if an exception is raised.
157
 */
158
static int
159
check_api_version(const char *name, int module_api_version)
160
447
{
161
447
    if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
162
0
        int err;
163
0
        err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
164
0
            "Python C API version mismatch for module %.100s: "
165
0
            "This Python has API version %d, module %.100s has version %d.",
166
0
             name,
167
0
             PYTHON_API_VERSION, name, module_api_version);
168
0
        if (err)
169
0
            return 0;
170
0
    }
171
447
    return 1;
172
447
}
173
174
static int
175
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
176
423
{
177
423
    PyObject *func;
178
423
    PyMethodDef *fdef;
179
180
9.36k
    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
181
8.94k
        if ((fdef->ml_flags & METH_CLASS) ||
182
8.94k
            (fdef->ml_flags & METH_STATIC)) {
183
0
            PyErr_SetString(PyExc_ValueError,
184
0
                            "module functions cannot set"
185
0
                            " METH_CLASS or METH_STATIC");
186
0
            return -1;
187
0
        }
188
8.94k
        func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
189
8.94k
        if (func == NULL) {
190
0
            return -1;
191
0
        }
192
8.94k
        _PyObject_SetDeferredRefcount(func);
193
8.94k
        if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
194
0
            Py_DECREF(func);
195
0
            return -1;
196
0
        }
197
8.94k
        Py_DECREF(func);
198
8.94k
    }
199
200
423
    return 0;
201
423
}
202
203
PyObject *
204
PyModule_Create2(PyModuleDef* module, int module_api_version)
205
0
{
206
0
    if (!_PyImport_IsInitialized(_PyInterpreterState_GET())) {
207
0
        PyErr_SetString(PyExc_SystemError,
208
0
                        "Python import machinery not initialized");
209
0
        return NULL;
210
0
    }
211
0
    return _PyModule_CreateInitialized(module, module_api_version);
212
0
}
213
214
PyObject *
215
_PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
216
64
{
217
64
    const char* name;
218
64
    PyModuleObject *m;
219
220
64
    if (!PyModuleDef_Init(module))
221
0
        return NULL;
222
64
    name = module->m_name;
223
64
    if (!check_api_version(name, module_api_version)) {
224
0
        return NULL;
225
0
    }
226
64
    if (module->m_slots) {
227
0
        PyErr_Format(
228
0
            PyExc_SystemError,
229
0
            "module %s: PyModule_Create is incompatible with m_slots", name);
230
0
        return NULL;
231
0
    }
232
64
    name = _PyImport_ResolveNameWithPackageContext(name);
233
234
64
    m = (PyModuleObject*)PyModule_New(name);
235
64
    if (m == NULL)
236
0
        return NULL;
237
238
64
    if (module->m_size > 0) {
239
0
        m->md_state = PyMem_Malloc(module->m_size);
240
0
        if (!m->md_state) {
241
0
            PyErr_NoMemory();
242
0
            Py_DECREF(m);
243
0
            return NULL;
244
0
        }
245
0
        memset(m->md_state, 0, module->m_size);
246
0
    }
247
248
64
    if (module->m_methods != NULL) {
249
64
        if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
250
0
            Py_DECREF(m);
251
0
            return NULL;
252
0
        }
253
64
    }
254
64
    if (module->m_doc != NULL) {
255
48
        if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
256
0
            Py_DECREF(m);
257
0
            return NULL;
258
0
        }
259
48
    }
260
64
    m->md_def = module;
261
#ifdef Py_GIL_DISABLED
262
    m->md_gil = Py_MOD_GIL_USED;
263
#endif
264
64
    return (PyObject*)m;
265
64
}
266
267
PyObject *
268
PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
269
383
{
270
383
    PyModuleDef_Slot* cur_slot;
271
383
    PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
272
383
    PyObject *nameobj;
273
383
    PyObject *m = NULL;
274
383
    int has_multiple_interpreters_slot = 0;
275
383
    void *multiple_interpreters = (void *)0;
276
383
    int has_gil_slot = 0;
277
383
    void *gil_slot = Py_MOD_GIL_USED;
278
383
    int has_execution_slots = 0;
279
383
    const char *name;
280
383
    int ret;
281
383
    PyInterpreterState *interp = _PyInterpreterState_GET();
282
283
383
    PyModuleDef_Init(def);
284
285
383
    nameobj = PyObject_GetAttrString(spec, "name");
286
383
    if (nameobj == NULL) {
287
0
        return NULL;
288
0
    }
289
383
    name = PyUnicode_AsUTF8(nameobj);
290
383
    if (name == NULL) {
291
0
        goto error;
292
0
    }
293
294
383
    if (!check_api_version(name, module_api_version)) {
295
0
        goto error;
296
0
    }
297
298
383
    if (def->m_size < 0) {
299
0
        PyErr_Format(
300
0
            PyExc_SystemError,
301
0
            "module %s: m_size may not be negative for multi-phase initialization",
302
0
            name);
303
0
        goto error;
304
0
    }
305
306
1.55k
    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
307
1.16k
        switch (cur_slot->slot) {
308
0
            case Py_mod_create:
309
0
                if (create) {
310
0
                    PyErr_Format(
311
0
                        PyExc_SystemError,
312
0
                        "module %s has multiple create slots",
313
0
                        name);
314
0
                    goto error;
315
0
                }
316
0
                create = cur_slot->value;
317
0
                break;
318
403
            case Py_mod_exec:
319
403
                has_execution_slots = 1;
320
403
                break;
321
383
            case Py_mod_multiple_interpreters:
322
383
                if (has_multiple_interpreters_slot) {
323
0
                    PyErr_Format(
324
0
                        PyExc_SystemError,
325
0
                        "module %s has more than one 'multiple interpreters' slots",
326
0
                        name);
327
0
                    goto error;
328
0
                }
329
383
                multiple_interpreters = cur_slot->value;
330
383
                has_multiple_interpreters_slot = 1;
331
383
                break;
332
383
            case Py_mod_gil:
333
383
                if (has_gil_slot) {
334
0
                    PyErr_Format(
335
0
                       PyExc_SystemError,
336
0
                       "module %s has more than one 'gil' slot",
337
0
                       name);
338
0
                    goto error;
339
0
                }
340
383
                gil_slot = cur_slot->value;
341
383
                has_gil_slot = 1;
342
383
                break;
343
0
            default:
344
0
                assert(cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT);
345
0
                PyErr_Format(
346
0
                    PyExc_SystemError,
347
0
                    "module %s uses unknown slot ID %i",
348
0
                    name, cur_slot->slot);
349
0
                goto error;
350
1.16k
        }
351
1.16k
    }
352
353
    /* By default, multi-phase init modules are expected
354
       to work under multiple interpreters. */
355
383
    if (!has_multiple_interpreters_slot) {
356
0
        multiple_interpreters = Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
357
0
    }
358
383
    if (multiple_interpreters == Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED) {
359
0
        if (!_Py_IsMainInterpreter(interp)
360
0
            && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
361
0
        {
362
0
            goto error;
363
0
        }
364
0
    }
365
383
    else if (multiple_interpreters != Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
366
383
             && interp->ceval.own_gil
367
383
             && !_Py_IsMainInterpreter(interp)
368
383
             && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
369
0
    {
370
0
        goto error;
371
0
    }
372
373
383
    if (create) {
374
0
        m = create(spec, def);
375
0
        if (m == NULL) {
376
0
            if (!PyErr_Occurred()) {
377
0
                PyErr_Format(
378
0
                    PyExc_SystemError,
379
0
                    "creation of module %s failed without setting an exception",
380
0
                    name);
381
0
            }
382
0
            goto error;
383
0
        } else {
384
0
            if (PyErr_Occurred()) {
385
0
                _PyErr_FormatFromCause(
386
0
                    PyExc_SystemError,
387
0
                    "creation of module %s raised unreported exception",
388
0
                    name);
389
0
                goto error;
390
0
            }
391
0
        }
392
383
    } else {
393
383
        m = PyModule_NewObject(nameobj);
394
383
        if (m == NULL) {
395
0
            goto error;
396
0
        }
397
383
    }
398
399
383
    if (PyModule_Check(m)) {
400
383
        ((PyModuleObject*)m)->md_state = NULL;
401
383
        ((PyModuleObject*)m)->md_def = def;
402
#ifdef Py_GIL_DISABLED
403
        ((PyModuleObject*)m)->md_gil = gil_slot;
404
#else
405
383
        (void)gil_slot;
406
383
#endif
407
383
    } else {
408
0
        if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
409
0
            PyErr_Format(
410
0
                PyExc_SystemError,
411
0
                "module %s is not a module object, but requests module state",
412
0
                name);
413
0
            goto error;
414
0
        }
415
0
        if (has_execution_slots) {
416
0
            PyErr_Format(
417
0
                PyExc_SystemError,
418
0
                "module %s specifies execution slots, but did not create "
419
0
                    "a ModuleType instance",
420
0
                name);
421
0
            goto error;
422
0
        }
423
0
    }
424
425
383
    if (def->m_methods != NULL) {
426
359
        ret = _add_methods_to_object(m, nameobj, def->m_methods);
427
359
        if (ret != 0) {
428
0
            goto error;
429
0
        }
430
359
    }
431
432
383
    if (def->m_doc != NULL) {
433
327
        ret = PyModule_SetDocString(m, def->m_doc);
434
327
        if (ret != 0) {
435
0
            goto error;
436
0
        }
437
327
    }
438
439
383
    Py_DECREF(nameobj);
440
383
    return m;
441
442
0
error:
443
0
    Py_DECREF(nameobj);
444
0
    Py_XDECREF(m);
445
0
    return NULL;
446
383
}
447
448
#ifdef Py_GIL_DISABLED
449
int
450
PyUnstable_Module_SetGIL(PyObject *module, void *gil)
451
{
452
    if (!PyModule_Check(module)) {
453
        PyErr_BadInternalCall();
454
        return -1;
455
    }
456
    ((PyModuleObject *)module)->md_gil = gil;
457
    return 0;
458
}
459
#endif
460
461
int
462
PyModule_ExecDef(PyObject *module, PyModuleDef *def)
463
383
{
464
383
    PyModuleDef_Slot *cur_slot;
465
383
    const char *name;
466
383
    int ret;
467
468
383
    name = PyModule_GetName(module);
469
383
    if (name == NULL) {
470
0
        return -1;
471
0
    }
472
473
383
    if (def->m_size >= 0) {
474
383
        PyModuleObject *md = (PyModuleObject*)module;
475
383
        if (md->md_state == NULL) {
476
            /* Always set a state pointer; this serves as a marker to skip
477
             * multiple initialization (importlib.reload() is no-op) */
478
383
            md->md_state = PyMem_Malloc(def->m_size);
479
383
            if (!md->md_state) {
480
0
                PyErr_NoMemory();
481
0
                return -1;
482
0
            }
483
383
            memset(md->md_state, 0, def->m_size);
484
383
        }
485
383
    }
486
487
383
    if (def->m_slots == NULL) {
488
0
        return 0;
489
0
    }
490
491
1.55k
    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
492
1.16k
        switch (cur_slot->slot) {
493
0
            case Py_mod_create:
494
                /* handled in PyModule_FromDefAndSpec2 */
495
0
                break;
496
403
            case Py_mod_exec:
497
403
                ret = ((int (*)(PyObject *))cur_slot->value)(module);
498
403
                if (ret != 0) {
499
0
                    if (!PyErr_Occurred()) {
500
0
                        PyErr_Format(
501
0
                            PyExc_SystemError,
502
0
                            "execution of module %s failed without setting an exception",
503
0
                            name);
504
0
                    }
505
0
                    return -1;
506
0
                }
507
403
                if (PyErr_Occurred()) {
508
0
                    _PyErr_FormatFromCause(
509
0
                        PyExc_SystemError,
510
0
                        "execution of module %s raised unreported exception",
511
0
                        name);
512
0
                    return -1;
513
0
                }
514
403
                break;
515
403
            case Py_mod_multiple_interpreters:
516
766
            case Py_mod_gil:
517
                /* handled in PyModule_FromDefAndSpec2 */
518
766
                break;
519
0
            default:
520
0
                PyErr_Format(
521
0
                    PyExc_SystemError,
522
0
                    "module %s initialized with unknown slot %i",
523
0
                    name, cur_slot->slot);
524
0
                return -1;
525
1.16k
        }
526
1.16k
    }
527
383
    return 0;
528
383
}
529
530
int
531
PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
532
64
{
533
64
    int res;
534
64
    PyObject *name = PyModule_GetNameObject(m);
535
64
    if (name == NULL) {
536
0
        return -1;
537
0
    }
538
539
64
    res = _add_methods_to_object(m, name, functions);
540
64
    Py_DECREF(name);
541
64
    return res;
542
64
}
543
544
int
545
PyModule_SetDocString(PyObject *m, const char *doc)
546
375
{
547
375
    PyObject *v;
548
549
375
    v = PyUnicode_FromString(doc);
550
375
    if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
551
0
        Py_XDECREF(v);
552
0
        return -1;
553
0
    }
554
375
    Py_DECREF(v);
555
375
    return 0;
556
375
}
557
558
PyObject *
559
PyModule_GetDict(PyObject *m)
560
9.14k
{
561
9.14k
    if (!PyModule_Check(m)) {
562
0
        PyErr_BadInternalCall();
563
0
        return NULL;
564
0
    }
565
9.14k
    return _PyModule_GetDict(m);  // borrowed reference
566
9.14k
}
567
568
PyObject*
569
PyModule_GetNameObject(PyObject *mod)
570
447
{
571
447
    if (!PyModule_Check(mod)) {
572
0
        PyErr_BadArgument();
573
0
        return NULL;
574
0
    }
575
447
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
576
447
    if (dict == NULL || !PyDict_Check(dict)) {
577
0
        goto error;
578
0
    }
579
447
    PyObject *name;
580
447
    if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
581
        // error or not found
582
0
        goto error;
583
0
    }
584
447
    if (!PyUnicode_Check(name)) {
585
0
        Py_DECREF(name);
586
0
        goto error;
587
0
    }
588
447
    return name;
589
590
0
error:
591
0
    if (!PyErr_Occurred()) {
592
0
        PyErr_SetString(PyExc_SystemError, "nameless module");
593
0
    }
594
0
    return NULL;
595
447
}
596
597
const char *
598
PyModule_GetName(PyObject *m)
599
383
{
600
383
    PyObject *name = PyModule_GetNameObject(m);
601
383
    if (name == NULL) {
602
0
        return NULL;
603
0
    }
604
383
    assert(Py_REFCNT(name) >= 2);
605
383
    Py_DECREF(name);   /* module dict has still a reference */
606
383
    return PyUnicode_AsUTF8(name);
607
383
}
608
609
PyObject*
610
_PyModule_GetFilenameObject(PyObject *mod)
611
16
{
612
    // We return None to indicate "not found" or "bogus".
613
16
    if (!PyModule_Check(mod)) {
614
0
        PyErr_BadArgument();
615
0
        return NULL;
616
0
    }
617
16
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
618
16
    if (dict == NULL) {
619
        // The module has been tampered with.
620
0
        Py_RETURN_NONE;
621
0
    }
622
16
    PyObject *fileobj;
623
16
    int res = PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj);
624
16
    if (res < 0) {
625
0
        return NULL;
626
0
    }
627
16
    if (res == 0) {
628
        // __file__ isn't set.  There are several reasons why this might
629
        // be so, most of them valid reasons.  If it's the __main__
630
        // module then we're running the REPL or with -c.  Otherwise
631
        // it's a namespace package or other module with a loader that
632
        // isn't disk-based.  It could also be that a user created
633
        // a module manually but without manually setting __file__.
634
12
        Py_RETURN_NONE;
635
12
    }
636
4
    if (!PyUnicode_Check(fileobj)) {
637
0
        Py_DECREF(fileobj);
638
0
        Py_RETURN_NONE;
639
0
    }
640
4
    return fileobj;
641
4
}
642
643
PyObject*
644
PyModule_GetFilenameObject(PyObject *mod)
645
16
{
646
16
    PyObject *fileobj = _PyModule_GetFilenameObject(mod);
647
16
    if (fileobj == NULL) {
648
0
        return NULL;
649
0
    }
650
16
    if (fileobj == Py_None) {
651
12
        PyErr_SetString(PyExc_SystemError, "module filename missing");
652
12
        return NULL;
653
12
    }
654
4
    return fileobj;
655
16
}
656
657
const char *
658
PyModule_GetFilename(PyObject *m)
659
0
{
660
0
    PyObject *fileobj;
661
0
    const char *utf8;
662
0
    fileobj = PyModule_GetFilenameObject(m);
663
0
    if (fileobj == NULL)
664
0
        return NULL;
665
0
    utf8 = PyUnicode_AsUTF8(fileobj);
666
0
    Py_DECREF(fileobj);   /* module dict has still a reference */
667
0
    return utf8;
668
0
}
669
670
Py_ssize_t
671
_PyModule_GetFilenameUTF8(PyObject *mod, char *buffer, Py_ssize_t maxlen)
672
0
{
673
    // We "return" an empty string for an invalid module
674
    // and for a missing, empty, or invalid filename.
675
0
    assert(maxlen >= 0);
676
0
    Py_ssize_t size = -1;
677
0
    PyObject *filenameobj = _PyModule_GetFilenameObject(mod);
678
0
    if (filenameobj == NULL) {
679
0
        return -1;
680
0
    }
681
0
    if (filenameobj == Py_None) {
682
        // It is missing or invalid.
683
0
        buffer[0] = '\0';
684
0
        size = 0;
685
0
    }
686
0
    else {
687
0
        const char *filename = PyUnicode_AsUTF8AndSize(filenameobj, &size);
688
0
        assert(size >= 0);
689
0
        if (size > maxlen) {
690
0
            size = -1;
691
0
            PyErr_SetString(PyExc_ValueError, "__file__ too long");
692
0
        }
693
0
        else {
694
0
            (void)strcpy(buffer, filename);
695
0
        }
696
0
    }
697
0
    Py_DECREF(filenameobj);
698
0
    return size;
699
0
}
700
701
PyModuleDef*
702
PyModule_GetDef(PyObject* m)
703
417
{
704
417
    if (!PyModule_Check(m)) {
705
0
        PyErr_BadArgument();
706
0
        return NULL;
707
0
    }
708
417
    return _PyModule_GetDef(m);
709
417
}
710
711
void*
712
PyModule_GetState(PyObject* m)
713
22.1M
{
714
22.1M
    if (!PyModule_Check(m)) {
715
0
        PyErr_BadArgument();
716
0
        return NULL;
717
0
    }
718
22.1M
    return _PyModule_GetState(m);
719
22.1M
}
720
721
void
722
_PyModule_Clear(PyObject *m)
723
0
{
724
0
    PyObject *d = ((PyModuleObject *)m)->md_dict;
725
0
    if (d != NULL)
726
0
        _PyModule_ClearDict(d);
727
0
}
728
729
void
730
_PyModule_ClearDict(PyObject *d)
731
0
{
732
    /* To make the execution order of destructors for global
733
       objects a bit more predictable, we first zap all objects
734
       whose name starts with a single underscore, before we clear
735
       the entire dictionary.  We zap them by replacing them with
736
       None, rather than deleting them from the dictionary, to
737
       avoid rehashing the dictionary (to some extent). */
738
739
0
    Py_ssize_t pos;
740
0
    PyObject *key, *value;
741
742
0
    int verbose = _Py_GetConfig()->verbose;
743
744
    /* First, clear only names starting with a single underscore */
745
0
    pos = 0;
746
0
    while (PyDict_Next(d, &pos, &key, &value)) {
747
0
        if (value != Py_None && PyUnicode_Check(key)) {
748
0
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
749
0
                PyUnicode_READ_CHAR(key, 1) != '_') {
750
0
                if (verbose > 1) {
751
0
                    const char *s = PyUnicode_AsUTF8(key);
752
0
                    if (s != NULL)
753
0
                        PySys_WriteStderr("#   clear[1] %s\n", s);
754
0
                    else
755
0
                        PyErr_Clear();
756
0
                }
757
0
                if (PyDict_SetItem(d, key, Py_None) != 0) {
758
0
                    PyErr_FormatUnraisable("Exception ignored while "
759
0
                                           "clearing module dict");
760
0
                }
761
0
            }
762
0
        }
763
0
    }
764
765
    /* Next, clear all names except for __builtins__ */
766
0
    pos = 0;
767
0
    while (PyDict_Next(d, &pos, &key, &value)) {
768
0
        if (value != Py_None && PyUnicode_Check(key)) {
769
0
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
770
0
                !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
771
0
            {
772
0
                if (verbose > 1) {
773
0
                    const char *s = PyUnicode_AsUTF8(key);
774
0
                    if (s != NULL)
775
0
                        PySys_WriteStderr("#   clear[2] %s\n", s);
776
0
                    else
777
0
                        PyErr_Clear();
778
0
                }
779
0
                if (PyDict_SetItem(d, key, Py_None) != 0) {
780
0
                    PyErr_FormatUnraisable("Exception ignored while "
781
0
                                           "clearing module dict");
782
0
                }
783
0
            }
784
0
        }
785
0
    }
786
787
    /* Note: we leave __builtins__ in place, so that destructors
788
       of non-global objects defined in this module can still use
789
       builtins, in particularly 'None'. */
790
791
0
}
792
793
/*[clinic input]
794
class module "PyModuleObject *" "&PyModule_Type"
795
[clinic start generated code]*/
796
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
797
798
#include "clinic/moduleobject.c.h"
799
800
/* Methods */
801
802
/*[clinic input]
803
module.__init__
804
    name: unicode
805
    doc: object = None
806
807
Create a module object.
808
809
The name must be a string; the optional doc argument can have any type.
810
[clinic start generated code]*/
811
812
static int
813
module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
814
/*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
815
957
{
816
957
    return module_init_dict(self, self->md_dict, name, doc);
817
957
}
818
819
static void
820
module_dealloc(PyObject *self)
821
8
{
822
8
    PyModuleObject *m = _PyModule_CAST(self);
823
824
8
    PyObject_GC_UnTrack(m);
825
826
8
    int verbose = _Py_GetConfig()->verbose;
827
8
    if (verbose && m->md_name) {
828
0
        PySys_FormatStderr("# destroy %U\n", m->md_name);
829
0
    }
830
8
    FT_CLEAR_WEAKREFS(self, m->md_weaklist);
831
832
    /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
833
8
    if (m->md_def && m->md_def->m_free
834
8
        && (m->md_def->m_size <= 0 || m->md_state != NULL))
835
0
    {
836
0
        m->md_def->m_free(m);
837
0
    }
838
839
8
    Py_XDECREF(m->md_dict);
840
8
    Py_XDECREF(m->md_name);
841
8
    if (m->md_state != NULL)
842
0
        PyMem_Free(m->md_state);
843
8
    Py_TYPE(m)->tp_free((PyObject *)m);
844
8
}
845
846
static PyObject *
847
module_repr(PyObject *self)
848
0
{
849
0
    PyModuleObject *m = _PyModule_CAST(self);
850
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
851
0
    return _PyImport_ImportlibModuleRepr(interp, (PyObject *)m);
852
0
}
853
854
/* Check if the "_initializing" attribute of the module spec is set to true.
855
 */
856
int
857
_PyModuleSpec_IsInitializing(PyObject *spec)
858
33.1k
{
859
33.1k
    if (spec == NULL) {
860
0
        return 0;
861
0
    }
862
33.1k
    PyObject *value;
863
33.1k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_initializing), &value);
864
33.1k
    if (rc > 0) {
865
32.3k
        rc = PyObject_IsTrue(value);
866
32.3k
        Py_DECREF(value);
867
32.3k
    }
868
33.1k
    return rc;
869
33.1k
}
870
871
/* Check if the submodule name is in the "_uninitialized_submodules" attribute
872
   of the module spec.
873
 */
874
int
875
_PyModuleSpec_IsUninitializedSubmodule(PyObject *spec, PyObject *name)
876
673
{
877
673
    if (spec == NULL) {
878
0
         return 0;
879
0
    }
880
881
673
    PyObject *value;
882
673
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_uninitialized_submodules), &value);
883
673
    if (rc > 0) {
884
481
        rc = PySequence_Contains(value, name);
885
481
        Py_DECREF(value);
886
481
    }
887
673
    return rc;
888
673
}
889
890
int
891
_PyModuleSpec_GetFileOrigin(PyObject *spec, PyObject **p_origin)
892
693
{
893
693
    PyObject *has_location = NULL;
894
693
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(has_location), &has_location);
895
693
    if (rc <= 0) {
896
192
        return rc;
897
192
    }
898
    // If origin is not a location, or doesn't exist, or is not a str, we could consider falling
899
    // back to module.__file__. But the cases in which module.__file__ is not __spec__.origin
900
    // are cases in which we probably shouldn't be guessing.
901
501
    rc = PyObject_IsTrue(has_location);
902
501
    Py_DECREF(has_location);
903
501
    if (rc <= 0) {
904
32
        return rc;
905
32
    }
906
    // has_location is true, so origin is a location
907
469
    PyObject *origin = NULL;
908
469
    rc = PyObject_GetOptionalAttr(spec, &_Py_ID(origin), &origin);
909
469
    if (rc <= 0) {
910
0
        return rc;
911
0
    }
912
469
    assert(origin != NULL);
913
469
    if (!PyUnicode_Check(origin)) {
914
0
        Py_DECREF(origin);
915
0
        return 0;
916
0
    }
917
469
    *p_origin = origin;
918
469
    return 1;
919
469
}
920
921
int
922
_PyModule_IsPossiblyShadowing(PyObject *origin)
923
693
{
924
    // origin must be a unicode subtype
925
    // Returns 1 if the module at origin could be shadowing a module of the
926
    // same name later in the module search path. The condition we check is basically:
927
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
928
    // return not sys.flags.safe_path and root == (sys.path[0] or os.getcwd())
929
    // Returns 0 otherwise (or if we aren't sure)
930
    // Returns -1 if an error occurred that should be propagated
931
693
    if (origin == NULL) {
932
224
        return 0;
933
224
    }
934
935
    // not sys.flags.safe_path
936
469
    const PyConfig *config = _Py_GetConfig();
937
469
    if (config->safe_path) {
938
0
        return 0;
939
0
    }
940
941
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
942
469
    wchar_t root[MAXPATHLEN + 1];
943
469
    Py_ssize_t size = PyUnicode_AsWideChar(origin, root, MAXPATHLEN);
944
469
    if (size < 0) {
945
0
        return -1;
946
0
    }
947
469
    assert(size <= MAXPATHLEN);
948
469
    root[size] = L'\0';
949
950
469
    wchar_t *sep = wcsrchr(root, SEP);
951
469
    if (sep == NULL) {
952
0
        return 0;
953
0
    }
954
    // If it's a package then we need to look one directory further up
955
469
    if (wcscmp(sep + 1, L"__init__.py") == 0) {
956
0
        *sep = L'\0';
957
0
        sep = wcsrchr(root, SEP);
958
0
        if (sep == NULL) {
959
0
            return 0;
960
0
        }
961
0
    }
962
469
    *sep = L'\0';
963
964
    // sys.path[0] or os.getcwd()
965
469
    wchar_t *sys_path_0 = config->sys_path_0;
966
469
    if (!sys_path_0) {
967
469
        return 0;
968
469
    }
969
970
0
    wchar_t sys_path_0_buf[MAXPATHLEN];
971
0
    if (sys_path_0[0] == L'\0') {
972
        // if sys.path[0] == "", treat it as if it were the current directory
973
0
        if (!_Py_wgetcwd(sys_path_0_buf, MAXPATHLEN)) {
974
            // If we failed to getcwd, don't raise an exception and instead
975
            // let the caller proceed assuming no shadowing
976
0
            return 0;
977
0
        }
978
0
        sys_path_0 = sys_path_0_buf;
979
0
    }
980
981
0
    int result = wcscmp(sys_path_0, root) == 0;
982
0
    return result;
983
0
}
984
985
PyObject*
986
_Py_module_getattro_impl(PyModuleObject *m, PyObject *name, int suppress)
987
108k
{
988
    // When suppress=1, this function suppresses AttributeError.
989
108k
    PyObject *attr, *mod_name, *getattr;
990
108k
    attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
991
108k
    if (attr) {
992
103k
        return attr;
993
103k
    }
994
5.60k
    if (suppress == 1) {
995
4.93k
        if (PyErr_Occurred()) {
996
            // pass up non-AttributeError exception
997
0
            return NULL;
998
0
        }
999
4.93k
    }
1000
673
    else {
1001
673
        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1002
            // pass up non-AttributeError exception
1003
0
            return NULL;
1004
0
        }
1005
673
        PyErr_Clear();
1006
673
    }
1007
5.60k
    assert(m->md_dict != NULL);
1008
5.60k
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__getattr__), &getattr) < 0) {
1009
0
        return NULL;
1010
0
    }
1011
5.60k
    if (getattr) {
1012
0
        PyObject *result = PyObject_CallOneArg(getattr, name);
1013
0
        if (result == NULL && suppress == 1 && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1014
            // suppress AttributeError
1015
0
            PyErr_Clear();
1016
0
        }
1017
0
        Py_DECREF(getattr);
1018
0
        return result;
1019
0
    }
1020
1021
    // The attribute was not found.  We make a best effort attempt at a useful error message,
1022
    // but only if we're not suppressing AttributeError.
1023
5.60k
    if (suppress == 1) {
1024
4.93k
        return NULL;
1025
4.93k
    }
1026
673
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__name__), &mod_name) < 0) {
1027
0
        return NULL;
1028
0
    }
1029
673
    if (!mod_name || !PyUnicode_Check(mod_name)) {
1030
0
        Py_XDECREF(mod_name);
1031
0
        PyErr_Format(PyExc_AttributeError,
1032
0
                    "module has no attribute '%U'", name);
1033
0
        return NULL;
1034
0
    }
1035
673
    PyObject *spec;
1036
673
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__spec__), &spec) < 0) {
1037
0
        Py_DECREF(mod_name);
1038
0
        return NULL;
1039
0
    }
1040
673
    if (spec == NULL) {
1041
0
        PyErr_Format(PyExc_AttributeError,
1042
0
                     "module '%U' has no attribute '%U'",
1043
0
                     mod_name, name);
1044
0
        Py_DECREF(mod_name);
1045
0
        return NULL;
1046
0
    }
1047
1048
673
    PyObject *origin = NULL;
1049
673
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
1050
0
        goto done;
1051
0
    }
1052
1053
673
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
1054
673
    if (is_possibly_shadowing < 0) {
1055
0
        goto done;
1056
0
    }
1057
673
    int is_possibly_shadowing_stdlib = 0;
1058
673
    if (is_possibly_shadowing) {
1059
0
        PyObject *stdlib_modules;
1060
0
        if (PySys_GetOptionalAttrString("stdlib_module_names", &stdlib_modules) < 0) {
1061
0
            goto done;
1062
0
        }
1063
0
        if (stdlib_modules && PyAnySet_Check(stdlib_modules)) {
1064
0
            is_possibly_shadowing_stdlib = PySet_Contains(stdlib_modules, mod_name);
1065
0
            if (is_possibly_shadowing_stdlib < 0) {
1066
0
                Py_DECREF(stdlib_modules);
1067
0
                goto done;
1068
0
            }
1069
0
        }
1070
0
        Py_XDECREF(stdlib_modules);
1071
0
    }
1072
1073
673
    if (is_possibly_shadowing_stdlib) {
1074
0
        assert(origin);
1075
0
        PyErr_Format(PyExc_AttributeError,
1076
0
                    "module '%U' has no attribute '%U' "
1077
0
                    "(consider renaming '%U' since it has the same "
1078
0
                    "name as the standard library module named '%U' "
1079
0
                    "and prevents importing that standard library module)",
1080
0
                    mod_name, name, origin, mod_name);
1081
0
    }
1082
673
    else {
1083
673
        int rc = _PyModuleSpec_IsInitializing(spec);
1084
673
        if (rc < 0) {
1085
0
            goto done;
1086
0
        }
1087
673
        else if (rc > 0) {
1088
0
            if (is_possibly_shadowing) {
1089
0
                assert(origin);
1090
                // For non-stdlib modules, only mention the possibility of
1091
                // shadowing if the module is being initialized.
1092
0
                PyErr_Format(PyExc_AttributeError,
1093
0
                            "module '%U' has no attribute '%U' "
1094
0
                            "(consider renaming '%U' if it has the same name "
1095
0
                            "as a library you intended to import)",
1096
0
                            mod_name, name, origin);
1097
0
            }
1098
0
            else if (origin) {
1099
0
                PyErr_Format(PyExc_AttributeError,
1100
0
                            "partially initialized "
1101
0
                            "module '%U' from '%U' has no attribute '%U' "
1102
0
                            "(most likely due to a circular import)",
1103
0
                            mod_name, origin, name);
1104
0
            }
1105
0
            else {
1106
0
                PyErr_Format(PyExc_AttributeError,
1107
0
                            "partially initialized "
1108
0
                            "module '%U' has no attribute '%U' "
1109
0
                            "(most likely due to a circular import)",
1110
0
                            mod_name, name);
1111
0
            }
1112
0
        }
1113
673
        else {
1114
673
            assert(rc == 0);
1115
673
            rc = _PyModuleSpec_IsUninitializedSubmodule(spec, name);
1116
673
            if (rc > 0) {
1117
0
                PyErr_Format(PyExc_AttributeError,
1118
0
                            "cannot access submodule '%U' of module '%U' "
1119
0
                            "(most likely due to a circular import)",
1120
0
                            name, mod_name);
1121
0
            }
1122
673
            else if (rc == 0) {
1123
673
                PyErr_Format(PyExc_AttributeError,
1124
673
                            "module '%U' has no attribute '%U'",
1125
673
                            mod_name, name);
1126
673
            }
1127
673
        }
1128
673
    }
1129
1130
673
done:
1131
673
    Py_XDECREF(origin);
1132
673
    Py_DECREF(spec);
1133
673
    Py_DECREF(mod_name);
1134
673
    return NULL;
1135
673
}
1136
1137
1138
PyObject*
1139
_Py_module_getattro(PyObject *self, PyObject *name)
1140
47.7k
{
1141
47.7k
    PyModuleObject *m = _PyModule_CAST(self);
1142
47.7k
    return _Py_module_getattro_impl(m, name, 0);
1143
47.7k
}
1144
1145
static int
1146
module_traverse(PyObject *self, visitproc visit, void *arg)
1147
542k
{
1148
542k
    PyModuleObject *m = _PyModule_CAST(self);
1149
1150
    /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
1151
542k
    if (m->md_def && m->md_def->m_traverse
1152
542k
        && (m->md_def->m_size <= 0 || m->md_state != NULL))
1153
85.4k
    {
1154
85.4k
        int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
1155
85.4k
        if (res)
1156
0
            return res;
1157
85.4k
    }
1158
1159
542k
    Py_VISIT(m->md_dict);
1160
542k
    return 0;
1161
542k
}
1162
1163
static int
1164
module_clear(PyObject *self)
1165
0
{
1166
0
    PyModuleObject *m = _PyModule_CAST(self);
1167
1168
    /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
1169
0
    if (m->md_def && m->md_def->m_clear
1170
0
        && (m->md_def->m_size <= 0 || m->md_state != NULL))
1171
0
    {
1172
0
        int res = m->md_def->m_clear((PyObject*)m);
1173
0
        if (PyErr_Occurred()) {
1174
0
            PyErr_FormatUnraisable("Exception ignored in m_clear of module%s%V",
1175
0
                                   m->md_name ? " " : "",
1176
0
                                   m->md_name, "");
1177
0
        }
1178
0
        if (res)
1179
0
            return res;
1180
0
    }
1181
0
    Py_CLEAR(m->md_dict);
1182
0
    return 0;
1183
0
}
1184
1185
static PyObject *
1186
module_dir(PyObject *self, PyObject *args)
1187
20
{
1188
20
    PyObject *result = NULL;
1189
20
    PyObject *dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
1190
1191
20
    if (dict != NULL) {
1192
20
        if (PyDict_Check(dict)) {
1193
20
            PyObject *dirfunc = PyDict_GetItemWithError(dict, &_Py_ID(__dir__));
1194
20
            if (dirfunc) {
1195
0
                result = _PyObject_CallNoArgs(dirfunc);
1196
0
            }
1197
20
            else if (!PyErr_Occurred()) {
1198
20
                result = PyDict_Keys(dict);
1199
20
            }
1200
20
        }
1201
0
        else {
1202
0
            PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
1203
0
        }
1204
20
    }
1205
1206
20
    Py_XDECREF(dict);
1207
20
    return result;
1208
20
}
1209
1210
static PyMethodDef module_methods[] = {
1211
    {"__dir__", module_dir, METH_NOARGS,
1212
     PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
1213
    {0}
1214
};
1215
1216
static PyObject *
1217
module_get_dict(PyModuleObject *m)
1218
0
{
1219
0
    PyObject *dict = PyObject_GetAttr((PyObject *)m, &_Py_ID(__dict__));
1220
0
    if (dict == NULL) {
1221
0
        return NULL;
1222
0
    }
1223
0
    if (!PyDict_Check(dict)) {
1224
0
        PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
1225
0
        Py_DECREF(dict);
1226
0
        return NULL;
1227
0
    }
1228
0
    return dict;
1229
0
}
1230
1231
static PyObject *
1232
module_get_annotate(PyObject *self, void *Py_UNUSED(ignored))
1233
0
{
1234
0
    PyModuleObject *m = _PyModule_CAST(self);
1235
1236
0
    PyObject *dict = module_get_dict(m);
1237
0
    if (dict == NULL) {
1238
0
        return NULL;
1239
0
    }
1240
1241
0
    PyObject *annotate;
1242
0
    if (PyDict_GetItemRef(dict, &_Py_ID(__annotate__), &annotate) == 0) {
1243
0
        annotate = Py_None;
1244
0
        if (PyDict_SetItem(dict, &_Py_ID(__annotate__), annotate) == -1) {
1245
0
            Py_CLEAR(annotate);
1246
0
        }
1247
0
    }
1248
0
    Py_DECREF(dict);
1249
0
    return annotate;
1250
0
}
1251
1252
static int
1253
module_set_annotate(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
1254
0
{
1255
0
    PyModuleObject *m = _PyModule_CAST(self);
1256
0
    if (value == NULL) {
1257
0
        PyErr_SetString(PyExc_TypeError, "cannot delete __annotate__ attribute");
1258
0
        return -1;
1259
0
    }
1260
1261
0
    PyObject *dict = module_get_dict(m);
1262
0
    if (dict == NULL) {
1263
0
        return -1;
1264
0
    }
1265
1266
0
    if (!Py_IsNone(value) && !PyCallable_Check(value)) {
1267
0
        PyErr_SetString(PyExc_TypeError, "__annotate__ must be callable or None");
1268
0
        Py_DECREF(dict);
1269
0
        return -1;
1270
0
    }
1271
1272
0
    if (PyDict_SetItem(dict, &_Py_ID(__annotate__), value) == -1) {
1273
0
        Py_DECREF(dict);
1274
0
        return -1;
1275
0
    }
1276
0
    if (!Py_IsNone(value)) {
1277
0
        if (PyDict_Pop(dict, &_Py_ID(__annotations__), NULL) == -1) {
1278
0
            Py_DECREF(dict);
1279
0
            return -1;
1280
0
        }
1281
0
    }
1282
0
    Py_DECREF(dict);
1283
0
    return 0;
1284
0
}
1285
1286
static PyObject *
1287
module_get_annotations(PyObject *self, void *Py_UNUSED(ignored))
1288
0
{
1289
0
    PyModuleObject *m = _PyModule_CAST(self);
1290
1291
0
    PyObject *dict = module_get_dict(m);
1292
0
    if (dict == NULL) {
1293
0
        return NULL;
1294
0
    }
1295
1296
0
    PyObject *annotations;
1297
0
    if (PyDict_GetItemRef(dict, &_Py_ID(__annotations__), &annotations) == 0) {
1298
0
        PyObject *spec;
1299
0
        if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__spec__), &spec) < 0) {
1300
0
            Py_DECREF(dict);
1301
0
            return NULL;
1302
0
        }
1303
0
        bool is_initializing = false;
1304
0
        if (spec != NULL) {
1305
0
            int rc = _PyModuleSpec_IsInitializing(spec);
1306
0
            if (rc < 0) {
1307
0
                Py_DECREF(spec);
1308
0
                Py_DECREF(dict);
1309
0
                return NULL;
1310
0
            }
1311
0
            Py_DECREF(spec);
1312
0
            if (rc) {
1313
0
                is_initializing = true;
1314
0
            }
1315
0
        }
1316
1317
0
        PyObject *annotate;
1318
0
        int annotate_result = PyDict_GetItemRef(dict, &_Py_ID(__annotate__), &annotate);
1319
0
        if (annotate_result < 0) {
1320
0
            Py_DECREF(dict);
1321
0
            return NULL;
1322
0
        }
1323
0
        if (annotate_result == 1 && PyCallable_Check(annotate)) {
1324
0
            PyObject *one = _PyLong_GetOne();
1325
0
            annotations = _PyObject_CallOneArg(annotate, one);
1326
0
            if (annotations == NULL) {
1327
0
                Py_DECREF(annotate);
1328
0
                Py_DECREF(dict);
1329
0
                return NULL;
1330
0
            }
1331
0
            if (!PyDict_Check(annotations)) {
1332
0
                PyErr_Format(PyExc_TypeError,
1333
0
                             "__annotate__() must return a dict, not %T",
1334
0
                             annotations);
1335
0
                Py_DECREF(annotate);
1336
0
                Py_DECREF(annotations);
1337
0
                Py_DECREF(dict);
1338
0
                return NULL;
1339
0
            }
1340
0
        }
1341
0
        else {
1342
0
            annotations = PyDict_New();
1343
0
        }
1344
0
        Py_XDECREF(annotate);
1345
        // Do not cache annotations if the module is still initializing
1346
0
        if (annotations && !is_initializing) {
1347
0
            int result = PyDict_SetItem(
1348
0
                    dict, &_Py_ID(__annotations__), annotations);
1349
0
            if (result) {
1350
0
                Py_CLEAR(annotations);
1351
0
            }
1352
0
        }
1353
0
    }
1354
0
    Py_DECREF(dict);
1355
0
    return annotations;
1356
0
}
1357
1358
static int
1359
module_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
1360
0
{
1361
0
    PyModuleObject *m = _PyModule_CAST(self);
1362
1363
0
    PyObject *dict = module_get_dict(m);
1364
0
    if (dict == NULL) {
1365
0
        return -1;
1366
0
    }
1367
1368
0
    int ret = -1;
1369
0
    if (value != NULL) {
1370
        /* set */
1371
0
        ret = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
1372
0
    }
1373
0
    else {
1374
        /* delete */
1375
0
        ret = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
1376
0
        if (ret == 0) {
1377
0
            PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__annotations__));
1378
0
            ret = -1;
1379
0
        }
1380
0
        else if (ret > 0) {
1381
0
            ret = 0;
1382
0
        }
1383
0
    }
1384
0
    if (ret == 0 && PyDict_Pop(dict, &_Py_ID(__annotate__), NULL) < 0) {
1385
0
        ret = -1;
1386
0
    }
1387
1388
0
    Py_DECREF(dict);
1389
0
    return ret;
1390
0
}
1391
1392
1393
static PyGetSetDef module_getsets[] = {
1394
    {"__annotations__", module_get_annotations, module_set_annotations},
1395
    {"__annotate__", module_get_annotate, module_set_annotate},
1396
    {NULL}
1397
};
1398
1399
PyTypeObject PyModule_Type = {
1400
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1401
    "module",                                   /* tp_name */
1402
    sizeof(PyModuleObject),                     /* tp_basicsize */
1403
    0,                                          /* tp_itemsize */
1404
    module_dealloc,                             /* tp_dealloc */
1405
    0,                                          /* tp_vectorcall_offset */
1406
    0,                                          /* tp_getattr */
1407
    0,                                          /* tp_setattr */
1408
    0,                                          /* tp_as_async */
1409
    module_repr,                                /* tp_repr */
1410
    0,                                          /* tp_as_number */
1411
    0,                                          /* tp_as_sequence */
1412
    0,                                          /* tp_as_mapping */
1413
    0,                                          /* tp_hash */
1414
    0,                                          /* tp_call */
1415
    0,                                          /* tp_str */
1416
    _Py_module_getattro,                        /* tp_getattro */
1417
    PyObject_GenericSetAttr,                    /* tp_setattro */
1418
    0,                                          /* tp_as_buffer */
1419
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1420
        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
1421
    module___init____doc__,                     /* tp_doc */
1422
    module_traverse,                            /* tp_traverse */
1423
    module_clear,                               /* tp_clear */
1424
    0,                                          /* tp_richcompare */
1425
    offsetof(PyModuleObject, md_weaklist),      /* tp_weaklistoffset */
1426
    0,                                          /* tp_iter */
1427
    0,                                          /* tp_iternext */
1428
    module_methods,                             /* tp_methods */
1429
    module_members,                             /* tp_members */
1430
    module_getsets,                             /* tp_getset */
1431
    0,                                          /* tp_base */
1432
    0,                                          /* tp_dict */
1433
    0,                                          /* tp_descr_get */
1434
    0,                                          /* tp_descr_set */
1435
    offsetof(PyModuleObject, md_dict),          /* tp_dictoffset */
1436
    module___init__,                            /* tp_init */
1437
    0,                                          /* tp_alloc */
1438
    new_module,                                 /* tp_new */
1439
    PyObject_GC_Del,                            /* tp_free */
1440
};