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.

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