moduleobject.c 15.9 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3
/* Module object implementation */

4
#include "Python.h"
5
#include "structmember.h"
Guido van Rossum's avatar
Guido van Rossum committed
6

7 8
static Py_ssize_t max_module_number;

Guido van Rossum's avatar
Guido van Rossum committed
9
typedef struct {
10 11 12 13
    PyObject_HEAD
    PyObject *md_dict;
    struct PyModuleDef *md_def;
    void *md_state;
14
} PyModuleObject;
Guido van Rossum's avatar
Guido van Rossum committed
15

16
static PyMemberDef module_members[] = {
17 18
    {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
    {0}
19 20
};

21
static PyTypeObject moduledef_type = {
22 23 24 25
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "moduledef",                                /* tp_name */
    sizeof(struct PyModuleDef),                 /* tp_size */
    0,                                          /* tp_itemsize */
26 27 28
};


29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
static int
module_init_dict(PyObject *md_dict, PyObject *name, PyObject *doc)
{
    if (md_dict == NULL)
        return -1;
    if (doc == NULL)
        doc = Py_None;

    if (PyDict_SetItemString(md_dict, "__name__", name) != 0)
        return -1;
    if (PyDict_SetItemString(md_dict, "__doc__", doc) != 0)
        return -1;
    if (PyDict_SetItemString(md_dict, "__package__", Py_None) != 0)
        return -1;
    if (PyDict_SetItemString(md_dict, "__loader__", Py_None) != 0)
        return -1;

    return 0;
}


50
PyObject *
51
PyModule_NewObject(PyObject *name)
Guido van Rossum's avatar
Guido van Rossum committed
52
{
53 54 55 56 57 58 59
    PyModuleObject *m;
    m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
    if (m == NULL)
        return NULL;
    m->md_def = NULL;
    m->md_state = NULL;
    m->md_dict = PyDict_New();
60
    if (module_init_dict(m->md_dict, name, NULL) != 0)
61 62 63
        goto fail;
    PyObject_GC_Track(m);
    return (PyObject *)m;
64 65

 fail:
66 67
    Py_DECREF(m);
    return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82
PyObject *
PyModule_New(const char *name)
{
    PyObject *nameobj, *module;
    nameobj = PyUnicode_FromString(name);
    if (nameobj == NULL)
        return NULL;
    module = PyModule_NewObject(nameobj);
    Py_DECREF(nameobj);
    return module;
}


83 84 85
PyObject *
PyModule_Create2(struct PyModuleDef* module, int module_api_version)
{
86 87 88 89
    PyObject *d, *v, *n;
    PyMethodDef *ml;
    const char* name;
    PyModuleObject *m;
90 91 92
    PyInterpreterState *interp = PyThreadState_Get()->interp;
    if (interp->modules == NULL)
        Py_FatalError("Python import machinery not initialized");
93 94 95 96 97 98 99 100 101
    if (PyType_Ready(&moduledef_type) < 0)
        return NULL;
    if (module->m_base.m_index == 0) {
        max_module_number++;
        Py_REFCNT(module) = 1;
        Py_TYPE(module) = &moduledef_type;
        module->m_base.m_index = max_module_number;
    }
    name = module->m_name;
102
    if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
103 104 105 106 107 108 109
        int err;
        err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
            "Python C API version mismatch for module %.100s: "
            "This Python has API version %d, module %.100s has version %d.",
             name,
             PYTHON_API_VERSION, name, module_api_version);
        if (err)
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
            return NULL;
    }
    /* Make sure name is fully qualified.

       This is a bit of a hack: when the shared library is loaded,
       the module name is "package.module", but the module calls
       PyModule_Create*() with just "module" for the name.  The shared
       library loader squirrels away the true name of the module in
       _Py_PackageContext, and PyModule_Create*() will substitute this
       (if the name actually matches).
    */
    if (_Py_PackageContext != NULL) {
        char *p = strrchr(_Py_PackageContext, '.');
        if (p != NULL && strcmp(module->m_name, p+1) == 0) {
            name = _Py_PackageContext;
            _Py_PackageContext = NULL;
        }
    }
    if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
        return NULL;

    if (module->m_size > 0) {
        m->md_state = PyMem_MALLOC(module->m_size);
        if (!m->md_state) {
            PyErr_NoMemory();
            Py_DECREF(m);
            return NULL;
        }
        memset(m->md_state, 0, module->m_size);
    }

    d = PyModule_GetDict((PyObject*)m);
    if (module->m_methods != NULL) {
        n = PyUnicode_FromString(name);
144 145
        if (n == NULL) {
            Py_DECREF(m);
146
            return NULL;
147
        }
148 149 150 151 152 153 154
        for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
            if ((ml->ml_flags & METH_CLASS) ||
                (ml->ml_flags & METH_STATIC)) {
                PyErr_SetString(PyExc_ValueError,
                                "module functions cannot set"
                                " METH_CLASS or METH_STATIC");
                Py_DECREF(n);
155
                Py_DECREF(m);
156 157 158 159 160
                return NULL;
            }
            v = PyCFunction_NewEx(ml, (PyObject*)m, n);
            if (v == NULL) {
                Py_DECREF(n);
161
                Py_DECREF(m);
162 163 164 165 166
                return NULL;
            }
            if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
                Py_DECREF(v);
                Py_DECREF(n);
167
                Py_DECREF(m);
168 169 170 171 172 173 174 175 176 177
                return NULL;
            }
            Py_DECREF(v);
        }
        Py_DECREF(n);
    }
    if (module->m_doc != NULL) {
        v = PyUnicode_FromString(module->m_doc);
        if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
            Py_XDECREF(v);
178
            Py_DECREF(m);
179 180 181 182 183 184
            return NULL;
        }
        Py_DECREF(v);
    }
    m->md_def = module;
    return (PyObject*)m;
185 186 187
}


188
PyObject *
189
PyModule_GetDict(PyObject *m)
Guido van Rossum's avatar
Guido van Rossum committed
190
{
191 192 193 194 195 196 197 198 199
    PyObject *d;
    if (!PyModule_Check(m)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    d = ((PyModuleObject *)m) -> md_dict;
    if (d == NULL)
        ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
    return d;
Guido van Rossum's avatar
Guido van Rossum committed
200 201
}

202 203
PyObject*
PyModule_GetNameObject(PyObject *m)
204
{
205
    PyObject *d;
206
    PyObject *name;
207 208 209 210 211 212
    if (!PyModule_Check(m)) {
        PyErr_BadArgument();
        return NULL;
    }
    d = ((PyModuleObject *)m)->md_dict;
    if (d == NULL ||
213 214
        (name = PyDict_GetItemString(d, "__name__")) == NULL ||
        !PyUnicode_Check(name))
215 216 217 218
    {
        PyErr_SetString(PyExc_SystemError, "nameless module");
        return NULL;
    }
219 220 221 222 223 224 225 226 227 228 229 230
    Py_INCREF(name);
    return name;
}

const char *
PyModule_GetName(PyObject *m)
{
    PyObject *name = PyModule_GetNameObject(m);
    if (name == NULL)
        return NULL;
    Py_DECREF(name);   /* module dict has still a reference */
    return _PyUnicode_AsString(name);
231 232
}

233 234
PyObject*
PyModule_GetFilenameObject(PyObject *m)
235
{
236 237 238 239 240 241 242 243 244 245 246 247 248 249
    PyObject *d;
    PyObject *fileobj;
    if (!PyModule_Check(m)) {
        PyErr_BadArgument();
        return NULL;
    }
    d = ((PyModuleObject *)m)->md_dict;
    if (d == NULL ||
        (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
        !PyUnicode_Check(fileobj))
    {
        PyErr_SetString(PyExc_SystemError, "module filename missing");
        return NULL;
    }
250
    Py_INCREF(fileobj);
251
    return fileobj;
252 253 254 255 256
}

const char *
PyModule_GetFilename(PyObject *m)
{
257
    PyObject *fileobj;
258 259
    char *utf8;
    fileobj = PyModule_GetFilenameObject(m);
260 261
    if (fileobj == NULL)
        return NULL;
262
    utf8 = _PyUnicode_AsString(fileobj);
263
    Py_DECREF(fileobj);   /* module dict has still a reference */
264
    return utf8;
265 266
}

267 268 269
PyModuleDef*
PyModule_GetDef(PyObject* m)
{
270 271 272 273 274
    if (!PyModule_Check(m)) {
        PyErr_BadArgument();
        return NULL;
    }
    return ((PyModuleObject *)m)->md_def;
275 276 277 278 279
}

void*
PyModule_GetState(PyObject* m)
{
280 281 282 283 284
    if (!PyModule_Check(m)) {
        PyErr_BadArgument();
        return NULL;
    }
    return ((PyModuleObject *)m)->md_state;
285 286
}

287
void
288
_PyModule_Clear(PyObject *m)
289
{
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    /* To make the execution order of destructors for global
       objects a bit more predictable, we first zap all objects
       whose name starts with a single underscore, before we clear
       the entire dictionary.  We zap them by replacing them with
       None, rather than deleting them from the dictionary, to
       avoid rehashing the dictionary (to some extent). */

    Py_ssize_t pos;
    PyObject *key, *value;
    PyObject *d;

    d = ((PyModuleObject *)m)->md_dict;
    if (d == NULL)
        return;

    /* First, clear only names starting with a single underscore */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
309
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
Martin v. Löwis's avatar
Martin v. Löwis committed
310
                PyUnicode_READ_CHAR(key, 1) != '_') {
311 312 313 314 315 316 317
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[1] %s\n", s);
                    else
                        PyErr_Clear();
                }
318 319 320 321 322 323 324 325 326
                PyDict_SetItem(d, key, Py_None);
            }
        }
    }

    /* Next, clear all names except for __builtins__ */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
Martin v. Löwis's avatar
Martin v. Löwis committed
327 328
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
                PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
329 330 331 332 333 334 335 336
            {
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[2] %s\n", s);
                    else
                        PyErr_Clear();
                }
337 338 339 340 341 342 343 344
                PyDict_SetItem(d, key, Py_None);
            }
        }
    }

    /* Note: we leave __builtins__ in place, so that destructors
       of non-global objects defined in this module can still use
       builtins, in particularly 'None'. */
345 346 347

}

Guido van Rossum's avatar
Guido van Rossum committed
348 349
/* Methods */

350
static int
351
module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
352
{
353 354 355 356 357 358 359 360 361 362 363 364
    static char *kwlist[] = {"name", "doc", NULL};
    PyObject *dict, *name = Py_None, *doc = Py_None;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
                                     kwlist, &name, &doc))
        return -1;
    dict = m->md_dict;
    if (dict == NULL) {
        dict = PyDict_New();
        if (dict == NULL)
            return -1;
        m->md_dict = dict;
    }
365
    if (module_init_dict(dict, name, doc) < 0)
366 367
        return -1;
    return 0;
368 369
}

Guido van Rossum's avatar
Guido van Rossum committed
370
static void
371
module_dealloc(PyModuleObject *m)
Guido van Rossum's avatar
Guido van Rossum committed
372
{
373 374 375 376
    PyObject_GC_UnTrack(m);
    if (m->md_def && m->md_def->m_free)
        m->md_def->m_free(m);
    if (m->md_dict != NULL) {
377
        _PyModule_Clear((PyObject *)m);
378 379 380 381 382
        Py_DECREF(m->md_dict);
    }
    if (m->md_state != NULL)
        PyMem_FREE(m->md_state);
    Py_TYPE(m)->tp_free((PyObject *)m);
Guido van Rossum's avatar
Guido van Rossum committed
383 384
}

385
static PyObject *
386
module_repr(PyModuleObject *m)
Guido van Rossum's avatar
Guido van Rossum committed
387
{
388
    PyObject *name, *filename, *repr, *loader = NULL;
389

390 391 392 393 394 395
    /* See if the module has an __loader__.  If it does, give the loader the
     * first shot at producing a repr for the module.
     */
    if (m->md_dict != NULL) {
        loader = PyDict_GetItemString(m->md_dict, "__loader__");
    }
396
    if (loader != NULL && loader != Py_None) {
397 398 399 400 401 402 403 404 405 406 407 408 409
        repr = PyObject_CallMethod(loader, "module_repr", "(O)",
                                   (PyObject *)m, NULL);
        if (repr == NULL) {
            PyErr_Clear();
        }
        else {
            return repr;
        }
    }
    /* __loader__.module_repr(m) did not provide us with a repr.  Next, see if
     * the module has an __file__.  If it doesn't then use repr(__loader__) if
     * it exists, otherwise, just use module.__name__.
     */
410
    name = PyModule_GetNameObject((PyObject *)m);
411 412
    if (name == NULL) {
        PyErr_Clear();
413 414 415
        name = PyUnicode_FromStringAndSize("?", 1);
        if (name == NULL)
            return NULL;
416
    }
417
    filename = PyModule_GetFilenameObject((PyObject *)m);
418 419
    if (filename == NULL) {
        PyErr_Clear();
420
        /* There's no m.__file__, so if there was a __loader__, use that in
421 422
         * the repr, otherwise, the only thing you can use is m.__name__
         */
423
        if (loader == NULL || loader == Py_None) {
424 425 426 427 428
            repr = PyUnicode_FromFormat("<module %R>", name);
        }
        else {
            repr = PyUnicode_FromFormat("<module %R (%R)>", name, loader);
        }
429
    }
430
    /* Finally, use m.__file__ */
431 432 433
    else {
        repr = PyUnicode_FromFormat("<module %R from %R>", name, filename);
        Py_DECREF(filename);
434
    }
435
    Py_DECREF(name);
436
    return repr;
Guido van Rossum's avatar
Guido van Rossum committed
437 438
}

439 440 441
static int
module_traverse(PyModuleObject *m, visitproc visit, void *arg)
{
442 443 444 445 446 447 448
    if (m->md_def && m->md_def->m_traverse) {
        int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
        if (res)
            return res;
    }
    Py_VISIT(m->md_dict);
    return 0;
449 450
}

451 452 453
static int
module_clear(PyModuleObject *m)
{
454 455 456 457 458 459 460
    if (m->md_def && m->md_def->m_clear) {
        int res = m->md_def->m_clear((PyObject*)m);
        if (res)
            return res;
    }
    Py_CLEAR(m->md_dict);
    return 0;
461
}
462

463 464 465
static PyObject *
module_dir(PyObject *self, PyObject *args)
{
466
    _Py_IDENTIFIER(__dict__);
467
    PyObject *result = NULL;
468
    PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    if (dict != NULL) {
        if (PyDict_Check(dict))
            result = PyDict_Keys(dict);
        else {
            const char *name = PyModule_GetName(self);
            if (name)
                PyErr_Format(PyExc_TypeError,
                             "%.200s.__dict__ is not a dictionary",
                             name);
        }
    }

    Py_XDECREF(dict);
    return result;
}

static PyMethodDef module_methods[] = {
    {"__dir__", module_dir, METH_NOARGS,
488
     PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
489 490 491
    {0}
};

492

493
PyDoc_STRVAR(module_doc,
494 495 496
"module(name[, doc])\n\
\n\
Create a module object.\n\
497
The name must be a string; the optional doc argument can have any type.");
498

499
PyTypeObject PyModule_Type = {
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "module",                                   /* tp_name */
    sizeof(PyModuleObject),                     /* tp_size */
    0,                                          /* tp_itemsize */
    (destructor)module_dealloc,                 /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    (reprfunc)module_repr,                      /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    PyObject_GenericSetAttr,                    /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
    module_doc,                                 /* tp_doc */
    (traverseproc)module_traverse,              /* tp_traverse */
    (inquiry)module_clear,                      /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
528
    module_methods,                             /* tp_methods */
529 530 531 532 533 534 535 536 537 538 539
    module_members,                             /* tp_members */
    0,                                          /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    offsetof(PyModuleObject, md_dict),          /* tp_dictoffset */
    (initproc)module_init,                      /* tp_init */
    PyType_GenericAlloc,                        /* tp_alloc */
    PyType_GenericNew,                          /* tp_new */
    PyObject_GC_Del,                            /* tp_free */
Guido van Rossum's avatar
Guido van Rossum committed
540
};