~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Objects/moduleobject.c

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

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