You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

883 lines
25 KiB

36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
  1. /* Module object implementation */
  2. #include "Python.h"
  3. #include "pycore_interp.h" // PyInterpreterState.importlib
  4. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  5. #include "structmember.h" // PyMemberDef
  6. static Py_ssize_t max_module_number;
  7. _Py_IDENTIFIER(__doc__);
  8. _Py_IDENTIFIER(__name__);
  9. _Py_IDENTIFIER(__spec__);
  10. typedef struct {
  11. PyObject_HEAD
  12. PyObject *md_dict;
  13. struct PyModuleDef *md_def;
  14. void *md_state;
  15. PyObject *md_weaklist;
  16. PyObject *md_name; /* for logging purposes after md_dict is cleared */
  17. } PyModuleObject;
  18. static PyMemberDef module_members[] = {
  19. {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
  20. {0}
  21. };
  22. PyTypeObject PyModuleDef_Type = {
  23. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  24. "moduledef", /* tp_name */
  25. sizeof(struct PyModuleDef), /* tp_basicsize */
  26. 0, /* tp_itemsize */
  27. };
  28. PyObject*
  29. PyModuleDef_Init(struct PyModuleDef* def)
  30. {
  31. if (PyType_Ready(&PyModuleDef_Type) < 0)
  32. return NULL;
  33. if (def->m_base.m_index == 0) {
  34. max_module_number++;
  35. Py_SET_REFCNT(def, 1);
  36. Py_SET_TYPE(def, &PyModuleDef_Type);
  37. def->m_base.m_index = max_module_number;
  38. }
  39. return (PyObject*)def;
  40. }
  41. static int
  42. module_init_dict(PyModuleObject *mod, PyObject *md_dict,
  43. PyObject *name, PyObject *doc)
  44. {
  45. _Py_IDENTIFIER(__package__);
  46. _Py_IDENTIFIER(__loader__);
  47. if (md_dict == NULL)
  48. return -1;
  49. if (doc == NULL)
  50. doc = Py_None;
  51. if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0)
  52. return -1;
  53. if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0)
  54. return -1;
  55. if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0)
  56. return -1;
  57. if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0)
  58. return -1;
  59. if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0)
  60. return -1;
  61. if (PyUnicode_CheckExact(name)) {
  62. Py_INCREF(name);
  63. Py_XSETREF(mod->md_name, name);
  64. }
  65. return 0;
  66. }
  67. PyObject *
  68. PyModule_NewObject(PyObject *name)
  69. {
  70. PyModuleObject *m;
  71. m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
  72. if (m == NULL)
  73. return NULL;
  74. m->md_def = NULL;
  75. m->md_state = NULL;
  76. m->md_weaklist = NULL;
  77. m->md_name = NULL;
  78. m->md_dict = PyDict_New();
  79. if (module_init_dict(m, m->md_dict, name, NULL) != 0)
  80. goto fail;
  81. PyObject_GC_Track(m);
  82. return (PyObject *)m;
  83. fail:
  84. Py_DECREF(m);
  85. return NULL;
  86. }
  87. PyObject *
  88. PyModule_New(const char *name)
  89. {
  90. PyObject *nameobj, *module;
  91. nameobj = PyUnicode_FromString(name);
  92. if (nameobj == NULL)
  93. return NULL;
  94. module = PyModule_NewObject(nameobj);
  95. Py_DECREF(nameobj);
  96. return module;
  97. }
  98. /* Check API/ABI version
  99. * Issues a warning on mismatch, which is usually not fatal.
  100. * Returns 0 if an exception is raised.
  101. */
  102. static int
  103. check_api_version(const char *name, int module_api_version)
  104. {
  105. if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
  106. int err;
  107. err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  108. "Python C API version mismatch for module %.100s: "
  109. "This Python has API version %d, module %.100s has version %d.",
  110. name,
  111. PYTHON_API_VERSION, name, module_api_version);
  112. if (err)
  113. return 0;
  114. }
  115. return 1;
  116. }
  117. static int
  118. _add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
  119. {
  120. PyObject *func;
  121. PyMethodDef *fdef;
  122. for (fdef = functions; fdef->ml_name != NULL; fdef++) {
  123. if ((fdef->ml_flags & METH_CLASS) ||
  124. (fdef->ml_flags & METH_STATIC)) {
  125. PyErr_SetString(PyExc_ValueError,
  126. "module functions cannot set"
  127. " METH_CLASS or METH_STATIC");
  128. return -1;
  129. }
  130. func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
  131. if (func == NULL) {
  132. return -1;
  133. }
  134. if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
  135. Py_DECREF(func);
  136. return -1;
  137. }
  138. Py_DECREF(func);
  139. }
  140. return 0;
  141. }
  142. PyObject *
  143. PyModule_Create2(struct PyModuleDef* module, int module_api_version)
  144. {
  145. if (!_PyImport_IsInitialized(_PyInterpreterState_GET())) {
  146. PyErr_SetString(PyExc_SystemError,
  147. "Python import machinery not initialized");
  148. return NULL;
  149. }
  150. return _PyModule_CreateInitialized(module, module_api_version);
  151. }
  152. PyObject *
  153. _PyModule_CreateInitialized(struct PyModuleDef* module, int module_api_version)
  154. {
  155. const char* name;
  156. PyModuleObject *m;
  157. if (!PyModuleDef_Init(module))
  158. return NULL;
  159. name = module->m_name;
  160. if (!check_api_version(name, module_api_version)) {
  161. return NULL;
  162. }
  163. if (module->m_slots) {
  164. PyErr_Format(
  165. PyExc_SystemError,
  166. "module %s: PyModule_Create is incompatible with m_slots", name);
  167. return NULL;
  168. }
  169. /* Make sure name is fully qualified.
  170. This is a bit of a hack: when the shared library is loaded,
  171. the module name is "package.module", but the module calls
  172. PyModule_Create*() with just "module" for the name. The shared
  173. library loader squirrels away the true name of the module in
  174. _Py_PackageContext, and PyModule_Create*() will substitute this
  175. (if the name actually matches).
  176. */
  177. if (_Py_PackageContext != NULL) {
  178. const char *p = strrchr(_Py_PackageContext, '.');
  179. if (p != NULL && strcmp(module->m_name, p+1) == 0) {
  180. name = _Py_PackageContext;
  181. _Py_PackageContext = NULL;
  182. }
  183. }
  184. if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
  185. return NULL;
  186. if (module->m_size > 0) {
  187. m->md_state = PyMem_Malloc(module->m_size);
  188. if (!m->md_state) {
  189. PyErr_NoMemory();
  190. Py_DECREF(m);
  191. return NULL;
  192. }
  193. memset(m->md_state, 0, module->m_size);
  194. }
  195. if (module->m_methods != NULL) {
  196. if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
  197. Py_DECREF(m);
  198. return NULL;
  199. }
  200. }
  201. if (module->m_doc != NULL) {
  202. if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
  203. Py_DECREF(m);
  204. return NULL;
  205. }
  206. }
  207. m->md_def = module;
  208. return (PyObject*)m;
  209. }
  210. PyObject *
  211. PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version)
  212. {
  213. PyModuleDef_Slot* cur_slot;
  214. PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
  215. PyObject *nameobj;
  216. PyObject *m = NULL;
  217. int has_execution_slots = 0;
  218. const char *name;
  219. int ret;
  220. PyModuleDef_Init(def);
  221. nameobj = PyObject_GetAttrString(spec, "name");
  222. if (nameobj == NULL) {
  223. return NULL;
  224. }
  225. name = PyUnicode_AsUTF8(nameobj);
  226. if (name == NULL) {
  227. goto error;
  228. }
  229. if (!check_api_version(name, module_api_version)) {
  230. goto error;
  231. }
  232. if (def->m_size < 0) {
  233. PyErr_Format(
  234. PyExc_SystemError,
  235. "module %s: m_size may not be negative for multi-phase initialization",
  236. name);
  237. goto error;
  238. }
  239. for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
  240. if (cur_slot->slot == Py_mod_create) {
  241. if (create) {
  242. PyErr_Format(
  243. PyExc_SystemError,
  244. "module %s has multiple create slots",
  245. name);
  246. goto error;
  247. }
  248. create = cur_slot->value;
  249. } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) {
  250. PyErr_Format(
  251. PyExc_SystemError,
  252. "module %s uses unknown slot ID %i",
  253. name, cur_slot->slot);
  254. goto error;
  255. } else {
  256. has_execution_slots = 1;
  257. }
  258. }
  259. if (create) {
  260. m = create(spec, def);
  261. if (m == NULL) {
  262. if (!PyErr_Occurred()) {
  263. PyErr_Format(
  264. PyExc_SystemError,
  265. "creation of module %s failed without setting an exception",
  266. name);
  267. }
  268. goto error;
  269. } else {
  270. if (PyErr_Occurred()) {
  271. PyErr_Format(PyExc_SystemError,
  272. "creation of module %s raised unreported exception",
  273. name);
  274. goto error;
  275. }
  276. }
  277. } else {
  278. m = PyModule_NewObject(nameobj);
  279. if (m == NULL) {
  280. goto error;
  281. }
  282. }
  283. if (PyModule_Check(m)) {
  284. ((PyModuleObject*)m)->md_state = NULL;
  285. ((PyModuleObject*)m)->md_def = def;
  286. } else {
  287. if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
  288. PyErr_Format(
  289. PyExc_SystemError,
  290. "module %s is not a module object, but requests module state",
  291. name);
  292. goto error;
  293. }
  294. if (has_execution_slots) {
  295. PyErr_Format(
  296. PyExc_SystemError,
  297. "module %s specifies execution slots, but did not create "
  298. "a ModuleType instance",
  299. name);
  300. goto error;
  301. }
  302. }
  303. if (def->m_methods != NULL) {
  304. ret = _add_methods_to_object(m, nameobj, def->m_methods);
  305. if (ret != 0) {
  306. goto error;
  307. }
  308. }
  309. if (def->m_doc != NULL) {
  310. ret = PyModule_SetDocString(m, def->m_doc);
  311. if (ret != 0) {
  312. goto error;
  313. }
  314. }
  315. Py_DECREF(nameobj);
  316. return m;
  317. error:
  318. Py_DECREF(nameobj);
  319. Py_XDECREF(m);
  320. return NULL;
  321. }
  322. int
  323. PyModule_ExecDef(PyObject *module, PyModuleDef *def)
  324. {
  325. PyModuleDef_Slot *cur_slot;
  326. const char *name;
  327. int ret;
  328. name = PyModule_GetName(module);
  329. if (name == NULL) {
  330. return -1;
  331. }
  332. if (def->m_size >= 0) {
  333. PyModuleObject *md = (PyModuleObject*)module;
  334. if (md->md_state == NULL) {
  335. /* Always set a state pointer; this serves as a marker to skip
  336. * multiple initialization (importlib.reload() is no-op) */
  337. md->md_state = PyMem_Malloc(def->m_size);
  338. if (!md->md_state) {
  339. PyErr_NoMemory();
  340. return -1;
  341. }
  342. memset(md->md_state, 0, def->m_size);
  343. }
  344. }
  345. if (def->m_slots == NULL) {
  346. return 0;
  347. }
  348. for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
  349. switch (cur_slot->slot) {
  350. case Py_mod_create:
  351. /* handled in PyModule_FromDefAndSpec2 */
  352. break;
  353. case Py_mod_exec:
  354. ret = ((int (*)(PyObject *))cur_slot->value)(module);
  355. if (ret != 0) {
  356. if (!PyErr_Occurred()) {
  357. PyErr_Format(
  358. PyExc_SystemError,
  359. "execution of module %s failed without setting an exception",
  360. name);
  361. }
  362. return -1;
  363. }
  364. if (PyErr_Occurred()) {
  365. PyErr_Format(
  366. PyExc_SystemError,
  367. "execution of module %s raised unreported exception",
  368. name);
  369. return -1;
  370. }
  371. break;
  372. default:
  373. PyErr_Format(
  374. PyExc_SystemError,
  375. "module %s initialized with unknown slot %i",
  376. name, cur_slot->slot);
  377. return -1;
  378. }
  379. }
  380. return 0;
  381. }
  382. int
  383. PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
  384. {
  385. int res;
  386. PyObject *name = PyModule_GetNameObject(m);
  387. if (name == NULL) {
  388. return -1;
  389. }
  390. res = _add_methods_to_object(m, name, functions);
  391. Py_DECREF(name);
  392. return res;
  393. }
  394. int
  395. PyModule_SetDocString(PyObject *m, const char *doc)
  396. {
  397. PyObject *v;
  398. v = PyUnicode_FromString(doc);
  399. if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) {
  400. Py_XDECREF(v);
  401. return -1;
  402. }
  403. Py_DECREF(v);
  404. return 0;
  405. }
  406. PyObject *
  407. PyModule_GetDict(PyObject *m)
  408. {
  409. PyObject *d;
  410. if (!PyModule_Check(m)) {
  411. PyErr_BadInternalCall();
  412. return NULL;
  413. }
  414. d = ((PyModuleObject *)m) -> md_dict;
  415. assert(d != NULL);
  416. return d;
  417. }
  418. PyObject*
  419. PyModule_GetNameObject(PyObject *m)
  420. {
  421. PyObject *d;
  422. PyObject *name;
  423. if (!PyModule_Check(m)) {
  424. PyErr_BadArgument();
  425. return NULL;
  426. }
  427. d = ((PyModuleObject *)m)->md_dict;
  428. if (d == NULL ||
  429. (name = _PyDict_GetItemIdWithError(d, &PyId___name__)) == NULL ||
  430. !PyUnicode_Check(name))
  431. {
  432. if (!PyErr_Occurred()) {
  433. PyErr_SetString(PyExc_SystemError, "nameless module");
  434. }
  435. return NULL;
  436. }
  437. Py_INCREF(name);
  438. return name;
  439. }
  440. const char *
  441. PyModule_GetName(PyObject *m)
  442. {
  443. PyObject *name = PyModule_GetNameObject(m);
  444. if (name == NULL)
  445. return NULL;
  446. Py_DECREF(name); /* module dict has still a reference */
  447. return PyUnicode_AsUTF8(name);
  448. }
  449. PyObject*
  450. PyModule_GetFilenameObject(PyObject *m)
  451. {
  452. _Py_IDENTIFIER(__file__);
  453. PyObject *d;
  454. PyObject *fileobj;
  455. if (!PyModule_Check(m)) {
  456. PyErr_BadArgument();
  457. return NULL;
  458. }
  459. d = ((PyModuleObject *)m)->md_dict;
  460. if (d == NULL ||
  461. (fileobj = _PyDict_GetItemIdWithError(d, &PyId___file__)) == NULL ||
  462. !PyUnicode_Check(fileobj))
  463. {
  464. if (!PyErr_Occurred()) {
  465. PyErr_SetString(PyExc_SystemError, "module filename missing");
  466. }
  467. return NULL;
  468. }
  469. Py_INCREF(fileobj);
  470. return fileobj;
  471. }
  472. const char *
  473. PyModule_GetFilename(PyObject *m)
  474. {
  475. PyObject *fileobj;
  476. const char *utf8;
  477. fileobj = PyModule_GetFilenameObject(m);
  478. if (fileobj == NULL)
  479. return NULL;
  480. utf8 = PyUnicode_AsUTF8(fileobj);
  481. Py_DECREF(fileobj); /* module dict has still a reference */
  482. return utf8;
  483. }
  484. PyModuleDef*
  485. PyModule_GetDef(PyObject* m)
  486. {
  487. if (!PyModule_Check(m)) {
  488. PyErr_BadArgument();
  489. return NULL;
  490. }
  491. return ((PyModuleObject *)m)->md_def;
  492. }
  493. void*
  494. PyModule_GetState(PyObject* m)
  495. {
  496. if (!PyModule_Check(m)) {
  497. PyErr_BadArgument();
  498. return NULL;
  499. }
  500. return ((PyModuleObject *)m)->md_state;
  501. }
  502. void
  503. _PyModule_Clear(PyObject *m)
  504. {
  505. PyObject *d = ((PyModuleObject *)m)->md_dict;
  506. if (d != NULL)
  507. _PyModule_ClearDict(d);
  508. }
  509. void
  510. _PyModule_ClearDict(PyObject *d)
  511. {
  512. /* To make the execution order of destructors for global
  513. objects a bit more predictable, we first zap all objects
  514. whose name starts with a single underscore, before we clear
  515. the entire dictionary. We zap them by replacing them with
  516. None, rather than deleting them from the dictionary, to
  517. avoid rehashing the dictionary (to some extent). */
  518. Py_ssize_t pos;
  519. PyObject *key, *value;
  520. int verbose = _Py_GetConfig()->verbose;
  521. /* First, clear only names starting with a single underscore */
  522. pos = 0;
  523. while (PyDict_Next(d, &pos, &key, &value)) {
  524. if (value != Py_None && PyUnicode_Check(key)) {
  525. if (PyUnicode_READ_CHAR(key, 0) == '_' &&
  526. PyUnicode_READ_CHAR(key, 1) != '_') {
  527. if (verbose > 1) {
  528. const char *s = PyUnicode_AsUTF8(key);
  529. if (s != NULL)
  530. PySys_WriteStderr("# clear[1] %s\n", s);
  531. else
  532. PyErr_Clear();
  533. }
  534. if (PyDict_SetItem(d, key, Py_None) != 0) {
  535. PyErr_WriteUnraisable(NULL);
  536. }
  537. }
  538. }
  539. }
  540. /* Next, clear all names except for __builtins__ */
  541. pos = 0;
  542. while (PyDict_Next(d, &pos, &key, &value)) {
  543. if (value != Py_None && PyUnicode_Check(key)) {
  544. if (PyUnicode_READ_CHAR(key, 0) != '_' ||
  545. !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
  546. {
  547. if (verbose > 1) {
  548. const char *s = PyUnicode_AsUTF8(key);
  549. if (s != NULL)
  550. PySys_WriteStderr("# clear[2] %s\n", s);
  551. else
  552. PyErr_Clear();
  553. }
  554. if (PyDict_SetItem(d, key, Py_None) != 0) {
  555. PyErr_WriteUnraisable(NULL);
  556. }
  557. }
  558. }
  559. }
  560. /* Note: we leave __builtins__ in place, so that destructors
  561. of non-global objects defined in this module can still use
  562. builtins, in particularly 'None'. */
  563. }
  564. /*[clinic input]
  565. class module "PyModuleObject *" "&PyModule_Type"
  566. [clinic start generated code]*/
  567. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
  568. #include "clinic/moduleobject.c.h"
  569. /* Methods */
  570. /*[clinic input]
  571. module.__init__
  572. name: unicode
  573. doc: object = None
  574. Create a module object.
  575. The name must be a string; the optional doc argument can have any type.
  576. [clinic start generated code]*/
  577. static int
  578. module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
  579. /*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
  580. {
  581. PyObject *dict = self->md_dict;
  582. if (dict == NULL) {
  583. dict = PyDict_New();
  584. if (dict == NULL)
  585. return -1;
  586. self->md_dict = dict;
  587. }
  588. if (module_init_dict(self, dict, name, doc) < 0)
  589. return -1;
  590. return 0;
  591. }
  592. static void
  593. module_dealloc(PyModuleObject *m)
  594. {
  595. int verbose = _Py_GetConfig()->verbose;
  596. PyObject_GC_UnTrack(m);
  597. if (verbose && m->md_name) {
  598. PySys_FormatStderr("# destroy %U\n", m->md_name);
  599. }
  600. if (m->md_weaklist != NULL)
  601. PyObject_ClearWeakRefs((PyObject *) m);
  602. /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
  603. if (m->md_def && m->md_def->m_free
  604. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  605. {
  606. m->md_def->m_free(m);
  607. }
  608. Py_XDECREF(m->md_dict);
  609. Py_XDECREF(m->md_name);
  610. if (m->md_state != NULL)
  611. PyMem_Free(m->md_state);
  612. Py_TYPE(m)->tp_free((PyObject *)m);
  613. }
  614. static PyObject *
  615. module_repr(PyModuleObject *m)
  616. {
  617. PyInterpreterState *interp = _PyInterpreterState_GET();
  618. return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
  619. }
  620. /* Check if the "_initializing" attribute of the module spec is set to true.
  621. Clear the exception and return 0 if spec is NULL.
  622. */
  623. int
  624. _PyModuleSpec_IsInitializing(PyObject *spec)
  625. {
  626. if (spec != NULL) {
  627. _Py_IDENTIFIER(_initializing);
  628. PyObject *value = _PyObject_GetAttrId(spec, &PyId__initializing);
  629. if (value != NULL) {
  630. int initializing = PyObject_IsTrue(value);
  631. Py_DECREF(value);
  632. if (initializing >= 0) {
  633. return initializing;
  634. }
  635. }
  636. }
  637. PyErr_Clear();
  638. return 0;
  639. }
  640. static PyObject*
  641. module_getattro(PyModuleObject *m, PyObject *name)
  642. {
  643. PyObject *attr, *mod_name, *getattr;
  644. attr = PyObject_GenericGetAttr((PyObject *)m, name);
  645. if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError)) {
  646. return attr;
  647. }
  648. PyErr_Clear();
  649. if (m->md_dict) {
  650. _Py_IDENTIFIER(__getattr__);
  651. getattr = _PyDict_GetItemIdWithError(m->md_dict, &PyId___getattr__);
  652. if (getattr) {
  653. return PyObject_CallOneArg(getattr, name);
  654. }
  655. if (PyErr_Occurred()) {
  656. return NULL;
  657. }
  658. mod_name = _PyDict_GetItemIdWithError(m->md_dict, &PyId___name__);
  659. if (mod_name && PyUnicode_Check(mod_name)) {
  660. Py_INCREF(mod_name);
  661. PyObject *spec = _PyDict_GetItemIdWithError(m->md_dict, &PyId___spec__);
  662. if (spec == NULL && PyErr_Occurred()) {
  663. Py_DECREF(mod_name);
  664. return NULL;
  665. }
  666. Py_XINCREF(spec);
  667. if (_PyModuleSpec_IsInitializing(spec)) {
  668. PyErr_Format(PyExc_AttributeError,
  669. "partially initialized "
  670. "module '%U' has no attribute '%U' "
  671. "(most likely due to a circular import)",
  672. mod_name, name);
  673. }
  674. else {
  675. PyErr_Format(PyExc_AttributeError,
  676. "module '%U' has no attribute '%U'",
  677. mod_name, name);
  678. }
  679. Py_XDECREF(spec);
  680. Py_DECREF(mod_name);
  681. return NULL;
  682. }
  683. else if (PyErr_Occurred()) {
  684. return NULL;
  685. }
  686. }
  687. PyErr_Format(PyExc_AttributeError,
  688. "module has no attribute '%U'", name);
  689. return NULL;
  690. }
  691. static int
  692. module_traverse(PyModuleObject *m, visitproc visit, void *arg)
  693. {
  694. /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
  695. if (m->md_def && m->md_def->m_traverse
  696. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  697. {
  698. int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
  699. if (res)
  700. return res;
  701. }
  702. Py_VISIT(m->md_dict);
  703. return 0;
  704. }
  705. static int
  706. module_clear(PyModuleObject *m)
  707. {
  708. /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
  709. if (m->md_def && m->md_def->m_clear
  710. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  711. {
  712. int res = m->md_def->m_clear((PyObject*)m);
  713. if (PyErr_Occurred()) {
  714. PySys_FormatStderr("Exception ignored in m_clear of module%s%V\n",
  715. m->md_name ? " " : "",
  716. m->md_name, "");
  717. PyErr_WriteUnraisable(NULL);
  718. }
  719. if (res)
  720. return res;
  721. }
  722. Py_CLEAR(m->md_dict);
  723. return 0;
  724. }
  725. static PyObject *
  726. module_dir(PyObject *self, PyObject *args)
  727. {
  728. _Py_IDENTIFIER(__dict__);
  729. _Py_IDENTIFIER(__dir__);
  730. PyObject *result = NULL;
  731. PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
  732. if (dict != NULL) {
  733. if (PyDict_Check(dict)) {
  734. PyObject *dirfunc = _PyDict_GetItemIdWithError(dict, &PyId___dir__);
  735. if (dirfunc) {
  736. result = _PyObject_CallNoArg(dirfunc);
  737. }
  738. else if (!PyErr_Occurred()) {
  739. result = PyDict_Keys(dict);
  740. }
  741. }
  742. else {
  743. const char *name = PyModule_GetName(self);
  744. if (name)
  745. PyErr_Format(PyExc_TypeError,
  746. "%.200s.__dict__ is not a dictionary",
  747. name);
  748. }
  749. }
  750. Py_XDECREF(dict);
  751. return result;
  752. }
  753. static PyMethodDef module_methods[] = {
  754. {"__dir__", module_dir, METH_NOARGS,
  755. PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
  756. {0}
  757. };
  758. PyTypeObject PyModule_Type = {
  759. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  760. "module", /* tp_name */
  761. sizeof(PyModuleObject), /* tp_basicsize */
  762. 0, /* tp_itemsize */
  763. (destructor)module_dealloc, /* tp_dealloc */
  764. 0, /* tp_vectorcall_offset */
  765. 0, /* tp_getattr */
  766. 0, /* tp_setattr */
  767. 0, /* tp_as_async */
  768. (reprfunc)module_repr, /* tp_repr */
  769. 0, /* tp_as_number */
  770. 0, /* tp_as_sequence */
  771. 0, /* tp_as_mapping */
  772. 0, /* tp_hash */
  773. 0, /* tp_call */
  774. 0, /* tp_str */
  775. (getattrofunc)module_getattro, /* tp_getattro */
  776. PyObject_GenericSetAttr, /* tp_setattro */
  777. 0, /* tp_as_buffer */
  778. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  779. Py_TPFLAGS_BASETYPE, /* tp_flags */
  780. module___init____doc__, /* tp_doc */
  781. (traverseproc)module_traverse, /* tp_traverse */
  782. (inquiry)module_clear, /* tp_clear */
  783. 0, /* tp_richcompare */
  784. offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
  785. 0, /* tp_iter */
  786. 0, /* tp_iternext */
  787. module_methods, /* tp_methods */
  788. module_members, /* tp_members */
  789. 0, /* tp_getset */
  790. 0, /* tp_base */
  791. 0, /* tp_dict */
  792. 0, /* tp_descr_get */
  793. 0, /* tp_descr_set */
  794. offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
  795. module___init__, /* tp_init */
  796. PyType_GenericAlloc, /* tp_alloc */
  797. PyType_GenericNew, /* tp_new */
  798. PyObject_GC_Del, /* tp_free */
  799. };