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.

869 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_GetItemId(d, &PyId___name__)) == NULL ||
  430. !PyUnicode_Check(name))
  431. {
  432. PyErr_SetString(PyExc_SystemError, "nameless module");
  433. return NULL;
  434. }
  435. Py_INCREF(name);
  436. return name;
  437. }
  438. const char *
  439. PyModule_GetName(PyObject *m)
  440. {
  441. PyObject *name = PyModule_GetNameObject(m);
  442. if (name == NULL)
  443. return NULL;
  444. Py_DECREF(name); /* module dict has still a reference */
  445. return PyUnicode_AsUTF8(name);
  446. }
  447. PyObject*
  448. PyModule_GetFilenameObject(PyObject *m)
  449. {
  450. _Py_IDENTIFIER(__file__);
  451. PyObject *d;
  452. PyObject *fileobj;
  453. if (!PyModule_Check(m)) {
  454. PyErr_BadArgument();
  455. return NULL;
  456. }
  457. d = ((PyModuleObject *)m)->md_dict;
  458. if (d == NULL ||
  459. (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL ||
  460. !PyUnicode_Check(fileobj))
  461. {
  462. PyErr_SetString(PyExc_SystemError, "module filename missing");
  463. return NULL;
  464. }
  465. Py_INCREF(fileobj);
  466. return fileobj;
  467. }
  468. const char *
  469. PyModule_GetFilename(PyObject *m)
  470. {
  471. PyObject *fileobj;
  472. const char *utf8;
  473. fileobj = PyModule_GetFilenameObject(m);
  474. if (fileobj == NULL)
  475. return NULL;
  476. utf8 = PyUnicode_AsUTF8(fileobj);
  477. Py_DECREF(fileobj); /* module dict has still a reference */
  478. return utf8;
  479. }
  480. PyModuleDef*
  481. PyModule_GetDef(PyObject* m)
  482. {
  483. if (!PyModule_Check(m)) {
  484. PyErr_BadArgument();
  485. return NULL;
  486. }
  487. return ((PyModuleObject *)m)->md_def;
  488. }
  489. void*
  490. PyModule_GetState(PyObject* m)
  491. {
  492. if (!PyModule_Check(m)) {
  493. PyErr_BadArgument();
  494. return NULL;
  495. }
  496. return ((PyModuleObject *)m)->md_state;
  497. }
  498. void
  499. _PyModule_Clear(PyObject *m)
  500. {
  501. PyObject *d = ((PyModuleObject *)m)->md_dict;
  502. if (d != NULL)
  503. _PyModule_ClearDict(d);
  504. }
  505. void
  506. _PyModule_ClearDict(PyObject *d)
  507. {
  508. /* To make the execution order of destructors for global
  509. objects a bit more predictable, we first zap all objects
  510. whose name starts with a single underscore, before we clear
  511. the entire dictionary. We zap them by replacing them with
  512. None, rather than deleting them from the dictionary, to
  513. avoid rehashing the dictionary (to some extent). */
  514. Py_ssize_t pos;
  515. PyObject *key, *value;
  516. int verbose = _Py_GetConfig()->verbose;
  517. /* First, clear only names starting with a single underscore */
  518. pos = 0;
  519. while (PyDict_Next(d, &pos, &key, &value)) {
  520. if (value != Py_None && PyUnicode_Check(key)) {
  521. if (PyUnicode_READ_CHAR(key, 0) == '_' &&
  522. PyUnicode_READ_CHAR(key, 1) != '_') {
  523. if (verbose > 1) {
  524. const char *s = PyUnicode_AsUTF8(key);
  525. if (s != NULL)
  526. PySys_WriteStderr("# clear[1] %s\n", s);
  527. else
  528. PyErr_Clear();
  529. }
  530. if (PyDict_SetItem(d, key, Py_None) != 0) {
  531. PyErr_WriteUnraisable(NULL);
  532. }
  533. }
  534. }
  535. }
  536. /* Next, clear all names except for __builtins__ */
  537. pos = 0;
  538. while (PyDict_Next(d, &pos, &key, &value)) {
  539. if (value != Py_None && PyUnicode_Check(key)) {
  540. if (PyUnicode_READ_CHAR(key, 0) != '_' ||
  541. !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
  542. {
  543. if (verbose > 1) {
  544. const char *s = PyUnicode_AsUTF8(key);
  545. if (s != NULL)
  546. PySys_WriteStderr("# clear[2] %s\n", s);
  547. else
  548. PyErr_Clear();
  549. }
  550. if (PyDict_SetItem(d, key, Py_None) != 0) {
  551. PyErr_WriteUnraisable(NULL);
  552. }
  553. }
  554. }
  555. }
  556. /* Note: we leave __builtins__ in place, so that destructors
  557. of non-global objects defined in this module can still use
  558. builtins, in particularly 'None'. */
  559. }
  560. /*[clinic input]
  561. class module "PyModuleObject *" "&PyModule_Type"
  562. [clinic start generated code]*/
  563. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
  564. #include "clinic/moduleobject.c.h"
  565. /* Methods */
  566. /*[clinic input]
  567. module.__init__
  568. name: unicode
  569. doc: object = None
  570. Create a module object.
  571. The name must be a string; the optional doc argument can have any type.
  572. [clinic start generated code]*/
  573. static int
  574. module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
  575. /*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
  576. {
  577. PyObject *dict = self->md_dict;
  578. if (dict == NULL) {
  579. dict = PyDict_New();
  580. if (dict == NULL)
  581. return -1;
  582. self->md_dict = dict;
  583. }
  584. if (module_init_dict(self, dict, name, doc) < 0)
  585. return -1;
  586. return 0;
  587. }
  588. static void
  589. module_dealloc(PyModuleObject *m)
  590. {
  591. int verbose = _Py_GetConfig()->verbose;
  592. PyObject_GC_UnTrack(m);
  593. if (verbose && m->md_name) {
  594. PySys_FormatStderr("# destroy %U\n", m->md_name);
  595. }
  596. if (m->md_weaklist != NULL)
  597. PyObject_ClearWeakRefs((PyObject *) m);
  598. /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
  599. if (m->md_def && m->md_def->m_free
  600. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  601. {
  602. m->md_def->m_free(m);
  603. }
  604. Py_XDECREF(m->md_dict);
  605. Py_XDECREF(m->md_name);
  606. if (m->md_state != NULL)
  607. PyMem_FREE(m->md_state);
  608. Py_TYPE(m)->tp_free((PyObject *)m);
  609. }
  610. static PyObject *
  611. module_repr(PyModuleObject *m)
  612. {
  613. PyInterpreterState *interp = _PyInterpreterState_GET();
  614. return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
  615. }
  616. /* Check if the "_initializing" attribute of the module spec is set to true.
  617. Clear the exception and return 0 if spec is NULL.
  618. */
  619. int
  620. _PyModuleSpec_IsInitializing(PyObject *spec)
  621. {
  622. if (spec != NULL) {
  623. _Py_IDENTIFIER(_initializing);
  624. PyObject *value = _PyObject_GetAttrId(spec, &PyId__initializing);
  625. if (value != NULL) {
  626. int initializing = PyObject_IsTrue(value);
  627. Py_DECREF(value);
  628. if (initializing >= 0) {
  629. return initializing;
  630. }
  631. }
  632. }
  633. PyErr_Clear();
  634. return 0;
  635. }
  636. static PyObject*
  637. module_getattro(PyModuleObject *m, PyObject *name)
  638. {
  639. PyObject *attr, *mod_name, *getattr;
  640. attr = PyObject_GenericGetAttr((PyObject *)m, name);
  641. if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError)) {
  642. return attr;
  643. }
  644. PyErr_Clear();
  645. if (m->md_dict) {
  646. _Py_IDENTIFIER(__getattr__);
  647. getattr = _PyDict_GetItemId(m->md_dict, &PyId___getattr__);
  648. if (getattr) {
  649. return PyObject_CallOneArg(getattr, name);
  650. }
  651. mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__);
  652. if (mod_name && PyUnicode_Check(mod_name)) {
  653. Py_INCREF(mod_name);
  654. PyObject *spec = _PyDict_GetItemId(m->md_dict, &PyId___spec__);
  655. Py_XINCREF(spec);
  656. if (_PyModuleSpec_IsInitializing(spec)) {
  657. PyErr_Format(PyExc_AttributeError,
  658. "partially initialized "
  659. "module '%U' has no attribute '%U' "
  660. "(most likely due to a circular import)",
  661. mod_name, name);
  662. }
  663. else {
  664. PyErr_Format(PyExc_AttributeError,
  665. "module '%U' has no attribute '%U'",
  666. mod_name, name);
  667. }
  668. Py_XDECREF(spec);
  669. Py_DECREF(mod_name);
  670. return NULL;
  671. }
  672. }
  673. PyErr_Format(PyExc_AttributeError,
  674. "module has no attribute '%U'", name);
  675. return NULL;
  676. }
  677. static int
  678. module_traverse(PyModuleObject *m, visitproc visit, void *arg)
  679. {
  680. /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
  681. if (m->md_def && m->md_def->m_traverse
  682. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  683. {
  684. int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
  685. if (res)
  686. return res;
  687. }
  688. Py_VISIT(m->md_dict);
  689. return 0;
  690. }
  691. static int
  692. module_clear(PyModuleObject *m)
  693. {
  694. /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
  695. if (m->md_def && m->md_def->m_clear
  696. && (m->md_def->m_size <= 0 || m->md_state != NULL))
  697. {
  698. int res = m->md_def->m_clear((PyObject*)m);
  699. if (PyErr_Occurred()) {
  700. PySys_FormatStderr("Exception ignored in m_clear of module%s%V\n",
  701. m->md_name ? " " : "",
  702. m->md_name, "");
  703. PyErr_WriteUnraisable(NULL);
  704. }
  705. if (res)
  706. return res;
  707. }
  708. Py_CLEAR(m->md_dict);
  709. return 0;
  710. }
  711. static PyObject *
  712. module_dir(PyObject *self, PyObject *args)
  713. {
  714. _Py_IDENTIFIER(__dict__);
  715. _Py_IDENTIFIER(__dir__);
  716. PyObject *result = NULL;
  717. PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
  718. if (dict != NULL) {
  719. if (PyDict_Check(dict)) {
  720. PyObject *dirfunc = _PyDict_GetItemIdWithError(dict, &PyId___dir__);
  721. if (dirfunc) {
  722. result = _PyObject_CallNoArg(dirfunc);
  723. }
  724. else if (!PyErr_Occurred()) {
  725. result = PyDict_Keys(dict);
  726. }
  727. }
  728. else {
  729. const char *name = PyModule_GetName(self);
  730. if (name)
  731. PyErr_Format(PyExc_TypeError,
  732. "%.200s.__dict__ is not a dictionary",
  733. name);
  734. }
  735. }
  736. Py_XDECREF(dict);
  737. return result;
  738. }
  739. static PyMethodDef module_methods[] = {
  740. {"__dir__", module_dir, METH_NOARGS,
  741. PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
  742. {0}
  743. };
  744. PyTypeObject PyModule_Type = {
  745. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  746. "module", /* tp_name */
  747. sizeof(PyModuleObject), /* tp_basicsize */
  748. 0, /* tp_itemsize */
  749. (destructor)module_dealloc, /* tp_dealloc */
  750. 0, /* tp_vectorcall_offset */
  751. 0, /* tp_getattr */
  752. 0, /* tp_setattr */
  753. 0, /* tp_as_async */
  754. (reprfunc)module_repr, /* tp_repr */
  755. 0, /* tp_as_number */
  756. 0, /* tp_as_sequence */
  757. 0, /* tp_as_mapping */
  758. 0, /* tp_hash */
  759. 0, /* tp_call */
  760. 0, /* tp_str */
  761. (getattrofunc)module_getattro, /* tp_getattro */
  762. PyObject_GenericSetAttr, /* tp_setattro */
  763. 0, /* tp_as_buffer */
  764. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  765. Py_TPFLAGS_BASETYPE, /* tp_flags */
  766. module___init____doc__, /* tp_doc */
  767. (traverseproc)module_traverse, /* tp_traverse */
  768. (inquiry)module_clear, /* tp_clear */
  769. 0, /* tp_richcompare */
  770. offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
  771. 0, /* tp_iter */
  772. 0, /* tp_iternext */
  773. module_methods, /* tp_methods */
  774. module_members, /* tp_members */
  775. 0, /* tp_getset */
  776. 0, /* tp_base */
  777. 0, /* tp_dict */
  778. 0, /* tp_descr_get */
  779. 0, /* tp_descr_set */
  780. offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
  781. module___init__, /* tp_init */
  782. PyType_GenericAlloc, /* tp_alloc */
  783. PyType_GenericNew, /* tp_new */
  784. PyObject_GC_Del, /* tp_free */
  785. };