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.

515 lines
15 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 "structmember.h"
  4. static Py_ssize_t max_module_number;
  5. typedef struct {
  6. PyObject_HEAD
  7. PyObject *md_dict;
  8. struct PyModuleDef *md_def;
  9. void *md_state;
  10. PyObject *md_weaklist;
  11. PyObject *md_name; /* for logging purposes after md_dict is cleared */
  12. } PyModuleObject;
  13. static PyMemberDef module_members[] = {
  14. {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
  15. {0}
  16. };
  17. static PyTypeObject moduledef_type = {
  18. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  19. "moduledef", /* tp_name */
  20. sizeof(struct PyModuleDef), /* tp_size */
  21. 0, /* tp_itemsize */
  22. };
  23. static int
  24. module_init_dict(PyModuleObject *mod, PyObject *md_dict,
  25. PyObject *name, PyObject *doc)
  26. {
  27. if (md_dict == NULL)
  28. return -1;
  29. if (doc == NULL)
  30. doc = Py_None;
  31. if (PyDict_SetItemString(md_dict, "__name__", name) != 0)
  32. return -1;
  33. if (PyDict_SetItemString(md_dict, "__doc__", doc) != 0)
  34. return -1;
  35. if (PyDict_SetItemString(md_dict, "__package__", Py_None) != 0)
  36. return -1;
  37. if (PyDict_SetItemString(md_dict, "__loader__", Py_None) != 0)
  38. return -1;
  39. if (PyDict_SetItemString(md_dict, "__spec__", Py_None) != 0)
  40. return -1;
  41. if (PyUnicode_CheckExact(name)) {
  42. Py_INCREF(name);
  43. Py_XDECREF(mod->md_name);
  44. mod->md_name = name;
  45. }
  46. return 0;
  47. }
  48. PyObject *
  49. PyModule_NewObject(PyObject *name)
  50. {
  51. PyModuleObject *m;
  52. m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
  53. if (m == NULL)
  54. return NULL;
  55. m->md_def = NULL;
  56. m->md_state = NULL;
  57. m->md_weaklist = NULL;
  58. m->md_name = NULL;
  59. m->md_dict = PyDict_New();
  60. if (module_init_dict(m, m->md_dict, name, NULL) != 0)
  61. goto fail;
  62. PyObject_GC_Track(m);
  63. return (PyObject *)m;
  64. fail:
  65. Py_DECREF(m);
  66. return NULL;
  67. }
  68. PyObject *
  69. PyModule_New(const char *name)
  70. {
  71. PyObject *nameobj, *module;
  72. nameobj = PyUnicode_FromString(name);
  73. if (nameobj == NULL)
  74. return NULL;
  75. module = PyModule_NewObject(nameobj);
  76. Py_DECREF(nameobj);
  77. return module;
  78. }
  79. PyObject *
  80. PyModule_Create2(struct PyModuleDef* module, int module_api_version)
  81. {
  82. PyObject *d, *v, *n;
  83. PyMethodDef *ml;
  84. const char* name;
  85. PyModuleObject *m;
  86. PyInterpreterState *interp = PyThreadState_Get()->interp;
  87. if (interp->modules == NULL)
  88. Py_FatalError("Python import machinery not initialized");
  89. if (PyType_Ready(&moduledef_type) < 0)
  90. return NULL;
  91. if (module->m_base.m_index == 0) {
  92. max_module_number++;
  93. Py_REFCNT(module) = 1;
  94. Py_TYPE(module) = &moduledef_type;
  95. module->m_base.m_index = max_module_number;
  96. }
  97. name = module->m_name;
  98. if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
  99. int err;
  100. err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  101. "Python C API version mismatch for module %.100s: "
  102. "This Python has API version %d, module %.100s has version %d.",
  103. name,
  104. PYTHON_API_VERSION, name, module_api_version);
  105. if (err)
  106. return NULL;
  107. }
  108. /* Make sure name is fully qualified.
  109. This is a bit of a hack: when the shared library is loaded,
  110. the module name is "package.module", but the module calls
  111. PyModule_Create*() with just "module" for the name. The shared
  112. library loader squirrels away the true name of the module in
  113. _Py_PackageContext, and PyModule_Create*() will substitute this
  114. (if the name actually matches).
  115. */
  116. if (_Py_PackageContext != NULL) {
  117. char *p = strrchr(_Py_PackageContext, '.');
  118. if (p != NULL && strcmp(module->m_name, p+1) == 0) {
  119. name = _Py_PackageContext;
  120. _Py_PackageContext = NULL;
  121. }
  122. }
  123. if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
  124. return NULL;
  125. if (module->m_size > 0) {
  126. m->md_state = PyMem_MALLOC(module->m_size);
  127. if (!m->md_state) {
  128. PyErr_NoMemory();
  129. Py_DECREF(m);
  130. return NULL;
  131. }
  132. memset(m->md_state, 0, module->m_size);
  133. }
  134. d = PyModule_GetDict((PyObject*)m);
  135. if (module->m_methods != NULL) {
  136. n = PyUnicode_FromString(name);
  137. if (n == NULL) {
  138. Py_DECREF(m);
  139. return NULL;
  140. }
  141. for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
  142. if ((ml->ml_flags & METH_CLASS) ||
  143. (ml->ml_flags & METH_STATIC)) {
  144. PyErr_SetString(PyExc_ValueError,
  145. "module functions cannot set"
  146. " METH_CLASS or METH_STATIC");
  147. Py_DECREF(n);
  148. Py_DECREF(m);
  149. return NULL;
  150. }
  151. v = PyCFunction_NewEx(ml, (PyObject*)m, n);
  152. if (v == NULL) {
  153. Py_DECREF(n);
  154. Py_DECREF(m);
  155. return NULL;
  156. }
  157. if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
  158. Py_DECREF(v);
  159. Py_DECREF(n);
  160. Py_DECREF(m);
  161. return NULL;
  162. }
  163. Py_DECREF(v);
  164. }
  165. Py_DECREF(n);
  166. }
  167. if (module->m_doc != NULL) {
  168. v = PyUnicode_FromString(module->m_doc);
  169. if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
  170. Py_XDECREF(v);
  171. Py_DECREF(m);
  172. return NULL;
  173. }
  174. Py_DECREF(v);
  175. }
  176. m->md_def = module;
  177. return (PyObject*)m;
  178. }
  179. PyObject *
  180. PyModule_GetDict(PyObject *m)
  181. {
  182. PyObject *d;
  183. if (!PyModule_Check(m)) {
  184. PyErr_BadInternalCall();
  185. return NULL;
  186. }
  187. d = ((PyModuleObject *)m) -> md_dict;
  188. if (d == NULL)
  189. ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
  190. return d;
  191. }
  192. PyObject*
  193. PyModule_GetNameObject(PyObject *m)
  194. {
  195. PyObject *d;
  196. PyObject *name;
  197. if (!PyModule_Check(m)) {
  198. PyErr_BadArgument();
  199. return NULL;
  200. }
  201. d = ((PyModuleObject *)m)->md_dict;
  202. if (d == NULL ||
  203. (name = PyDict_GetItemString(d, "__name__")) == NULL ||
  204. !PyUnicode_Check(name))
  205. {
  206. PyErr_SetString(PyExc_SystemError, "nameless module");
  207. return NULL;
  208. }
  209. Py_INCREF(name);
  210. return name;
  211. }
  212. const char *
  213. PyModule_GetName(PyObject *m)
  214. {
  215. PyObject *name = PyModule_GetNameObject(m);
  216. if (name == NULL)
  217. return NULL;
  218. Py_DECREF(name); /* module dict has still a reference */
  219. return _PyUnicode_AsString(name);
  220. }
  221. PyObject*
  222. PyModule_GetFilenameObject(PyObject *m)
  223. {
  224. PyObject *d;
  225. PyObject *fileobj;
  226. if (!PyModule_Check(m)) {
  227. PyErr_BadArgument();
  228. return NULL;
  229. }
  230. d = ((PyModuleObject *)m)->md_dict;
  231. if (d == NULL ||
  232. (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
  233. !PyUnicode_Check(fileobj))
  234. {
  235. PyErr_SetString(PyExc_SystemError, "module filename missing");
  236. return NULL;
  237. }
  238. Py_INCREF(fileobj);
  239. return fileobj;
  240. }
  241. const char *
  242. PyModule_GetFilename(PyObject *m)
  243. {
  244. PyObject *fileobj;
  245. char *utf8;
  246. fileobj = PyModule_GetFilenameObject(m);
  247. if (fileobj == NULL)
  248. return NULL;
  249. utf8 = _PyUnicode_AsString(fileobj);
  250. Py_DECREF(fileobj); /* module dict has still a reference */
  251. return utf8;
  252. }
  253. PyModuleDef*
  254. PyModule_GetDef(PyObject* m)
  255. {
  256. if (!PyModule_Check(m)) {
  257. PyErr_BadArgument();
  258. return NULL;
  259. }
  260. return ((PyModuleObject *)m)->md_def;
  261. }
  262. void*
  263. PyModule_GetState(PyObject* m)
  264. {
  265. if (!PyModule_Check(m)) {
  266. PyErr_BadArgument();
  267. return NULL;
  268. }
  269. return ((PyModuleObject *)m)->md_state;
  270. }
  271. void
  272. _PyModule_Clear(PyObject *m)
  273. {
  274. PyObject *d = ((PyModuleObject *)m)->md_dict;
  275. if (d != NULL)
  276. _PyModule_ClearDict(d);
  277. }
  278. void
  279. _PyModule_ClearDict(PyObject *d)
  280. {
  281. /* To make the execution order of destructors for global
  282. objects a bit more predictable, we first zap all objects
  283. whose name starts with a single underscore, before we clear
  284. the entire dictionary. We zap them by replacing them with
  285. None, rather than deleting them from the dictionary, to
  286. avoid rehashing the dictionary (to some extent). */
  287. Py_ssize_t pos;
  288. PyObject *key, *value;
  289. /* First, clear only names starting with a single underscore */
  290. pos = 0;
  291. while (PyDict_Next(d, &pos, &key, &value)) {
  292. if (value != Py_None && PyUnicode_Check(key)) {
  293. if (PyUnicode_READ_CHAR(key, 0) == '_' &&
  294. PyUnicode_READ_CHAR(key, 1) != '_') {
  295. if (Py_VerboseFlag > 1) {
  296. const char *s = _PyUnicode_AsString(key);
  297. if (s != NULL)
  298. PySys_WriteStderr("# clear[1] %s\n", s);
  299. else
  300. PyErr_Clear();
  301. }
  302. if (PyDict_SetItem(d, key, Py_None) != 0)
  303. PyErr_Clear();
  304. }
  305. }
  306. }
  307. /* Next, clear all names except for __builtins__ */
  308. pos = 0;
  309. while (PyDict_Next(d, &pos, &key, &value)) {
  310. if (value != Py_None && PyUnicode_Check(key)) {
  311. if (PyUnicode_READ_CHAR(key, 0) != '_' ||
  312. PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
  313. {
  314. if (Py_VerboseFlag > 1) {
  315. const char *s = _PyUnicode_AsString(key);
  316. if (s != NULL)
  317. PySys_WriteStderr("# clear[2] %s\n", s);
  318. else
  319. PyErr_Clear();
  320. }
  321. if (PyDict_SetItem(d, key, Py_None) != 0)
  322. PyErr_Clear();
  323. }
  324. }
  325. }
  326. /* Note: we leave __builtins__ in place, so that destructors
  327. of non-global objects defined in this module can still use
  328. builtins, in particularly 'None'. */
  329. }
  330. /* Methods */
  331. static int
  332. module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
  333. {
  334. static char *kwlist[] = {"name", "doc", NULL};
  335. PyObject *dict, *name = Py_None, *doc = Py_None;
  336. if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
  337. kwlist, &name, &doc))
  338. return -1;
  339. dict = m->md_dict;
  340. if (dict == NULL) {
  341. dict = PyDict_New();
  342. if (dict == NULL)
  343. return -1;
  344. m->md_dict = dict;
  345. }
  346. if (module_init_dict(m, dict, name, doc) < 0)
  347. return -1;
  348. return 0;
  349. }
  350. static void
  351. module_dealloc(PyModuleObject *m)
  352. {
  353. PyObject_GC_UnTrack(m);
  354. if (Py_VerboseFlag && m->md_name) {
  355. PySys_FormatStderr("# destroy %S\n", m->md_name);
  356. }
  357. if (m->md_weaklist != NULL)
  358. PyObject_ClearWeakRefs((PyObject *) m);
  359. if (m->md_def && m->md_def->m_free)
  360. m->md_def->m_free(m);
  361. Py_XDECREF(m->md_dict);
  362. Py_XDECREF(m->md_name);
  363. if (m->md_state != NULL)
  364. PyMem_FREE(m->md_state);
  365. Py_TYPE(m)->tp_free((PyObject *)m);
  366. }
  367. static PyObject *
  368. module_repr(PyModuleObject *m)
  369. {
  370. PyThreadState *tstate = PyThreadState_GET();
  371. PyInterpreterState *interp = tstate->interp;
  372. return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
  373. }
  374. static int
  375. module_traverse(PyModuleObject *m, visitproc visit, void *arg)
  376. {
  377. if (m->md_def && m->md_def->m_traverse) {
  378. int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
  379. if (res)
  380. return res;
  381. }
  382. Py_VISIT(m->md_dict);
  383. return 0;
  384. }
  385. static int
  386. module_clear(PyModuleObject *m)
  387. {
  388. if (m->md_def && m->md_def->m_clear) {
  389. int res = m->md_def->m_clear((PyObject*)m);
  390. if (res)
  391. return res;
  392. }
  393. Py_CLEAR(m->md_dict);
  394. return 0;
  395. }
  396. static PyObject *
  397. module_dir(PyObject *self, PyObject *args)
  398. {
  399. _Py_IDENTIFIER(__dict__);
  400. PyObject *result = NULL;
  401. PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
  402. if (dict != NULL) {
  403. if (PyDict_Check(dict))
  404. result = PyDict_Keys(dict);
  405. else {
  406. const char *name = PyModule_GetName(self);
  407. if (name)
  408. PyErr_Format(PyExc_TypeError,
  409. "%.200s.__dict__ is not a dictionary",
  410. name);
  411. }
  412. }
  413. Py_XDECREF(dict);
  414. return result;
  415. }
  416. static PyMethodDef module_methods[] = {
  417. {"__dir__", module_dir, METH_NOARGS,
  418. PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
  419. {0}
  420. };
  421. PyDoc_STRVAR(module_doc,
  422. "module(name[, doc])\n\
  423. \n\
  424. Create a module object.\n\
  425. The name must be a string; the optional doc argument can have any type.");
  426. PyTypeObject PyModule_Type = {
  427. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  428. "module", /* tp_name */
  429. sizeof(PyModuleObject), /* tp_size */
  430. 0, /* tp_itemsize */
  431. (destructor)module_dealloc, /* tp_dealloc */
  432. 0, /* tp_print */
  433. 0, /* tp_getattr */
  434. 0, /* tp_setattr */
  435. 0, /* tp_reserved */
  436. (reprfunc)module_repr, /* tp_repr */
  437. 0, /* tp_as_number */
  438. 0, /* tp_as_sequence */
  439. 0, /* tp_as_mapping */
  440. 0, /* tp_hash */
  441. 0, /* tp_call */
  442. 0, /* tp_str */
  443. PyObject_GenericGetAttr, /* tp_getattro */
  444. PyObject_GenericSetAttr, /* tp_setattro */
  445. 0, /* tp_as_buffer */
  446. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  447. Py_TPFLAGS_BASETYPE, /* tp_flags */
  448. module_doc, /* tp_doc */
  449. (traverseproc)module_traverse, /* tp_traverse */
  450. (inquiry)module_clear, /* tp_clear */
  451. 0, /* tp_richcompare */
  452. offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
  453. 0, /* tp_iter */
  454. 0, /* tp_iternext */
  455. module_methods, /* tp_methods */
  456. module_members, /* tp_members */
  457. 0, /* tp_getset */
  458. 0, /* tp_base */
  459. 0, /* tp_dict */
  460. 0, /* tp_descr_get */
  461. 0, /* tp_descr_set */
  462. offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
  463. (initproc)module_init, /* tp_init */
  464. PyType_GenericAlloc, /* tp_alloc */
  465. PyType_GenericNew, /* tp_new */
  466. PyObject_GC_Del, /* tp_free */
  467. };