blob: 89afe29032301d3ee4c14f15bc1cf1b059acbb11 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis1a214512008-06-11 05:26:20 +00007static Py_ssize_t max_module_number;
8
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000010 PyObject_HEAD
11 PyObject *md_dict;
12 struct PyModuleDef *md_def;
13 void *md_state;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020014 PyObject *md_weaklist;
15 PyObject *md_name; /* for logging purposes after md_dict is cleared */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000016} PyModuleObject;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000017
Neil Schemenauerf23473f2001-10-21 22:28:58 +000018static PyMemberDef module_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
20 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +000021};
22
Nick Coghland5cacbb2015-05-23 22:24:10 +100023PyTypeObject PyModuleDef_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000024 PyVarObject_HEAD_INIT(&PyType_Type, 0)
25 "moduledef", /* tp_name */
26 sizeof(struct PyModuleDef), /* tp_size */
27 0, /* tp_itemsize */
Martin v. Löwis1a214512008-06-11 05:26:20 +000028};
29
30
Nick Coghland5cacbb2015-05-23 22:24:10 +100031PyObject*
32PyModuleDef_Init(struct PyModuleDef* def)
33{
34 if (PyType_Ready(&PyModuleDef_Type) < 0)
35 return NULL;
36 if (def->m_base.m_index == 0) {
37 max_module_number++;
38 Py_REFCNT(def) = 1;
39 Py_TYPE(def) = &PyModuleDef_Type;
40 def->m_base.m_index = max_module_number;
41 }
42 return (PyObject*)def;
43}
44
Brett Cannon4c14b5d2013-05-04 13:56:58 -040045static int
Antoine Pitroudcedaf62013-07-31 23:14:08 +020046module_init_dict(PyModuleObject *mod, PyObject *md_dict,
47 PyObject *name, PyObject *doc)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040048{
Benjamin Peterson027ce162014-04-24 19:39:18 -040049 _Py_IDENTIFIER(__name__);
50 _Py_IDENTIFIER(__doc__);
51 _Py_IDENTIFIER(__package__);
52 _Py_IDENTIFIER(__loader__);
53 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka009b8112015-03-18 21:53:15 +020054
Brett Cannon4c14b5d2013-05-04 13:56:58 -040055 if (md_dict == NULL)
56 return -1;
57 if (doc == NULL)
58 doc = Py_None;
59
Benjamin Peterson027ce162014-04-24 19:39:18 -040060 if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040061 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040062 if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040063 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040064 if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040065 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040066 if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040067 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040068 if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0)
Eric Snowb523f842013-11-22 09:05:39 -070069 return -1;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020070 if (PyUnicode_CheckExact(name)) {
71 Py_INCREF(name);
Serhiy Storchaka48842712016-04-06 09:45:48 +030072 Py_XSETREF(mod->md_name, name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +020073 }
Brett Cannon4c14b5d2013-05-04 13:56:58 -040074
75 return 0;
76}
77
78
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079PyObject *
Victor Stinner0639b562011-03-04 12:57:07 +000080PyModule_NewObject(PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 PyModuleObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
84 if (m == NULL)
85 return NULL;
86 m->md_def = NULL;
87 m->md_state = NULL;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020088 m->md_weaklist = NULL;
89 m->md_name = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 m->md_dict = PyDict_New();
Antoine Pitroudcedaf62013-07-31 23:14:08 +020091 if (module_init_dict(m, m->md_dict, name, NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyObject_GC_Track(m);
94 return (PyObject *)m;
Guido van Rossumc45611d1993-11-17 22:58:56 +000095
96 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 Py_DECREF(m);
98 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099}
100
Martin v. Löwis1a214512008-06-11 05:26:20 +0000101PyObject *
Victor Stinner0639b562011-03-04 12:57:07 +0000102PyModule_New(const char *name)
103{
104 PyObject *nameobj, *module;
105 nameobj = PyUnicode_FromString(name);
106 if (nameobj == NULL)
107 return NULL;
108 module = PyModule_NewObject(nameobj);
109 Py_DECREF(nameobj);
110 return module;
111}
112
Nick Coghland5cacbb2015-05-23 22:24:10 +1000113/* Check API/ABI version
114 * Issues a warning on mismatch, which is usually not fatal.
115 * Returns 0 if an exception is raised.
116 */
117static int
118check_api_version(const char *name, int module_api_version)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000119{
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000120 if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000121 int err;
122 err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
123 "Python C API version mismatch for module %.100s: "
124 "This Python has API version %d, module %.100s has version %d.",
125 name,
126 PYTHON_API_VERSION, name, module_api_version);
127 if (err)
Nick Coghland5cacbb2015-05-23 22:24:10 +1000128 return 0;
129 }
130 return 1;
131}
132
Nick Coghlan8682f572016-08-21 17:41:56 +1000133static int
134_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
135{
136 PyObject *func;
137 PyMethodDef *fdef;
138
139 for (fdef = functions; fdef->ml_name != NULL; fdef++) {
140 if ((fdef->ml_flags & METH_CLASS) ||
141 (fdef->ml_flags & METH_STATIC)) {
142 PyErr_SetString(PyExc_ValueError,
143 "module functions cannot set"
144 " METH_CLASS or METH_STATIC");
145 return -1;
146 }
147 func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
148 if (func == NULL) {
149 return -1;
150 }
151 if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
152 Py_DECREF(func);
153 return -1;
154 }
155 Py_DECREF(func);
156 }
157
158 return 0;
159}
160
Nick Coghland5cacbb2015-05-23 22:24:10 +1000161PyObject *
162PyModule_Create2(struct PyModuleDef* module, int module_api_version)
163{
Eric Snow86b7afd2017-09-04 17:54:09 -0600164 if (!_PyImport_IsInitialized(PyThreadState_GET()->interp))
165 Py_FatalError("Python import machinery not initialized");
166 return _PyModule_CreateInitialized(module, module_api_version);
167}
168
169PyObject *
170_PyModule_CreateInitialized(struct PyModuleDef* module, int module_api_version)
171{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000172 const char* name;
173 PyModuleObject *m;
Eric Snow86b7afd2017-09-04 17:54:09 -0600174
Nick Coghland5cacbb2015-05-23 22:24:10 +1000175 if (!PyModuleDef_Init(module))
176 return NULL;
177 name = module->m_name;
178 if (!check_api_version(name, module_api_version)) {
179 return NULL;
180 }
181 if (module->m_slots) {
182 PyErr_Format(
183 PyExc_SystemError,
184 "module %s: PyModule_Create is incompatible with m_slots", name);
185 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 }
187 /* Make sure name is fully qualified.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 This is a bit of a hack: when the shared library is loaded,
190 the module name is "package.module", but the module calls
191 PyModule_Create*() with just "module" for the name. The shared
192 library loader squirrels away the true name of the module in
193 _Py_PackageContext, and PyModule_Create*() will substitute this
194 (if the name actually matches).
195 */
196 if (_Py_PackageContext != NULL) {
Serhiy Storchakab57d9ea2016-11-21 10:25:54 +0200197 const char *p = strrchr(_Py_PackageContext, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if (p != NULL && strcmp(module->m_name, p+1) == 0) {
199 name = _Py_PackageContext;
200 _Py_PackageContext = NULL;
201 }
202 }
203 if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
204 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (module->m_size > 0) {
207 m->md_state = PyMem_MALLOC(module->m_size);
208 if (!m->md_state) {
209 PyErr_NoMemory();
210 Py_DECREF(m);
211 return NULL;
212 }
213 memset(m->md_state, 0, module->m_size);
214 }
215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (module->m_methods != NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +1000217 if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
Meador Inge29e49d62012-07-19 13:45:43 -0500218 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 return NULL;
Meador Inge29e49d62012-07-19 13:45:43 -0500220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 }
222 if (module->m_doc != NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +1000223 if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
Meador Inge29e49d62012-07-19 13:45:43 -0500224 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return NULL;
226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 }
228 m->md_def = module;
229 return (PyObject*)m;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000230}
231
Nick Coghland5cacbb2015-05-23 22:24:10 +1000232PyObject *
233PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version)
234{
235 PyModuleDef_Slot* cur_slot;
236 PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
237 PyObject *nameobj;
238 PyObject *m = NULL;
239 int has_execution_slots = 0;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200240 const char *name;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000241 int ret;
242
243 PyModuleDef_Init(def);
244
245 nameobj = PyObject_GetAttrString(spec, "name");
246 if (nameobj == NULL) {
247 return NULL;
248 }
249 name = PyUnicode_AsUTF8(nameobj);
250 if (name == NULL) {
251 goto error;
252 }
253
254 if (!check_api_version(name, module_api_version)) {
255 goto error;
256 }
257
258 if (def->m_size < 0) {
259 PyErr_Format(
260 PyExc_SystemError,
261 "module %s: m_size may not be negative for multi-phase initialization",
262 name);
263 goto error;
264 }
265
266 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
267 if (cur_slot->slot == Py_mod_create) {
268 if (create) {
269 PyErr_Format(
270 PyExc_SystemError,
271 "module %s has multiple create slots",
272 name);
273 goto error;
274 }
275 create = cur_slot->value;
276 } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) {
277 PyErr_Format(
278 PyExc_SystemError,
279 "module %s uses unknown slot ID %i",
280 name, cur_slot->slot);
281 goto error;
282 } else {
283 has_execution_slots = 1;
284 }
285 }
286
287 if (create) {
288 m = create(spec, def);
289 if (m == NULL) {
290 if (!PyErr_Occurred()) {
291 PyErr_Format(
292 PyExc_SystemError,
293 "creation of module %s failed without setting an exception",
294 name);
295 }
296 goto error;
297 } else {
298 if (PyErr_Occurred()) {
299 PyErr_Format(PyExc_SystemError,
300 "creation of module %s raised unreported exception",
301 name);
302 goto error;
303 }
304 }
305 } else {
Nick Coghlan8682f572016-08-21 17:41:56 +1000306 m = PyModule_NewObject(nameobj);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000307 if (m == NULL) {
308 goto error;
309 }
310 }
311
312 if (PyModule_Check(m)) {
313 ((PyModuleObject*)m)->md_state = NULL;
314 ((PyModuleObject*)m)->md_def = def;
315 } else {
316 if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
317 PyErr_Format(
318 PyExc_SystemError,
319 "module %s is not a module object, but requests module state",
320 name);
321 goto error;
322 }
323 if (has_execution_slots) {
324 PyErr_Format(
325 PyExc_SystemError,
326 "module %s specifies execution slots, but did not create "
327 "a ModuleType instance",
328 name);
329 goto error;
330 }
331 }
332
333 if (def->m_methods != NULL) {
Nick Coghlan8682f572016-08-21 17:41:56 +1000334 ret = _add_methods_to_object(m, nameobj, def->m_methods);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000335 if (ret != 0) {
336 goto error;
337 }
338 }
339
340 if (def->m_doc != NULL) {
341 ret = PyModule_SetDocString(m, def->m_doc);
342 if (ret != 0) {
343 goto error;
344 }
345 }
346
Nick Coghlana48db2b2015-05-24 01:03:46 +1000347 Py_DECREF(nameobj);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000348 return m;
349
350error:
351 Py_DECREF(nameobj);
352 Py_XDECREF(m);
353 return NULL;
354}
355
356int
357PyModule_ExecDef(PyObject *module, PyModuleDef *def)
358{
359 PyModuleDef_Slot *cur_slot;
360 const char *name;
361 int ret;
362
363 name = PyModule_GetName(module);
364 if (name == NULL) {
365 return -1;
366 }
367
Nick Coghlan8682f572016-08-21 17:41:56 +1000368 if (def->m_size >= 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +1000369 PyModuleObject *md = (PyModuleObject*)module;
370 if (md->md_state == NULL) {
371 /* Always set a state pointer; this serves as a marker to skip
372 * multiple initialization (importlib.reload() is no-op) */
373 md->md_state = PyMem_MALLOC(def->m_size);
374 if (!md->md_state) {
375 PyErr_NoMemory();
376 return -1;
377 }
378 memset(md->md_state, 0, def->m_size);
379 }
380 }
381
382 if (def->m_slots == NULL) {
383 return 0;
384 }
385
386 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
387 switch (cur_slot->slot) {
388 case Py_mod_create:
Serhiy Storchaka333ad922016-09-26 23:14:44 +0300389 /* handled in PyModule_FromDefAndSpec2 */
Nick Coghland5cacbb2015-05-23 22:24:10 +1000390 break;
391 case Py_mod_exec:
392 ret = ((int (*)(PyObject *))cur_slot->value)(module);
393 if (ret != 0) {
394 if (!PyErr_Occurred()) {
395 PyErr_Format(
396 PyExc_SystemError,
397 "execution of module %s failed without setting an exception",
398 name);
399 }
400 return -1;
401 }
402 if (PyErr_Occurred()) {
403 PyErr_Format(
404 PyExc_SystemError,
405 "execution of module %s raised unreported exception",
406 name);
407 return -1;
408 }
409 break;
410 default:
411 PyErr_Format(
412 PyExc_SystemError,
413 "module %s initialized with unknown slot %i",
414 name, cur_slot->slot);
415 return -1;
416 }
417 }
418 return 0;
419}
420
421int
422PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
423{
Nick Coghlan8682f572016-08-21 17:41:56 +1000424 int res;
425 PyObject *name = PyModule_GetNameObject(m);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000426 if (name == NULL) {
427 return -1;
428 }
429
Nick Coghlan8682f572016-08-21 17:41:56 +1000430 res = _add_methods_to_object(m, name, functions);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000431 Py_DECREF(name);
Nick Coghlan8682f572016-08-21 17:41:56 +1000432 return res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000433}
434
435int
436PyModule_SetDocString(PyObject *m, const char *doc)
437{
438 PyObject *v;
439 _Py_IDENTIFIER(__doc__);
440
441 v = PyUnicode_FromString(doc);
442 if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) {
443 Py_XDECREF(v);
444 return -1;
445 }
446 Py_DECREF(v);
447 return 0;
448}
Martin v. Löwis1a214512008-06-11 05:26:20 +0000449
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000451PyModule_GetDict(PyObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *d;
454 if (!PyModule_Check(m)) {
455 PyErr_BadInternalCall();
456 return NULL;
457 }
458 d = ((PyModuleObject *)m) -> md_dict;
Berker Peksag7fbce562016-08-19 12:00:13 +0300459 assert(d != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461}
462
Victor Stinnerbd475112011-02-23 00:21:43 +0000463PyObject*
464PyModule_GetNameObject(PyObject *m)
Guido van Rossum0558a201990-10-26 15:00:11 +0000465{
Benjamin Peterson027ce162014-04-24 19:39:18 -0400466 _Py_IDENTIFIER(__name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyObject *d;
Victor Stinnerbd475112011-02-23 00:21:43 +0000468 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (!PyModule_Check(m)) {
470 PyErr_BadArgument();
471 return NULL;
472 }
473 d = ((PyModuleObject *)m)->md_dict;
474 if (d == NULL ||
Benjamin Peterson027ce162014-04-24 19:39:18 -0400475 (name = _PyDict_GetItemId(d, &PyId___name__)) == NULL ||
Victor Stinnerbd475112011-02-23 00:21:43 +0000476 !PyUnicode_Check(name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 {
478 PyErr_SetString(PyExc_SystemError, "nameless module");
479 return NULL;
480 }
Victor Stinnerbd475112011-02-23 00:21:43 +0000481 Py_INCREF(name);
482 return name;
483}
484
485const char *
486PyModule_GetName(PyObject *m)
487{
488 PyObject *name = PyModule_GetNameObject(m);
489 if (name == NULL)
490 return NULL;
491 Py_DECREF(name); /* module dict has still a reference */
Serhiy Storchaka06515832016-11-20 09:13:07 +0200492 return PyUnicode_AsUTF8(name);
Guido van Rossum0558a201990-10-26 15:00:11 +0000493}
494
Victor Stinner6c00c142010-08-17 23:37:11 +0000495PyObject*
496PyModule_GetFilenameObject(PyObject *m)
Guido van Rossum98cc19f1999-02-15 14:47:16 +0000497{
Benjamin Peterson027ce162014-04-24 19:39:18 -0400498 _Py_IDENTIFIER(__file__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject *d;
500 PyObject *fileobj;
501 if (!PyModule_Check(m)) {
502 PyErr_BadArgument();
503 return NULL;
504 }
505 d = ((PyModuleObject *)m)->md_dict;
506 if (d == NULL ||
Benjamin Peterson027ce162014-04-24 19:39:18 -0400507 (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 !PyUnicode_Check(fileobj))
509 {
510 PyErr_SetString(PyExc_SystemError, "module filename missing");
511 return NULL;
512 }
Victor Stinner6c00c142010-08-17 23:37:11 +0000513 Py_INCREF(fileobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return fileobj;
Victor Stinner8124feb2010-05-07 00:50:12 +0000515}
516
517const char *
518PyModule_GetFilename(PyObject *m)
519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 PyObject *fileobj;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200521 const char *utf8;
Victor Stinner6c00c142010-08-17 23:37:11 +0000522 fileobj = PyModule_GetFilenameObject(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (fileobj == NULL)
524 return NULL;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200525 utf8 = PyUnicode_AsUTF8(fileobj);
Victor Stinnerbd475112011-02-23 00:21:43 +0000526 Py_DECREF(fileobj); /* module dict has still a reference */
Victor Stinner6c00c142010-08-17 23:37:11 +0000527 return utf8;
Guido van Rossum98cc19f1999-02-15 14:47:16 +0000528}
529
Martin v. Löwis1a214512008-06-11 05:26:20 +0000530PyModuleDef*
531PyModule_GetDef(PyObject* m)
532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (!PyModule_Check(m)) {
534 PyErr_BadArgument();
535 return NULL;
536 }
537 return ((PyModuleObject *)m)->md_def;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000538}
539
540void*
541PyModule_GetState(PyObject* m)
542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (!PyModule_Check(m)) {
544 PyErr_BadArgument();
545 return NULL;
546 }
547 return ((PyModuleObject *)m)->md_state;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000548}
549
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000550void
Fred Drakeee238b92000-07-09 06:03:25 +0000551_PyModule_Clear(PyObject *m)
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000552{
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200553 PyObject *d = ((PyModuleObject *)m)->md_dict;
554 if (d != NULL)
555 _PyModule_ClearDict(d);
556}
557
558void
559_PyModule_ClearDict(PyObject *d)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* To make the execution order of destructors for global
562 objects a bit more predictable, we first zap all objects
563 whose name starts with a single underscore, before we clear
564 the entire dictionary. We zap them by replacing them with
565 None, rather than deleting them from the dictionary, to
566 avoid rehashing the dictionary (to some extent). */
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_ssize_t pos;
569 PyObject *key, *value;
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* First, clear only names starting with a single underscore */
572 pos = 0;
573 while (PyDict_Next(d, &pos, &key, &value)) {
574 if (value != Py_None && PyUnicode_Check(key)) {
Brett Cannon62228db2012-04-29 14:38:11 -0400575 if (PyUnicode_READ_CHAR(key, 0) == '_' &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200576 PyUnicode_READ_CHAR(key, 1) != '_') {
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000577 if (Py_VerboseFlag > 1) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200578 const char *s = PyUnicode_AsUTF8(key);
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000579 if (s != NULL)
580 PySys_WriteStderr("# clear[1] %s\n", s);
581 else
582 PyErr_Clear();
583 }
Serhiy Storchaka1f9d11b2014-02-12 09:55:01 +0200584 if (PyDict_SetItem(d, key, Py_None) != 0)
585 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 }
587 }
588 }
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 /* Next, clear all names except for __builtins__ */
591 pos = 0;
592 while (PyDict_Next(d, &pos, &key, &value)) {
593 if (value != Py_None && PyUnicode_Check(key)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200594 if (PyUnicode_READ_CHAR(key, 0) != '_' ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200595 !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000596 {
597 if (Py_VerboseFlag > 1) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200598 const char *s = PyUnicode_AsUTF8(key);
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000599 if (s != NULL)
600 PySys_WriteStderr("# clear[2] %s\n", s);
601 else
602 PyErr_Clear();
603 }
Serhiy Storchaka1f9d11b2014-02-12 09:55:01 +0200604 if (PyDict_SetItem(d, key, Py_None) != 0)
605 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 }
608 }
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Note: we leave __builtins__ in place, so that destructors
611 of non-global objects defined in this module can still use
612 builtins, in particularly 'None'. */
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000613
614}
615
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200616/*[clinic input]
617class module "PyModuleObject *" "&PyModule_Type"
618[clinic start generated code]*/
619/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
620
621#include "clinic/moduleobject.c.h"
622
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623/* Methods */
624
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200625/*[clinic input]
626module.__init__
627 name: unicode
628 doc: object = None
629
630Create a module object.
631
632The name must be a string; the optional doc argument can have any type.
633[clinic start generated code]*/
634
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635static int
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200636module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
637/*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200639 PyObject *dict = self->md_dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (dict == NULL) {
641 dict = PyDict_New();
642 if (dict == NULL)
643 return -1;
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200644 self->md_dict = dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200646 if (module_init_dict(self, dict, name, doc) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return -1;
648 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649}
650
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651static void
Fred Drakeee238b92000-07-09 06:03:25 +0000652module_dealloc(PyModuleObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyObject_GC_UnTrack(m);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200655 if (Py_VerboseFlag && m->md_name) {
656 PySys_FormatStderr("# destroy %S\n", m->md_name);
657 }
658 if (m->md_weaklist != NULL)
659 PyObject_ClearWeakRefs((PyObject *) m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (m->md_def && m->md_def->m_free)
661 m->md_def->m_free(m);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200662 Py_XDECREF(m->md_dict);
663 Py_XDECREF(m->md_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (m->md_state != NULL)
665 PyMem_FREE(m->md_state);
666 Py_TYPE(m)->tp_free((PyObject *)m);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667}
668
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669static PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000670module_repr(PyModuleObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000671{
Eric Snowb523f842013-11-22 09:05:39 -0700672 PyThreadState *tstate = PyThreadState_GET();
673 PyInterpreterState *interp = tstate->interp;
Barry Warsaw2907fe62001-08-16 20:39:24 +0000674
Eric Snowb523f842013-11-22 09:05:39 -0700675 return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676}
677
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700678static PyObject*
Benjamin Peterson1184e262014-04-24 19:29:23 -0400679module_getattro(PyModuleObject *m, PyObject *name)
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700680{
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700681 PyObject *attr, *mod_name;
Benjamin Peterson1184e262014-04-24 19:29:23 -0400682 attr = PyObject_GenericGetAttr((PyObject *)m, name);
683 if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError))
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700684 return attr;
685 PyErr_Clear();
Benjamin Peterson1184e262014-04-24 19:29:23 -0400686 if (m->md_dict) {
Benjamin Peterson027ce162014-04-24 19:39:18 -0400687 _Py_IDENTIFIER(__name__);
688 mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__);
Benjamin Peterson1184e262014-04-24 19:29:23 -0400689 if (mod_name) {
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700690 PyErr_Format(PyExc_AttributeError,
691 "module '%U' has no attribute '%U'", mod_name, name);
692 return NULL;
693 }
Benjamin Peterson1184e262014-04-24 19:29:23 -0400694 else if (PyErr_Occurred()) {
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700695 PyErr_Clear();
Benjamin Peterson1184e262014-04-24 19:29:23 -0400696 }
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700697 }
698 PyErr_Format(PyExc_AttributeError,
699 "module has no attribute '%U'", name);
700 return NULL;
701}
702
Neil Schemenauer10e31cf2001-01-02 15:58:27 +0000703static int
704module_traverse(PyModuleObject *m, visitproc visit, void *arg)
705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (m->md_def && m->md_def->m_traverse) {
707 int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
708 if (res)
709 return res;
710 }
711 Py_VISIT(m->md_dict);
712 return 0;
Neil Schemenauer10e31cf2001-01-02 15:58:27 +0000713}
714
Martin v. Löwis1a214512008-06-11 05:26:20 +0000715static int
716module_clear(PyModuleObject *m)
717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (m->md_def && m->md_def->m_clear) {
719 int res = m->md_def->m_clear((PyObject*)m);
720 if (res)
721 return res;
722 }
723 Py_CLEAR(m->md_dict);
724 return 0;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000725}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500727static PyObject *
728module_dir(PyObject *self, PyObject *args)
729{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200730 _Py_IDENTIFIER(__dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500731 PyObject *result = NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200732 PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500733
734 if (dict != NULL) {
735 if (PyDict_Check(dict))
736 result = PyDict_Keys(dict);
737 else {
738 const char *name = PyModule_GetName(self);
739 if (name)
740 PyErr_Format(PyExc_TypeError,
741 "%.200s.__dict__ is not a dictionary",
742 name);
743 }
744 }
745
746 Py_XDECREF(dict);
747 return result;
748}
749
750static PyMethodDef module_methods[] = {
751 {"__dir__", module_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -0500752 PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500753 {0}
754};
755
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756PyTypeObject PyModule_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyVarObject_HEAD_INIT(&PyType_Type, 0)
758 "module", /* tp_name */
759 sizeof(PyModuleObject), /* tp_size */
760 0, /* tp_itemsize */
761 (destructor)module_dealloc, /* tp_dealloc */
762 0, /* tp_print */
763 0, /* tp_getattr */
764 0, /* tp_setattr */
765 0, /* tp_reserved */
766 (reprfunc)module_repr, /* tp_repr */
767 0, /* tp_as_number */
768 0, /* tp_as_sequence */
769 0, /* tp_as_mapping */
770 0, /* tp_hash */
771 0, /* tp_call */
772 0, /* tp_str */
Benjamin Peterson1184e262014-04-24 19:29:23 -0400773 (getattrofunc)module_getattro, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 PyObject_GenericSetAttr, /* tp_setattro */
775 0, /* tp_as_buffer */
776 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
777 Py_TPFLAGS_BASETYPE, /* tp_flags */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200778 module___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 (traverseproc)module_traverse, /* tp_traverse */
780 (inquiry)module_clear, /* tp_clear */
781 0, /* tp_richcompare */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200782 offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 0, /* tp_iter */
784 0, /* tp_iternext */
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500785 module_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 module_members, /* tp_members */
787 0, /* tp_getset */
788 0, /* tp_base */
789 0, /* tp_dict */
790 0, /* tp_descr_get */
791 0, /* tp_descr_set */
792 offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200793 module___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyType_GenericAlloc, /* tp_alloc */
795 PyType_GenericNew, /* tp_new */
796 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000797};