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.

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