Coverage Report

Created: 2025-07-04 06:49

/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
700k
    (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
814
{
55
814
    assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
56
814
    if (def->m_base.m_index == 0) {
57
439
        Py_SET_REFCNT(def, 1);
58
439
        Py_SET_TYPE(def, &PyModuleDef_Type);
59
439
        def->m_base.m_index = _PyImport_GetNextModuleIndex();
60
439
    }
61
814
    return (PyObject*)def;
62
814
}
63
64
static int
65
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
66
                 PyObject *name, PyObject *doc)
67
1.39k
{
68
1.39k
    assert(md_dict != NULL);
69
1.39k
    if (doc == NULL)
70
487
        doc = Py_None;
71
72
1.39k
    if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
73
0
        return -1;
74
1.39k
    if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
75
0
        return -1;
76
1.39k
    if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
77
0
        return -1;
78
1.39k
    if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
79
0
        return -1;
80
1.39k
    if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
81
0
        return -1;
82
1.39k
    if (PyUnicode_CheckExact(name)) {
83
1.39k
        Py_XSETREF(mod->md_name, Py_NewRef(name));
84
1.39k
    }
85
86
1.39k
    return 0;
87
1.39k
}
88
89
static PyModuleObject *
90
new_module_notrack(PyTypeObject *mt)
91
1.39k
{
92
1.39k
    PyModuleObject *m;
93
1.39k
    m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
94
1.39k
    if (m == NULL)
95
0
        return NULL;
96
1.39k
    m->md_def = NULL;
97
1.39k
    m->md_state = NULL;
98
1.39k
    m->md_weaklist = NULL;
99
1.39k
    m->md_name = NULL;
100
1.39k
    m->md_dict = PyDict_New();
101
1.39k
    if (m->md_dict == NULL) {
102
0
        Py_DECREF(m);
103
0
        return NULL;
104
0
    }
105
1.39k
    return m;
106
1.39k
}
107
108
static void
109
track_module(PyModuleObject *m)
110
1.39k
{
111
1.39k
    _PyDict_EnablePerThreadRefcounting(m->md_dict);
112
1.39k
    _PyObject_SetDeferredRefcount((PyObject *)m);
113
1.39k
    PyObject_GC_Track(m);
114
1.39k
}
115
116
static PyObject *
117
new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
118
912
{
119
912
    PyModuleObject *m = new_module_notrack(mt);
120
912
    if (m != NULL) {
121
912
        track_module(m);
122
912
    }
123
912
    return (PyObject *)m;
124
912
}
125
126
PyObject *
127
PyModule_NewObject(PyObject *name)
128
487
{
129
487
    PyModuleObject *m = new_module_notrack(&PyModule_Type);
130
487
    if (m == NULL)
131
0
        return NULL;
132
487
    if (module_init_dict(m, m->md_dict, name, NULL) != 0)
133
0
        goto fail;
134
487
    track_module(m);
135
487
    return (PyObject *)m;
136
137
0
 fail:
138
0
    Py_DECREF(m);
139
0
    return NULL;
140
487
}
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
439
{
161
439
    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
439
    return 1;
172
439
}
173
174
static int
175
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
176
417
{
177
417
    PyObject *func;
178
417
    PyMethodDef *fdef;
179
180
9.30k
    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
181
8.89k
        if ((fdef->ml_flags & METH_CLASS) ||
182
8.89k
            (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.89k
        func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
189
8.89k
        if (func == NULL) {
190
0
            return -1;
191
0
        }
192
8.89k
        _PyObject_SetDeferredRefcount(func);
193
8.89k
        if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
194
0
            Py_DECREF(func);
195
0
            return -1;
196
0
        }
197
8.89k
        Py_DECREF(func);
198
8.89k
    }
199
200
417
    return 0;
201
417
}
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
375
{
270
375
    PyModuleDef_Slot* cur_slot;
271
375
    PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
272
375
    PyObject *nameobj;
273
375
    PyObject *m = NULL;
274
375
    int has_multiple_interpreters_slot = 0;
275
375
    void *multiple_interpreters = (void *)0;
276
375
    int has_gil_slot = 0;
277
375
    void *gil_slot = Py_MOD_GIL_USED;
278
375
    int has_execution_slots = 0;
279
375
    const char *name;
280
375
    int ret;
281
375
    PyInterpreterState *interp = _PyInterpreterState_GET();
282
283
375
    PyModuleDef_Init(def);
284
285
375
    nameobj = PyObject_GetAttrString(spec, "name");
286
375
    if (nameobj == NULL) {
287
0
        return NULL;
288
0
    }
289
375
    name = PyUnicode_AsUTF8(nameobj);
290
375
    if (name == NULL) {
291
0
        goto error;
292
0
    }
293
294
375
    if (!check_api_version(name, module_api_version)) {
295
0
        goto error;
296
0
    }
297
298
375
    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.52k
    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
307
1.14k
        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
395
            case Py_mod_exec:
319
395
                has_execution_slots = 1;
320
395
                break;
321
375
            case Py_mod_multiple_interpreters:
322
375
                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
375
                multiple_interpreters = cur_slot->value;
330
375
                has_multiple_interpreters_slot = 1;
331
375
                break;
332
375
            case Py_mod_gil:
333
375
                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
375
                gil_slot = cur_slot->value;
341
375
                has_gil_slot = 1;
342
375
                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.14k
        }
351
1.14k
    }
352
353
    /* By default, multi-phase init modules are expected
354
       to work under multiple interpreters. */
355
375
    if (!has_multiple_interpreters_slot) {
356
0
        multiple_interpreters = Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
357
0
    }
358
375
    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
375
    else if (multiple_interpreters != Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
366
375
             && interp->ceval.own_gil
367
375
             && !_Py_IsMainInterpreter(interp)
368
375
             && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
369
0
    {
370
0
        goto error;
371
0
    }
372
373
375
    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
375
    } else {
393
375
        m = PyModule_NewObject(nameobj);
394
375
        if (m == NULL) {
395
0
            goto error;
396
0
        }
397
375
    }
398
399
375
    if (PyModule_Check(m)) {
400
375
        ((PyModuleObject*)m)->md_state = NULL;
401
375
        ((PyModuleObject*)m)->md_def = def;
402
#ifdef Py_GIL_DISABLED
403
        ((PyModuleObject*)m)->md_gil = gil_slot;
404
#else
405
375
        (void)gil_slot;
406
375
#endif
407
375
    } 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
375
    if (def->m_methods != NULL) {
426
353
        ret = _add_methods_to_object(m, nameobj, def->m_methods);
427
353
        if (ret != 0) {
428
0
            goto error;
429
0
        }
430
353
    }
431
432
375
    if (def->m_doc != NULL) {
433
324
        ret = PyModule_SetDocString(m, def->m_doc);
434
324
        if (ret != 0) {
435
0
            goto error;
436
0
        }
437
324
    }
438
439
375
    Py_DECREF(nameobj);
440
375
    return m;
441
442
0
error:
443
0
    Py_DECREF(nameobj);
444
0
    Py_XDECREF(m);
445
0
    return NULL;
446
375
}
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
375
{
464
375
    PyModuleDef_Slot *cur_slot;
465
375
    const char *name;
466
375
    int ret;
467
468
375
    name = PyModule_GetName(module);
469
375
    if (name == NULL) {
470
0
        return -1;
471
0
    }
472
473
375
    if (def->m_size >= 0) {
474
375
        PyModuleObject *md = (PyModuleObject*)module;
475
375
        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
375
            md->md_state = PyMem_Malloc(def->m_size);
479
375
            if (!md->md_state) {
480
0
                PyErr_NoMemory();
481
0
                return -1;
482
0
            }
483
375
            memset(md->md_state, 0, def->m_size);
484
375
        }
485
375
    }
486
487
375
    if (def->m_slots == NULL) {
488
0
        return 0;
489
0
    }
490
491
1.52k
    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
492
1.14k
        switch (cur_slot->slot) {
493
0
            case Py_mod_create:
494
                /* handled in PyModule_FromDefAndSpec2 */
495
0
                break;
496
395
            case Py_mod_exec:
497
395
                ret = ((int (*)(PyObject *))cur_slot->value)(module);
498
395
                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
395
                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
395
                break;
515
395
            case Py_mod_multiple_interpreters:
516
750
            case Py_mod_gil:
517
                /* handled in PyModule_FromDefAndSpec2 */
518
750
                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.14k
        }
526
1.14k
    }
527
375
    return 0;
528
375
}
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
372
{
547
372
    PyObject *v;
548
549
372
    v = PyUnicode_FromString(doc);
550
372
    if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
551
0
        Py_XDECREF(v);
552
0
        return -1;
553
0
    }
554
372
    Py_DECREF(v);
555
372
    return 0;
556
372
}
557
558
PyObject *
559
PyModule_GetDict(PyObject *m)
560
8.86k
{
561
8.86k
    if (!PyModule_Check(m)) {
562
0
        PyErr_BadInternalCall();
563
0
        return NULL;
564
0
    }
565
8.86k
    return _PyModule_GetDict(m);  // borrowed reference
566
8.86k
}
567
568
PyObject*
569
PyModule_GetNameObject(PyObject *mod)
570
439
{
571
439
    if (!PyModule_Check(mod)) {
572
0
        PyErr_BadArgument();
573
0
        return NULL;
574
0
    }
575
439
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
576
439
    if (dict == NULL || !PyDict_Check(dict)) {
577
0
        goto error;
578
0
    }
579
439
    PyObject *name;
580
439
    if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
581
        // error or not found
582
0
        goto error;
583
0
    }
584
439
    if (!PyUnicode_Check(name)) {
585
0
        Py_DECREF(name);
586
0
        goto error;
587
0
    }
588
439
    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
439
}
596
597
const char *
598
PyModule_GetName(PyObject *m)
599
375
{
600
375
    PyObject *name = PyModule_GetNameObject(m);
601
375
    if (name == NULL) {
602
0
        return NULL;
603
0
    }
604
375
    assert(Py_REFCNT(name) >= 2);
605
375
    Py_DECREF(name);   /* module dict has still a reference */
606
375
    return PyUnicode_AsUTF8(name);
607
375
}
608
609
PyObject*
610
_PyModule_GetFilenameObject(PyObject *mod)
611
14
{
612
    // We return None to indicate "not found" or "bogus".
613
14
    if (!PyModule_Check(mod)) {
614
0
        PyErr_BadArgument();
615
0
        return NULL;
616
0
    }
617
14
    PyObject *dict = ((PyModuleObject *)mod)->md_dict;  // borrowed reference
618
14
    if (dict == NULL) {
619
        // The module has been tampered with.
620
0
        Py_RETURN_NONE;
621
0
    }
622
14
    PyObject *fileobj;
623
14
    int res = PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj);
624
14
    if (res < 0) {
625
0
        return NULL;
626
0
    }
627
14
    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
10
        Py_RETURN_NONE;
635
10
    }
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
14
{
646
14
    PyObject *fileobj = _PyModule_GetFilenameObject(mod);
647
14
    if (fileobj == NULL) {
648
0
        return NULL;
649
0
    }
650
14
    if (fileobj == Py_None) {
651
10
        PyErr_SetString(PyExc_SystemError, "module filename missing");
652
10
        return NULL;
653
10
    }
654
4
    return fileobj;
655
14
}
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
409
{
704
409
    if (!PyModule_Check(m)) {
705
0
        PyErr_BadArgument();
706
0
        return NULL;
707
0
    }
708
409
    return _PyModule_GetDef(m);
709
409
}
710
711
void*
712
PyModule_GetState(PyObject* m)
713
22.8M
{
714
22.8M
    if (!PyModule_Check(m)) {
715
0
        PyErr_BadArgument();
716
0
        return NULL;
717
0
    }
718
22.8M
    return _PyModule_GetState(m);
719
22.8M
}
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
912
{
816
912
    return module_init_dict(self, self->md_dict, name, doc);
817
912
}
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.8k
{
859
33.8k
    if (spec == NULL) {
860
0
        return 0;
861
0
    }
862
33.8k
    PyObject *value;
863
33.8k
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_initializing), &value);
864
33.8k
    if (rc > 0) {
865
33.0k
        rc = PyObject_IsTrue(value);
866
33.0k
        Py_DECREF(value);
867
33.0k
    }
868
33.8k
    return rc;
869
33.8k
}
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
700
{
877
700
    if (spec == NULL) {
878
0
         return 0;
879
0
    }
880
881
700
    PyObject *value;
882
700
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(_uninitialized_submodules), &value);
883
700
    if (rc > 0) {
884
508
        rc = PySequence_Contains(value, name);
885
508
        Py_DECREF(value);
886
508
    }
887
700
    return rc;
888
700
}
889
890
int
891
_PyModuleSpec_GetFileOrigin(PyObject *spec, PyObject **p_origin)
892
718
{
893
718
    PyObject *has_location = NULL;
894
718
    int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(has_location), &has_location);
895
718
    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
526
    rc = PyObject_IsTrue(has_location);
902
526
    Py_DECREF(has_location);
903
526
    if (rc <= 0) {
904
30
        return rc;
905
30
    }
906
    // has_location is true, so origin is a location
907
496
    PyObject *origin = NULL;
908
496
    rc = PyObject_GetOptionalAttr(spec, &_Py_ID(origin), &origin);
909
496
    if (rc <= 0) {
910
0
        return rc;
911
0
    }
912
496
    assert(origin != NULL);
913
496
    if (!PyUnicode_Check(origin)) {
914
0
        Py_DECREF(origin);
915
0
        return 0;
916
0
    }
917
496
    *p_origin = origin;
918
496
    return 1;
919
496
}
920
921
int
922
_PyModule_IsPossiblyShadowing(PyObject *origin)
923
718
{
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
718
    if (origin == NULL) {
932
222
        return 0;
933
222
    }
934
935
    // not sys.flags.safe_path
936
496
    const PyConfig *config = _Py_GetConfig();
937
496
    if (config->safe_path) {
938
0
        return 0;
939
0
    }
940
941
    // root = os.path.dirname(origin.removesuffix(os.sep + "__init__.py"))
942
496
    wchar_t root[MAXPATHLEN + 1];
943
496
    Py_ssize_t size = PyUnicode_AsWideChar(origin, root, MAXPATHLEN);
944
496
    if (size < 0) {
945
0
        return -1;
946
0
    }
947
496
    assert(size <= MAXPATHLEN);
948
496
    root[size] = L'\0';
949
950
496
    wchar_t *sep = wcsrchr(root, SEP);
951
496
    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
496
    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
496
    *sep = L'\0';
963
964
    // sys.path[0] or os.getcwd()
965
496
    wchar_t *sys_path_0 = config->sys_path_0;
966
496
    if (!sys_path_0) {
967
496
        return 0;
968
496
    }
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
107k
{
988
    // When suppress=1, this function suppresses AttributeError.
989
107k
    PyObject *attr, *mod_name, *getattr;
990
107k
    attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
991
107k
    if (attr) {
992
102k
        return attr;
993
102k
    }
994
5.43k
    if (suppress == 1) {
995
4.73k
        if (PyErr_Occurred()) {
996
            // pass up non-AttributeError exception
997
0
            return NULL;
998
0
        }
999
4.73k
    }
1000
700
    else {
1001
700
        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1002
            // pass up non-AttributeError exception
1003
0
            return NULL;
1004
0
        }
1005
700
        PyErr_Clear();
1006
700
    }
1007
5.43k
    assert(m->md_dict != NULL);
1008
5.43k
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__getattr__), &getattr) < 0) {
1009
0
        return NULL;
1010
0
    }
1011
5.43k
    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.43k
    if (suppress == 1) {
1024
4.73k
        return NULL;
1025
4.73k
    }
1026
700
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__name__), &mod_name) < 0) {
1027
0
        return NULL;
1028
0
    }
1029
700
    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
700
    PyObject *spec;
1036
700
    if (PyDict_GetItemRef(m->md_dict, &_Py_ID(__spec__), &spec) < 0) {
1037
0
        Py_DECREF(mod_name);
1038
0
        return NULL;
1039
0
    }
1040
700
    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
700
    PyObject *origin = NULL;
1049
700
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
1050
0
        goto done;
1051
0
    }
1052
1053
700
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
1054
700
    if (is_possibly_shadowing < 0) {
1055
0
        goto done;
1056
0
    }
1057
700
    int is_possibly_shadowing_stdlib = 0;
1058
700
    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
700
    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
700
    else {
1083
700
        int rc = _PyModuleSpec_IsInitializing(spec);
1084
700
        if (rc < 0) {
1085
0
            goto done;
1086
0
        }
1087
700
        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
700
        else {
1114
700
            assert(rc == 0);
1115
700
            rc = _PyModuleSpec_IsUninitializedSubmodule(spec, name);
1116
700
            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
700
            else if (rc == 0) {
1123
700
                PyErr_Format(PyExc_AttributeError,
1124
700
                            "module '%U' has no attribute '%U'",
1125
700
                            mod_name, name);
1126
700
            }
1127
700
        }
1128
700
    }
1129
1130
700
done:
1131
700
    Py_XDECREF(origin);
1132
700
    Py_DECREF(spec);
1133
700
    Py_DECREF(mod_name);
1134
700
    return NULL;
1135
700
}
1136
1137
1138
PyObject*
1139
_Py_module_getattro(PyObject *self, PyObject *name)
1140
45.5k
{
1141
45.5k
    PyModuleObject *m = _PyModule_CAST(self);
1142
45.5k
    return _Py_module_getattro_impl(m, name, 0);
1143
45.5k
}
1144
1145
static int
1146
module_traverse(PyObject *self, visitproc visit, void *arg)
1147
655k
{
1148
655k
    PyModuleObject *m = _PyModule_CAST(self);
1149
1150
    /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
1151
655k
    if (m->md_def && m->md_def->m_traverse
1152
655k
        && (m->md_def->m_size <= 0 || m->md_state != NULL))
1153
107k
    {
1154
107k
        int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
1155
107k
        if (res)
1156
0
            return res;
1157
107k
    }
1158
1159
655k
    Py_VISIT(m->md_dict);
1160
655k
    return 0;
1161
655k
}
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, "__annotate__ returned non-dict of type '%.100s'",
1333
0
                             Py_TYPE(annotations)->tp_name);
1334
0
                Py_DECREF(annotate);
1335
0
                Py_DECREF(annotations);
1336
0
                Py_DECREF(dict);
1337
0
                return NULL;
1338
0
            }
1339
0
        }
1340
0
        else {
1341
0
            annotations = PyDict_New();
1342
0
        }
1343
0
        Py_XDECREF(annotate);
1344
        // Do not cache annotations if the module is still initializing
1345
0
        if (annotations && !is_initializing) {
1346
0
            int result = PyDict_SetItem(
1347
0
                    dict, &_Py_ID(__annotations__), annotations);
1348
0
            if (result) {
1349
0
                Py_CLEAR(annotations);
1350
0
            }
1351
0
        }
1352
0
    }
1353
0
    Py_DECREF(dict);
1354
0
    return annotations;
1355
0
}
1356
1357
static int
1358
module_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
1359
0
{
1360
0
    PyModuleObject *m = _PyModule_CAST(self);
1361
1362
0
    PyObject *dict = module_get_dict(m);
1363
0
    if (dict == NULL) {
1364
0
        return -1;
1365
0
    }
1366
1367
0
    int ret = -1;
1368
0
    if (value != NULL) {
1369
        /* set */
1370
0
        ret = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
1371
0
    }
1372
0
    else {
1373
        /* delete */
1374
0
        ret = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
1375
0
        if (ret == 0) {
1376
0
            PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__annotations__));
1377
0
            ret = -1;
1378
0
        }
1379
0
        else if (ret > 0) {
1380
0
            ret = 0;
1381
0
        }
1382
0
    }
1383
0
    if (ret == 0 && PyDict_Pop(dict, &_Py_ID(__annotate__), NULL) < 0) {
1384
0
        ret = -1;
1385
0
    }
1386
1387
0
    Py_DECREF(dict);
1388
0
    return ret;
1389
0
}
1390
1391
1392
static PyGetSetDef module_getsets[] = {
1393
    {"__annotations__", module_get_annotations, module_set_annotations},
1394
    {"__annotate__", module_get_annotate, module_set_annotate},
1395
    {NULL}
1396
};
1397
1398
PyTypeObject PyModule_Type = {
1399
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1400
    "module",                                   /* tp_name */
1401
    sizeof(PyModuleObject),                     /* tp_basicsize */
1402
    0,                                          /* tp_itemsize */
1403
    module_dealloc,                             /* tp_dealloc */
1404
    0,                                          /* tp_vectorcall_offset */
1405
    0,                                          /* tp_getattr */
1406
    0,                                          /* tp_setattr */
1407
    0,                                          /* tp_as_async */
1408
    module_repr,                                /* tp_repr */
1409
    0,                                          /* tp_as_number */
1410
    0,                                          /* tp_as_sequence */
1411
    0,                                          /* tp_as_mapping */
1412
    0,                                          /* tp_hash */
1413
    0,                                          /* tp_call */
1414
    0,                                          /* tp_str */
1415
    _Py_module_getattro,                        /* tp_getattro */
1416
    PyObject_GenericSetAttr,                    /* tp_setattro */
1417
    0,                                          /* tp_as_buffer */
1418
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1419
        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
1420
    module___init____doc__,                     /* tp_doc */
1421
    module_traverse,                            /* tp_traverse */
1422
    module_clear,                               /* tp_clear */
1423
    0,                                          /* tp_richcompare */
1424
    offsetof(PyModuleObject, md_weaklist),      /* tp_weaklistoffset */
1425
    0,                                          /* tp_iter */
1426
    0,                                          /* tp_iternext */
1427
    module_methods,                             /* tp_methods */
1428
    module_members,                             /* tp_members */
1429
    module_getsets,                             /* tp_getset */
1430
    0,                                          /* tp_base */
1431
    0,                                          /* tp_dict */
1432
    0,                                          /* tp_descr_get */
1433
    0,                                          /* tp_descr_set */
1434
    offsetof(PyModuleObject, md_dict),          /* tp_dictoffset */
1435
    module___init__,                            /* tp_init */
1436
    0,                                          /* tp_alloc */
1437
    new_module,                                 /* tp_new */
1438
    PyObject_GC_Del,                            /* tp_free */
1439
};