1
2 /* Module object implementation */
3
4 #include "Python.h"
5 #include "pycore_call.h" // _PyObject_CallNoArgs()
6 #include "pycore_interp.h" // PyInterpreterState.importlib
7 #include "pycore_object.h" // _PyType_AllocNoTrack
8 #include "pycore_pystate.h" // _PyInterpreterState_GET()
9 #include "pycore_moduleobject.h" // _PyModule_GetDef()
10 #include "structmember.h" // PyMemberDef
11
12
13 static PyMemberDef module_members[] = {
14 {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
15 {0}
16 };
17
18
19 PyTypeObject PyModuleDef_Type = {
20 PyVarObject_HEAD_INIT(&PyType_Type, 0)
21 "moduledef", /* tp_name */
22 sizeof(PyModuleDef), /* tp_basicsize */
23 0, /* tp_itemsize */
24 };
25
26
27 int
28 _PyModule_IsExtension(PyObject *obj)
29 {
30 if (!PyModule_Check(obj)) {
31 return 0;
32 }
33 PyModuleObject *module = (PyModuleObject*)obj;
34
35 PyModuleDef *def = module->md_def;
36 return (def != NULL && def->m_methods != NULL);
37 }
38
39
40 PyObject*
41 PyModuleDef_Init(PyModuleDef* def)
42 {
43 assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
44 if (def->m_base.m_index == 0) {
45 Py_SET_REFCNT(def, 1);
46 Py_SET_TYPE(def, &PyModuleDef_Type);
47 def->m_base.m_index = _PyImport_GetNextModuleIndex();
48 }
49 return (PyObject*)def;
50 }
51
52 static int
53 module_init_dict(PyModuleObject *mod, PyObject *md_dict,
54 PyObject *name, PyObject *doc)
55 {
56 assert(md_dict != NULL);
57 if (doc == NULL)
58 doc = Py_None;
59
60 if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
61 return -1;
62 if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
63 return -1;
64 if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
65 return -1;
66 if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
67 return -1;
68 if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
69 return -1;
70 if (PyUnicode_CheckExact(name)) {
71 Py_XSETREF(mod->md_name, Py_NewRef(name));
72 }
73
74 return 0;
75 }
76
77 static PyModuleObject *
78 new_module_notrack(PyTypeObject *mt)
79 {
80 PyModuleObject *m;
81 m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
82 if (m == NULL)
83 return NULL;
84 m->md_def = NULL;
85 m->md_state = NULL;
86 m->md_weaklist = NULL;
87 m->md_name = NULL;
88 m->md_dict = PyDict_New();
89 if (m->md_dict != NULL) {
90 return m;
91 }
92 Py_DECREF(m);
93 return NULL;
94 }
95
96 static PyObject *
97 new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
98 {
99 PyObject *m = (PyObject *)new_module_notrack(mt);
100 if (m != NULL) {
101 PyObject_GC_Track(m);
102 }
103 return m;
104 }
105
106 PyObject *
107 PyModule_NewObject(PyObject *name)
108 {
109 PyModuleObject *m = new_module_notrack(&PyModule_Type);
110 if (m == NULL)
111 return NULL;
112 if (module_init_dict(m, m->md_dict, name, NULL) != 0)
113 goto fail;
114 PyObject_GC_Track(m);
115 return (PyObject *)m;
116
117 fail:
118 Py_DECREF(m);
119 return NULL;
120 }
121
122 PyObject *
123 PyModule_New(const char *name)
124 {
125 PyObject *nameobj, *module;
126 nameobj = PyUnicode_FromString(name);
127 if (nameobj == NULL)
128 return NULL;
129 module = PyModule_NewObject(nameobj);
130 Py_DECREF(nameobj);
131 return module;
132 }
133
134 /* Check API/ABI version
135 * Issues a warning on mismatch, which is usually not fatal.
136 * Returns 0 if an exception is raised.
137 */
138 static int
139 check_api_version(const char *name, int module_api_version)
140 {
141 if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
142 int err;
143 err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
144 "Python C API version mismatch for module %.100s: "
145 "This Python has API version %d, module %.100s has version %d.",
146 name,
147 PYTHON_API_VERSION, name, module_api_version);
148 if (err)
149 return 0;
150 }
151 return 1;
152 }
153
154 static int
155 _add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
156 {
157 PyObject *func;
158 PyMethodDef *fdef;
159
160 for (fdef = functions; fdef->ml_name != NULL; fdef++) {
161 if ((fdef->ml_flags & METH_CLASS) ||
162 (fdef->ml_flags & METH_STATIC)) {
163 PyErr_SetString(PyExc_ValueError,
164 "module functions cannot set"
165 " METH_CLASS or METH_STATIC");
166 return -1;
167 }
168 func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
169 if (func == NULL) {
170 return -1;
171 }
172 if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
173 Py_DECREF(func);
174 return -1;
175 }
176 Py_DECREF(func);
177 }
178
179 return 0;
180 }
181
182 PyObject *
183 PyModule_Create2(PyModuleDef* module, int module_api_version)
184 {
185 if (!_PyImport_IsInitialized(_PyInterpreterState_GET())) {
186 PyErr_SetString(PyExc_SystemError,
187 "Python import machinery not initialized");
188 return NULL;
189 }
190 return _PyModule_CreateInitialized(module, module_api_version);
191 }
192
193 PyObject *
194 _PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
195 {
196 const char* name;
197 PyModuleObject *m;
198
199 if (!PyModuleDef_Init(module))
200 return NULL;
201 name = module->m_name;
202 if (!check_api_version(name, module_api_version)) {
203 return NULL;
204 }
205 if (module->m_slots) {
206 PyErr_Format(
207 PyExc_SystemError,
208 "module %s: PyModule_Create is incompatible with m_slots", name);
209 return NULL;
210 }
211 name = _PyImport_ResolveNameWithPackageContext(name);
212 if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
213 return NULL;
214
215 if (module->m_size > 0) {
216 m->md_state = PyMem_Malloc(module->m_size);
217 if (!m->md_state) {
218 PyErr_NoMemory();
219 Py_DECREF(m);
220 return NULL;
221 }
222 memset(m->md_state, 0, module->m_size);
223 }
224
225 if (module->m_methods != NULL) {
226 if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
227 Py_DECREF(m);
228 return NULL;
229 }
230 }
231 if (module->m_doc != NULL) {
232 if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
233 Py_DECREF(m);
234 return NULL;
235 }
236 }
237 m->md_def = module;
238 return (PyObject*)m;
239 }
240
241 PyObject *
242 PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
243 {
244 PyModuleDef_Slot* cur_slot;
245 PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
246 PyObject *nameobj;
247 PyObject *m = NULL;
248 int has_multiple_interpreters_slot = 0;
249 void *multiple_interpreters = (void *)0;
250 int has_execution_slots = 0;
251 const char *name;
252 int ret;
253 PyInterpreterState *interp = _PyInterpreterState_GET();
254
255 PyModuleDef_Init(def);
256
257 nameobj = PyObject_GetAttrString(spec, "name");
258 if (nameobj == NULL) {
259 return NULL;
260 }
261 name = PyUnicode_AsUTF8(nameobj);
262 if (name == NULL) {
263 goto error;
264 }
265
266 if (!check_api_version(name, module_api_version)) {
267 goto error;
268 }
269
270 if (def->m_size < 0) {
271 PyErr_Format(
272 PyExc_SystemError,
273 "module %s: m_size may not be negative for multi-phase initialization",
274 name);
275 goto error;
276 }
277
278 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
279 switch (cur_slot->slot) {
280 case Py_mod_create:
281 if (create) {
282 PyErr_Format(
283 PyExc_SystemError,
284 "module %s has multiple create slots",
285 name);
286 goto error;
287 }
288 create = cur_slot->value;
289 break;
290 case Py_mod_exec:
291 has_execution_slots = 1;
292 break;
293 case Py_mod_multiple_interpreters:
294 if (has_multiple_interpreters_slot) {
295 PyErr_Format(
296 PyExc_SystemError,
297 "module %s has more than one 'multiple interpreters' slots",
298 name);
299 goto error;
300 }
301 multiple_interpreters = cur_slot->value;
302 has_multiple_interpreters_slot = 1;
303 break;
304 default:
305 assert(cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT);
306 PyErr_Format(
307 PyExc_SystemError,
308 "module %s uses unknown slot ID %i",
309 name, cur_slot->slot);
310 goto error;
311 }
312 }
313
314 /* By default, multi-phase init modules are expected
315 to work under multiple interpreters. */
316 if (!has_multiple_interpreters_slot) {
317 multiple_interpreters = Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
318 }
319 if (multiple_interpreters == Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED) {
320 if (!_Py_IsMainInterpreter(interp)
321 && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
322 {
323 goto error;
324 }
325 }
326 else if (multiple_interpreters != Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
327 && interp->ceval.own_gil
328 && !_Py_IsMainInterpreter(interp)
329 && _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
330 {
331 goto error;
332 }
333
334 if (create) {
335 m = create(spec, def);
336 if (m == NULL) {
337 if (!PyErr_Occurred()) {
338 PyErr_Format(
339 PyExc_SystemError,
340 "creation of module %s failed without setting an exception",
341 name);
342 }
343 goto error;
344 } else {
345 if (PyErr_Occurred()) {
346 _PyErr_FormatFromCause(
347 PyExc_SystemError,
348 "creation of module %s raised unreported exception",
349 name);
350 goto error;
351 }
352 }
353 } else {
354 m = PyModule_NewObject(nameobj);
355 if (m == NULL) {
356 goto error;
357 }
358 }
359
360 if (PyModule_Check(m)) {
361 ((PyModuleObject*)m)->md_state = NULL;
362 ((PyModuleObject*)m)->md_def = def;
363 } else {
364 if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
365 PyErr_Format(
366 PyExc_SystemError,
367 "module %s is not a module object, but requests module state",
368 name);
369 goto error;
370 }
371 if (has_execution_slots) {
372 PyErr_Format(
373 PyExc_SystemError,
374 "module %s specifies execution slots, but did not create "
375 "a ModuleType instance",
376 name);
377 goto error;
378 }
379 }
380
381 if (def->m_methods != NULL) {
382 ret = _add_methods_to_object(m, nameobj, def->m_methods);
383 if (ret != 0) {
384 goto error;
385 }
386 }
387
388 if (def->m_doc != NULL) {
389 ret = PyModule_SetDocString(m, def->m_doc);
390 if (ret != 0) {
391 goto error;
392 }
393 }
394
395 Py_DECREF(nameobj);
396 return m;
397
398 error:
399 Py_DECREF(nameobj);
400 Py_XDECREF(m);
401 return NULL;
402 }
403
404 int
405 PyModule_ExecDef(PyObject *module, PyModuleDef *def)
406 {
407 PyModuleDef_Slot *cur_slot;
408 const char *name;
409 int ret;
410
411 name = PyModule_GetName(module);
412 if (name == NULL) {
413 return -1;
414 }
415
416 if (def->m_size >= 0) {
417 PyModuleObject *md = (PyModuleObject*)module;
418 if (md->md_state == NULL) {
419 /* Always set a state pointer; this serves as a marker to skip
420 * multiple initialization (importlib.reload() is no-op) */
421 md->md_state = PyMem_Malloc(def->m_size);
422 if (!md->md_state) {
423 PyErr_NoMemory();
424 return -1;
425 }
426 memset(md->md_state, 0, def->m_size);
427 }
428 }
429
430 if (def->m_slots == NULL) {
431 return 0;
432 }
433
434 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
435 switch (cur_slot->slot) {
436 case Py_mod_create:
437 /* handled in PyModule_FromDefAndSpec2 */
438 break;
439 case Py_mod_exec:
440 ret = ((int (*)(PyObject *))cur_slot->value)(module);
441 if (ret != 0) {
442 if (!PyErr_Occurred()) {
443 PyErr_Format(
444 PyExc_SystemError,
445 "execution of module %s failed without setting an exception",
446 name);
447 }
448 return -1;
449 }
450 if (PyErr_Occurred()) {
451 _PyErr_FormatFromCause(
452 PyExc_SystemError,
453 "execution of module %s raised unreported exception",
454 name);
455 return -1;
456 }
457 break;
458 case Py_mod_multiple_interpreters:
459 /* handled in PyModule_FromDefAndSpec2 */
460 break;
461 default:
462 PyErr_Format(
463 PyExc_SystemError,
464 "module %s initialized with unknown slot %i",
465 name, cur_slot->slot);
466 return -1;
467 }
468 }
469 return 0;
470 }
471
472 int
473 PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
474 {
475 int res;
476 PyObject *name = PyModule_GetNameObject(m);
477 if (name == NULL) {
478 return -1;
479 }
480
481 res = _add_methods_to_object(m, name, functions);
482 Py_DECREF(name);
483 return res;
484 }
485
486 int
487 PyModule_SetDocString(PyObject *m, const char *doc)
488 {
489 PyObject *v;
490
491 v = PyUnicode_FromString(doc);
492 if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
493 Py_XDECREF(v);
494 return -1;
495 }
496 Py_DECREF(v);
497 return 0;
498 }
499
500 PyObject *
501 PyModule_GetDict(PyObject *m)
502 {
503 if (!PyModule_Check(m)) {
504 PyErr_BadInternalCall();
505 return NULL;
506 }
507 return _PyModule_GetDict(m);
508 }
509
510 PyObject*
511 PyModule_GetNameObject(PyObject *m)
512 {
513 PyObject *d;
514 PyObject *name;
515 if (!PyModule_Check(m)) {
516 PyErr_BadArgument();
517 return NULL;
518 }
519 d = ((PyModuleObject *)m)->md_dict;
520 if (d == NULL || !PyDict_Check(d) ||
521 (name = PyDict_GetItemWithError(d, &_Py_ID(__name__))) == NULL ||
522 !PyUnicode_Check(name))
523 {
524 if (!PyErr_Occurred()) {
525 PyErr_SetString(PyExc_SystemError, "nameless module");
526 }
527 return NULL;
528 }
529 return Py_NewRef(name);
530 }
531
532 const char *
533 PyModule_GetName(PyObject *m)
534 {
535 PyObject *name = PyModule_GetNameObject(m);
536 if (name == NULL) {
537 return NULL;
538 }
539 assert(Py_REFCNT(name) >= 2);
540 Py_DECREF(name); /* module dict has still a reference */
541 return PyUnicode_AsUTF8(name);
542 }
543
544 PyObject*
545 PyModule_GetFilenameObject(PyObject *m)
546 {
547 PyObject *d;
548 PyObject *fileobj;
549 if (!PyModule_Check(m)) {
550 PyErr_BadArgument();
551 return NULL;
552 }
553 d = ((PyModuleObject *)m)->md_dict;
554 if (d == NULL ||
555 (fileobj = PyDict_GetItemWithError(d, &_Py_ID(__file__))) == NULL ||
556 !PyUnicode_Check(fileobj))
557 {
558 if (!PyErr_Occurred()) {
559 PyErr_SetString(PyExc_SystemError, "module filename missing");
560 }
561 return NULL;
562 }
563 return Py_NewRef(fileobj);
564 }
565
566 const char *
567 PyModule_GetFilename(PyObject *m)
568 {
569 PyObject *fileobj;
570 const char *utf8;
571 fileobj = PyModule_GetFilenameObject(m);
572 if (fileobj == NULL)
573 return NULL;
574 utf8 = PyUnicode_AsUTF8(fileobj);
575 Py_DECREF(fileobj); /* module dict has still a reference */
576 return utf8;
577 }
578
579 PyModuleDef*
580 PyModule_GetDef(PyObject* m)
581 {
582 if (!PyModule_Check(m)) {
583 PyErr_BadArgument();
584 return NULL;
585 }
586 return _PyModule_GetDef(m);
587 }
588
589 void*
590 PyModule_GetState(PyObject* m)
591 {
592 if (!PyModule_Check(m)) {
593 PyErr_BadArgument();
594 return NULL;
595 }
596 return _PyModule_GetState(m);
597 }
598
599 void
600 _PyModule_Clear(PyObject *m)
601 {
602 PyObject *d = ((PyModuleObject *)m)->md_dict;
603 if (d != NULL)
604 _PyModule_ClearDict(d);
605 }
606
607 void
608 _PyModule_ClearDict(PyObject *d)
609 {
610 /* To make the execution order of destructors for global
611 objects a bit more predictable, we first zap all objects
612 whose name starts with a single underscore, before we clear
613 the entire dictionary. We zap them by replacing them with
614 None, rather than deleting them from the dictionary, to
615 avoid rehashing the dictionary (to some extent). */
616
617 Py_ssize_t pos;
618 PyObject *key, *value;
619
620 int verbose = _Py_GetConfig()->verbose;
621
622 /* First, clear only names starting with a single underscore */
623 pos = 0;
624 while (PyDict_Next(d, &pos, &key, &value)) {
625 if (value != Py_None && PyUnicode_Check(key)) {
626 if (PyUnicode_READ_CHAR(key, 0) == '_' &&
627 PyUnicode_READ_CHAR(key, 1) != '_') {
628 if (verbose > 1) {
629 const char *s = PyUnicode_AsUTF8(key);
630 if (s != NULL)
631 PySys_WriteStderr("# clear[1] %s\n", s);
632 else
633 PyErr_Clear();
634 }
635 if (PyDict_SetItem(d, key, Py_None) != 0) {
636 PyErr_WriteUnraisable(NULL);
637 }
638 }
639 }
640 }
641
642 /* Next, clear all names except for __builtins__ */
643 pos = 0;
644 while (PyDict_Next(d, &pos, &key, &value)) {
645 if (value != Py_None && PyUnicode_Check(key)) {
646 if (PyUnicode_READ_CHAR(key, 0) != '_' ||
647 !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
648 {
649 if (verbose > 1) {
650 const char *s = PyUnicode_AsUTF8(key);
651 if (s != NULL)
652 PySys_WriteStderr("# clear[2] %s\n", s);
653 else
654 PyErr_Clear();
655 }
656 if (PyDict_SetItem(d, key, Py_None) != 0) {
657 PyErr_WriteUnraisable(NULL);
658 }
659 }
660 }
661 }
662
663 /* Note: we leave __builtins__ in place, so that destructors
664 of non-global objects defined in this module can still use
665 builtins, in particularly 'None'. */
666
667 }
668
669 /*[clinic input]
670 class module "PyModuleObject *" "&PyModule_Type"
671 [clinic start generated code]*/
672 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
673
674 #include "clinic/moduleobject.c.h"
675
676 /* Methods */
677
678 /*[clinic input]
679 module.__init__
680 name: unicode
681 doc: object = None
682
683 Create a module object.
684
685 The name must be a string; the optional doc argument can have any type.
686 [clinic start generated code]*/
687
688 static int
689 module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
690 /*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
691 {
692 PyObject *dict = self->md_dict;
693 if (dict == NULL) {
694 dict = PyDict_New();
695 if (dict == NULL)
696 return -1;
697 self->md_dict = dict;
698 }
699 if (module_init_dict(self, dict, name, doc) < 0)
700 return -1;
701 return 0;
702 }
703
704 static void
705 module_dealloc(PyModuleObject *m)
706 {
707 int verbose = _Py_GetConfig()->verbose;
708
709 PyObject_GC_UnTrack(m);
710 if (verbose && m->md_name) {
711 PySys_FormatStderr("# destroy %U\n", m->md_name);
712 }
713 if (m->md_weaklist != NULL)
714 PyObject_ClearWeakRefs((PyObject *) m);
715 /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
716 if (m->md_def && m->md_def->m_free
717 && (m->md_def->m_size <= 0 || m->md_state != NULL))
718 {
719 m->md_def->m_free(m);
720 }
721 Py_XDECREF(m->md_dict);
722 Py_XDECREF(m->md_name);
723 if (m->md_state != NULL)
724 PyMem_Free(m->md_state);
725 Py_TYPE(m)->tp_free((PyObject *)m);
726 }
727
728 static PyObject *
729 module_repr(PyModuleObject *m)
730 {
731 PyInterpreterState *interp = _PyInterpreterState_GET();
732 return _PyImport_ImportlibModuleRepr(interp, (PyObject *)m);
733 }
734
735 /* Check if the "_initializing" attribute of the module spec is set to true.
736 Clear the exception and return 0 if spec is NULL.
737 */
738 int
739 _PyModuleSpec_IsInitializing(PyObject *spec)
740 {
741 if (spec != NULL) {
742 PyObject *value;
743 int ok = _PyObject_LookupAttr(spec, &_Py_ID(_initializing), &value);
744 if (ok == 0) {
745 return 0;
746 }
747 if (value != NULL) {
748 int initializing = PyObject_IsTrue(value);
749 Py_DECREF(value);
750 if (initializing >= 0) {
751 return initializing;
752 }
753 }
754 }
755 PyErr_Clear();
756 return 0;
757 }
758
759 /* Check if the submodule name is in the "_uninitialized_submodules" attribute
760 of the module spec.
761 */
762 int
763 _PyModuleSpec_IsUninitializedSubmodule(PyObject *spec, PyObject *name)
764 {
765 if (spec == NULL) {
766 return 0;
767 }
768
769 PyObject *value = PyObject_GetAttr(spec, &_Py_ID(_uninitialized_submodules));
770 if (value == NULL) {
771 return 0;
772 }
773
774 int is_uninitialized = PySequence_Contains(value, name);
775 Py_DECREF(value);
776 if (is_uninitialized == -1) {
777 return 0;
778 }
779 return is_uninitialized;
780 }
781
782 PyObject*
783 _Py_module_getattro_impl(PyModuleObject *m, PyObject *name, int suppress)
784 {
785 // When suppress=1, this function suppresses AttributeError.
786 PyObject *attr, *mod_name, *getattr;
787 attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
788 if (attr) {
789 return attr;
790 }
791 if (suppress == 1) {
792 if (PyErr_Occurred()) {
793 // pass up non-AttributeError exception
794 return NULL;
795 }
796 }
797 else {
798 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
799 // pass up non-AttributeError exception
800 return NULL;
801 }
802 PyErr_Clear();
803 }
804 assert(m->md_dict != NULL);
805 getattr = PyDict_GetItemWithError(m->md_dict, &_Py_ID(__getattr__));
806 if (getattr) {
807 PyObject *result = PyObject_CallOneArg(getattr, name);
808 if (result == NULL && suppress == 1 && PyErr_ExceptionMatches(PyExc_AttributeError)) {
809 // suppress AttributeError
810 PyErr_Clear();
811 }
812 return result;
813 }
814 if (PyErr_Occurred()) {
815 return NULL;
816 }
817 mod_name = PyDict_GetItemWithError(m->md_dict, &_Py_ID(__name__));
818 if (mod_name && PyUnicode_Check(mod_name)) {
819 Py_INCREF(mod_name);
820 PyObject *spec = PyDict_GetItemWithError(m->md_dict, &_Py_ID(__spec__));
821 if (spec == NULL && PyErr_Occurred()) {
822 Py_DECREF(mod_name);
823 return NULL;
824 }
825 if (suppress != 1) {
826 Py_XINCREF(spec);
827 if (_PyModuleSpec_IsInitializing(spec)) {
828 PyErr_Format(PyExc_AttributeError,
829 "partially initialized "
830 "module '%U' has no attribute '%U' "
831 "(most likely due to a circular import)",
832 mod_name, name);
833 }
834 else if (_PyModuleSpec_IsUninitializedSubmodule(spec, name)) {
835 PyErr_Format(PyExc_AttributeError,
836 "cannot access submodule '%U' of module '%U' "
837 "(most likely due to a circular import)",
838 name, mod_name);
839 }
840 else {
841 PyErr_Format(PyExc_AttributeError,
842 "module '%U' has no attribute '%U'",
843 mod_name, name);
844 }
845 Py_XDECREF(spec);
846 }
847 Py_DECREF(mod_name);
848 return NULL;
849 }
850 else if (PyErr_Occurred()) {
851 return NULL;
852 }
853 if (suppress != 1) {
854 PyErr_Format(PyExc_AttributeError,
855 "module has no attribute '%U'", name);
856 }
857 return NULL;
858 }
859
860
861 PyObject*
862 _Py_module_getattro(PyModuleObject *m, PyObject *name)
863 {
864 return _Py_module_getattro_impl(m, name, 0);
865 }
866
867 static int
868 module_traverse(PyModuleObject *m, visitproc visit, void *arg)
869 {
870 /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
871 if (m->md_def && m->md_def->m_traverse
872 && (m->md_def->m_size <= 0 || m->md_state != NULL))
873 {
874 int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
875 if (res)
876 return res;
877 }
878 Py_VISIT(m->md_dict);
879 return 0;
880 }
881
882 static int
883 module_clear(PyModuleObject *m)
884 {
885 /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
886 if (m->md_def && m->md_def->m_clear
887 && (m->md_def->m_size <= 0 || m->md_state != NULL))
888 {
889 int res = m->md_def->m_clear((PyObject*)m);
890 if (PyErr_Occurred()) {
891 PySys_FormatStderr("Exception ignored in m_clear of module%s%V\n",
892 m->md_name ? " " : "",
893 m->md_name, "");
894 PyErr_WriteUnraisable(NULL);
895 }
896 if (res)
897 return res;
898 }
899 Py_CLEAR(m->md_dict);
900 return 0;
901 }
902
903 static PyObject *
904 module_dir(PyObject *self, PyObject *args)
905 {
906 PyObject *result = NULL;
907 PyObject *dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
908
909 if (dict != NULL) {
910 if (PyDict_Check(dict)) {
911 PyObject *dirfunc = PyDict_GetItemWithError(dict, &_Py_ID(__dir__));
912 if (dirfunc) {
913 result = _PyObject_CallNoArgs(dirfunc);
914 }
915 else if (!PyErr_Occurred()) {
916 result = PyDict_Keys(dict);
917 }
918 }
919 else {
920 PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
921 }
922 }
923
924 Py_XDECREF(dict);
925 return result;
926 }
927
928 static PyMethodDef module_methods[] = {
929 {"__dir__", module_dir, METH_NOARGS,
930 PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
931 {0}
932 };
933
934 static PyObject *
935 module_get_annotations(PyModuleObject *m, void *Py_UNUSED(ignored))
936 {
937 PyObject *dict = PyObject_GetAttr((PyObject *)m, &_Py_ID(__dict__));
938 if (dict == NULL) {
939 return NULL;
940 }
941 if (!PyDict_Check(dict)) {
942 PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
943 Py_DECREF(dict);
944 return NULL;
945 }
946
947 PyObject *annotations = PyDict_GetItemWithError(dict, &_Py_ID(__annotations__));
948 if (annotations) {
949 Py_INCREF(annotations);
950 }
951 else if (!PyErr_Occurred()) {
952 annotations = PyDict_New();
953 if (annotations) {
954 int result = PyDict_SetItem(
955 dict, &_Py_ID(__annotations__), annotations);
956 if (result) {
957 Py_CLEAR(annotations);
958 }
959 }
960 }
961 Py_DECREF(dict);
962 return annotations;
963 }
964
965 static int
966 module_set_annotations(PyModuleObject *m, PyObject *value, void *Py_UNUSED(ignored))
967 {
968 int ret = -1;
969 PyObject *dict = PyObject_GetAttr((PyObject *)m, &_Py_ID(__dict__));
970 if (dict == NULL) {
971 return -1;
972 }
973 if (!PyDict_Check(dict)) {
974 PyErr_Format(PyExc_TypeError, "<module>.__dict__ is not a dictionary");
975 goto exit;
976 }
977
978 if (value != NULL) {
979 /* set */
980 ret = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
981 }
982 else {
983 /* delete */
984 ret = PyDict_DelItem(dict, &_Py_ID(__annotations__));
985 if (ret < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
986 PyErr_SetString(PyExc_AttributeError, "__annotations__");
987 }
988 }
989
990 exit:
991 Py_DECREF(dict);
992 return ret;
993 }
994
995
996 static PyGetSetDef module_getsets[] = {
997 {"__annotations__", (getter)module_get_annotations, (setter)module_set_annotations},
998 {NULL}
999 };
1000
1001 PyTypeObject PyModule_Type = {
1002 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1003 "module", /* tp_name */
1004 sizeof(PyModuleObject), /* tp_basicsize */
1005 0, /* tp_itemsize */
1006 (destructor)module_dealloc, /* tp_dealloc */
1007 0, /* tp_vectorcall_offset */
1008 0, /* tp_getattr */
1009 0, /* tp_setattr */
1010 0, /* tp_as_async */
1011 (reprfunc)module_repr, /* tp_repr */
1012 0, /* tp_as_number */
1013 0, /* tp_as_sequence */
1014 0, /* tp_as_mapping */
1015 0, /* tp_hash */
1016 0, /* tp_call */
1017 0, /* tp_str */
1018 (getattrofunc)_Py_module_getattro, /* tp_getattro */
1019 PyObject_GenericSetAttr, /* tp_setattro */
1020 0, /* tp_as_buffer */
1021 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1022 Py_TPFLAGS_BASETYPE, /* tp_flags */
1023 module___init____doc__, /* tp_doc */
1024 (traverseproc)module_traverse, /* tp_traverse */
1025 (inquiry)module_clear, /* tp_clear */
1026 0, /* tp_richcompare */
1027 offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
1028 0, /* tp_iter */
1029 0, /* tp_iternext */
1030 module_methods, /* tp_methods */
1031 module_members, /* tp_members */
1032 module_getsets, /* tp_getset */
1033 0, /* tp_base */
1034 0, /* tp_dict */
1035 0, /* tp_descr_get */
1036 0, /* tp_descr_set */
1037 offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
1038 module___init__, /* tp_init */
1039 0, /* tp_alloc */
1040 new_module, /* tp_new */
1041 PyObject_GC_Del, /* tp_free */
1042 };