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