source: trunk/essentials/dev-lang/python/Python/import.c

Last change on this file was 3364, checked in by bird, 18 years ago

In progress...

File size: 77.1 KB
Line 
1
2/* Module definition and import implementation */
3
4#include "Python.h"
5
6#include "Python-ast.h"
7#include "pyarena.h"
8#include "pythonrun.h"
9#include "errcode.h"
10#include "marshal.h"
11#include "code.h"
12#include "compile.h"
13#include "eval.h"
14#include "osdefs.h"
15#include "importdl.h"
16
17#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
20#ifdef __cplusplus
21extern "C" {
22#endif
23
24extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* In getmtime.c */
26
27/* Magic word to reject .pyc files generated by other Python versions.
28 It should change for each incompatible change to the bytecode.
29
30 The value of CR and LF is incorporated so if you ever read or write
31 a .pyc file in text mode the magic number will be wrong; also, the
32 Apple MPW compiler swaps their values, botching string constants.
33
34 The magic numbers must be spaced apart atleast 2 values, as the
35 -U interpeter flag will cause MAGIC+1 being used. They have been
36 odd numbers for some time now.
37
38 There were a variety of old schemes for setting the magic number.
39 The current working scheme is to increment the previous value by
40 10.
41
42 Known values:
43 Python 1.5: 20121
44 Python 1.5.1: 20121
45 Python 1.5.2: 20121
46 Python 1.6: 50428
47 Python 2.0: 50823
48 Python 2.0.1: 50823
49 Python 2.1: 60202
50 Python 2.1.1: 60202
51 Python 2.1.2: 60202
52 Python 2.2: 60717
53 Python 2.3a0: 62011
54 Python 2.3a0: 62021
55 Python 2.3a0: 62011 (!)
56 Python 2.4a0: 62041
57 Python 2.4a3: 62051
58 Python 2.4b1: 62061
59 Python 2.5a0: 62071
60 Python 2.5a0: 62081 (ast-branch)
61 Python 2.5a0: 62091 (with)
62 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
63 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
64 Python 2.5b3: 62111 (fix wrong code: x += yield)
65 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
66 storing constants that should have been removed)
67 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
68.
69*/
70#define MAGIC (62131 | ((long)'\r'<<16) | ((long)'\n'<<24))
71
72/* Magic word as global; note that _PyImport_Init() can change the
73 value of this global to accommodate for alterations of how the
74 compiler works which are enabled by command line switches. */
75static long pyc_magic = MAGIC;
76
77/* See _PyImport_FixupExtension() below */
78static PyObject *extensions = NULL;
79
80/* This table is defined in config.c: */
81extern struct _inittab _PyImport_Inittab[];
82
83struct _inittab *PyImport_Inittab = _PyImport_Inittab;
84
85/* these tables define the module suffixes that Python recognizes */
86struct filedescr * _PyImport_Filetab = NULL;
87
88#ifdef RISCOS
89static const struct filedescr _PyImport_StandardFiletab[] = {
90 {"/py", "U", PY_SOURCE},
91 {"/pyc", "rb", PY_COMPILED},
92 {0, 0}
93};
94#else
95static const struct filedescr _PyImport_StandardFiletab[] = {
96 {".py", "U", PY_SOURCE},
97#ifdef MS_WINDOWS
98 {".pyw", "U", PY_SOURCE},
99#endif
100 {".pyc", "rb", PY_COMPILED},
101 {0, 0}
102};
103#endif
104
105static PyTypeObject NullImporterType; /* Forward reference */
106
107/* Initialize things */
108
109void
110_PyImport_Init(void)
111{
112 const struct filedescr *scan;
113 struct filedescr *filetab;
114 int countD = 0;
115 int countS = 0;
116
117 /* prepare _PyImport_Filetab: copy entries from
118 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
119 */
120 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
121 ++countD;
122 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
123 ++countS;
124 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
125 if (filetab == NULL)
126 Py_FatalError("Can't initialize import file table.");
127 memcpy(filetab, _PyImport_DynLoadFiletab,
128 countD * sizeof(struct filedescr));
129 memcpy(filetab + countD, _PyImport_StandardFiletab,
130 countS * sizeof(struct filedescr));
131 filetab[countD + countS].suffix = NULL;
132
133 _PyImport_Filetab = filetab;
134
135 if (Py_OptimizeFlag) {
136 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
137 for (; filetab->suffix != NULL; filetab++) {
138#ifndef RISCOS
139 if (strcmp(filetab->suffix, ".pyc") == 0)
140 filetab->suffix = ".pyo";
141#else
142 if (strcmp(filetab->suffix, "/pyc") == 0)
143 filetab->suffix = "/pyo";
144#endif
145 }
146 }
147
148 if (Py_UnicodeFlag) {
149 /* Fix the pyc_magic so that byte compiled code created
150 using the all-Unicode method doesn't interfere with
151 code created in normal operation mode. */
152 pyc_magic = MAGIC + 1;
153 }
154}
155
156void
157_PyImportHooks_Init(void)
158{
159 PyObject *v, *path_hooks = NULL, *zimpimport;
160 int err = 0;
161
162 /* adding sys.path_hooks and sys.path_importer_cache, setting up
163 zipimport */
164 if (PyType_Ready(&NullImporterType) < 0)
165 goto error;
166
167 if (Py_VerboseFlag)
168 PySys_WriteStderr("# installing zipimport hook\n");
169
170 v = PyList_New(0);
171 if (v == NULL)
172 goto error;
173 err = PySys_SetObject("meta_path", v);
174 Py_DECREF(v);
175 if (err)
176 goto error;
177 v = PyDict_New();
178 if (v == NULL)
179 goto error;
180 err = PySys_SetObject("path_importer_cache", v);
181 Py_DECREF(v);
182 if (err)
183 goto error;
184 path_hooks = PyList_New(0);
185 if (path_hooks == NULL)
186 goto error;
187 err = PySys_SetObject("path_hooks", path_hooks);
188 if (err) {
189 error:
190 PyErr_Print();
191 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
192 "path_importer_cache, or NullImporter failed"
193 );
194 }
195
196 zimpimport = PyImport_ImportModule("zipimport");
197 if (zimpimport == NULL) {
198 PyErr_Clear(); /* No zip import module -- okay */
199 if (Py_VerboseFlag)
200 PySys_WriteStderr("# can't import zipimport\n");
201 }
202 else {
203 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
204 "zipimporter");
205 Py_DECREF(zimpimport);
206 if (zipimporter == NULL) {
207 PyErr_Clear(); /* No zipimporter object -- okay */
208 if (Py_VerboseFlag)
209 PySys_WriteStderr(
210 "# can't import zipimport.zipimporter\n");
211 }
212 else {
213 /* sys.path_hooks.append(zipimporter) */
214 err = PyList_Append(path_hooks, zipimporter);
215 Py_DECREF(zipimporter);
216 if (err)
217 goto error;
218 if (Py_VerboseFlag)
219 PySys_WriteStderr(
220 "# installed zipimport hook\n");
221 }
222 }
223 Py_DECREF(path_hooks);
224}
225
226void
227_PyImport_Fini(void)
228{
229 Py_XDECREF(extensions);
230 extensions = NULL;
231 PyMem_DEL(_PyImport_Filetab);
232 _PyImport_Filetab = NULL;
233}
234
235
236/* Locking primitives to prevent parallel imports of the same module
237 in different threads to return with a partially loaded module.
238 These calls are serialized by the global interpreter lock. */
239
240#ifdef WITH_THREAD
241
242#include "pythread.h"
243
244static PyThread_type_lock import_lock = 0;
245static long import_lock_thread = -1;
246static int import_lock_level = 0;
247
248static void
249lock_import(void)
250{
251 long me = PyThread_get_thread_ident();
252 if (me == -1)
253 return; /* Too bad */
254 if (import_lock == NULL) {
255 import_lock = PyThread_allocate_lock();
256 if (import_lock == NULL)
257 return; /* Nothing much we can do. */
258 }
259 if (import_lock_thread == me) {
260 import_lock_level++;
261 return;
262 }
263 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
264 {
265 PyThreadState *tstate = PyEval_SaveThread();
266 PyThread_acquire_lock(import_lock, 1);
267 PyEval_RestoreThread(tstate);
268 }
269 import_lock_thread = me;
270 import_lock_level = 1;
271}
272
273static int
274unlock_import(void)
275{
276 long me = PyThread_get_thread_ident();
277 if (me == -1 || import_lock == NULL)
278 return 0; /* Too bad */
279 if (import_lock_thread != me)
280 return -1;
281 import_lock_level--;
282 if (import_lock_level == 0) {
283 import_lock_thread = -1;
284 PyThread_release_lock(import_lock);
285 }
286 return 1;
287}
288
289/* This function is called from PyOS_AfterFork to ensure that newly
290 created child processes do not share locks with the parent. */
291
292void
293_PyImport_ReInitLock(void)
294{
295#ifdef _AIX
296 if (import_lock != NULL)
297 import_lock = PyThread_allocate_lock();
298#endif
299}
300
301#else
302
303#define lock_import()
304#define unlock_import() 0
305
306#endif
307
308static PyObject *
309imp_lock_held(PyObject *self, PyObject *noargs)
310{
311#ifdef WITH_THREAD
312 return PyBool_FromLong(import_lock_thread != -1);
313#else
314 return PyBool_FromLong(0);
315#endif
316}
317
318static PyObject *
319imp_acquire_lock(PyObject *self, PyObject *noargs)
320{
321#ifdef WITH_THREAD
322 lock_import();
323#endif
324 Py_INCREF(Py_None);
325 return Py_None;
326}
327
328static PyObject *
329imp_release_lock(PyObject *self, PyObject *noargs)
330{
331#ifdef WITH_THREAD
332 if (unlock_import() < 0) {
333 PyErr_SetString(PyExc_RuntimeError,
334 "not holding the import lock");
335 return NULL;
336 }
337#endif
338 Py_INCREF(Py_None);
339 return Py_None;
340}
341
342/* Helper for sys */
343
344PyObject *
345PyImport_GetModuleDict(void)
346{
347 PyInterpreterState *interp = PyThreadState_GET()->interp;
348 if (interp->modules == NULL)
349 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
350 return interp->modules;
351}
352
353
354/* List of names to clear in sys */
355static char* sys_deletes[] = {
356 "path", "argv", "ps1", "ps2", "exitfunc",
357 "exc_type", "exc_value", "exc_traceback",
358 "last_type", "last_value", "last_traceback",
359 "path_hooks", "path_importer_cache", "meta_path",
360 NULL
361};
362
363static char* sys_files[] = {
364 "stdin", "__stdin__",
365 "stdout", "__stdout__",
366 "stderr", "__stderr__",
367 NULL
368};
369
370
371/* Un-initialize things, as good as we can */
372
373void
374PyImport_Cleanup(void)
375{
376 Py_ssize_t pos, ndone;
377 char *name;
378 PyObject *key, *value, *dict;
379 PyInterpreterState *interp = PyThreadState_GET()->interp;
380 PyObject *modules = interp->modules;
381
382 if (modules == NULL)
383 return; /* Already done */
384
385 /* Delete some special variables first. These are common
386 places where user values hide and people complain when their
387 destructors fail. Since the modules containing them are
388 deleted *last* of all, they would come too late in the normal
389 destruction order. Sigh. */
390
391 value = PyDict_GetItemString(modules, "__builtin__");
392 if (value != NULL && PyModule_Check(value)) {
393 dict = PyModule_GetDict(value);
394 if (Py_VerboseFlag)
395 PySys_WriteStderr("# clear __builtin__._\n");
396 PyDict_SetItemString(dict, "_", Py_None);
397 }
398 value = PyDict_GetItemString(modules, "sys");
399 if (value != NULL && PyModule_Check(value)) {
400 char **p;
401 PyObject *v;
402 dict = PyModule_GetDict(value);
403 for (p = sys_deletes; *p != NULL; p++) {
404 if (Py_VerboseFlag)
405 PySys_WriteStderr("# clear sys.%s\n", *p);
406 PyDict_SetItemString(dict, *p, Py_None);
407 }
408 for (p = sys_files; *p != NULL; p+=2) {
409 if (Py_VerboseFlag)
410 PySys_WriteStderr("# restore sys.%s\n", *p);
411 v = PyDict_GetItemString(dict, *(p+1));
412 if (v == NULL)
413 v = Py_None;
414 PyDict_SetItemString(dict, *p, v);
415 }
416 }
417
418 /* First, delete __main__ */
419 value = PyDict_GetItemString(modules, "__main__");
420 if (value != NULL && PyModule_Check(value)) {
421 if (Py_VerboseFlag)
422 PySys_WriteStderr("# cleanup __main__\n");
423 _PyModule_Clear(value);
424 PyDict_SetItemString(modules, "__main__", Py_None);
425 }
426
427 /* The special treatment of __builtin__ here is because even
428 when it's not referenced as a module, its dictionary is
429 referenced by almost every module's __builtins__. Since
430 deleting a module clears its dictionary (even if there are
431 references left to it), we need to delete the __builtin__
432 module last. Likewise, we don't delete sys until the very
433 end because it is implicitly referenced (e.g. by print).
434
435 Also note that we 'delete' modules by replacing their entry
436 in the modules dict with None, rather than really deleting
437 them; this avoids a rehash of the modules dictionary and
438 also marks them as "non existent" so they won't be
439 re-imported. */
440
441 /* Next, repeatedly delete modules with a reference count of
442 one (skipping __builtin__ and sys) and delete them */
443 do {
444 ndone = 0;
445 pos = 0;
446 while (PyDict_Next(modules, &pos, &key, &value)) {
447 if (value->ob_refcnt != 1)
448 continue;
449 if (PyString_Check(key) && PyModule_Check(value)) {
450 name = PyString_AS_STRING(key);
451 if (strcmp(name, "__builtin__") == 0)
452 continue;
453 if (strcmp(name, "sys") == 0)
454 continue;
455 if (Py_VerboseFlag)
456 PySys_WriteStderr(
457 "# cleanup[1] %s\n", name);
458 _PyModule_Clear(value);
459 PyDict_SetItem(modules, key, Py_None);
460 ndone++;
461 }
462 }
463 } while (ndone > 0);
464
465 /* Next, delete all modules (still skipping __builtin__ and sys) */
466 pos = 0;
467 while (PyDict_Next(modules, &pos, &key, &value)) {
468 if (PyString_Check(key) && PyModule_Check(value)) {
469 name = PyString_AS_STRING(key);
470 if (strcmp(name, "__builtin__") == 0)
471 continue;
472 if (strcmp(name, "sys") == 0)
473 continue;
474 if (Py_VerboseFlag)
475 PySys_WriteStderr("# cleanup[2] %s\n", name);
476 _PyModule_Clear(value);
477 PyDict_SetItem(modules, key, Py_None);
478 }
479 }
480
481 /* Next, delete sys and __builtin__ (in that order) */
482 value = PyDict_GetItemString(modules, "sys");
483 if (value != NULL && PyModule_Check(value)) {
484 if (Py_VerboseFlag)
485 PySys_WriteStderr("# cleanup sys\n");
486 _PyModule_Clear(value);
487 PyDict_SetItemString(modules, "sys", Py_None);
488 }
489 value = PyDict_GetItemString(modules, "__builtin__");
490 if (value != NULL && PyModule_Check(value)) {
491 if (Py_VerboseFlag)
492 PySys_WriteStderr("# cleanup __builtin__\n");
493 _PyModule_Clear(value);
494 PyDict_SetItemString(modules, "__builtin__", Py_None);
495 }
496
497 /* Finally, clear and delete the modules directory */
498 PyDict_Clear(modules);
499 interp->modules = NULL;
500 Py_DECREF(modules);
501}
502
503
504/* Helper for pythonrun.c -- return magic number */
505
506long
507PyImport_GetMagicNumber(void)
508{
509 return pyc_magic;
510}
511
512
513/* Magic for extension modules (built-in as well as dynamically
514 loaded). To prevent initializing an extension module more than
515 once, we keep a static dictionary 'extensions' keyed by module name
516 (for built-in modules) or by filename (for dynamically loaded
517 modules), containing these modules. A copy of the module's
518 dictionary is stored by calling _PyImport_FixupExtension()
519 immediately after the module initialization function succeeds. A
520 copy can be retrieved from there by calling
521 _PyImport_FindExtension(). */
522
523PyObject *
524_PyImport_FixupExtension(char *name, char *filename)
525{
526 PyObject *modules, *mod, *dict, *copy;
527 if (extensions == NULL) {
528 extensions = PyDict_New();
529 if (extensions == NULL)
530 return NULL;
531 }
532 modules = PyImport_GetModuleDict();
533 mod = PyDict_GetItemString(modules, name);
534 if (mod == NULL || !PyModule_Check(mod)) {
535 PyErr_Format(PyExc_SystemError,
536 "_PyImport_FixupExtension: module %.200s not loaded", name);
537 return NULL;
538 }
539 dict = PyModule_GetDict(mod);
540 if (dict == NULL)
541 return NULL;
542 copy = PyDict_Copy(dict);
543 if (copy == NULL)
544 return NULL;
545 PyDict_SetItemString(extensions, filename, copy);
546 Py_DECREF(copy);
547 return copy;
548}
549
550PyObject *
551_PyImport_FindExtension(char *name, char *filename)
552{
553 PyObject *dict, *mod, *mdict;
554 if (extensions == NULL)
555 return NULL;
556 dict = PyDict_GetItemString(extensions, filename);
557 if (dict == NULL)
558 return NULL;
559 mod = PyImport_AddModule(name);
560 if (mod == NULL)
561 return NULL;
562 mdict = PyModule_GetDict(mod);
563 if (mdict == NULL)
564 return NULL;
565 if (PyDict_Update(mdict, dict))
566 return NULL;
567 if (Py_VerboseFlag)
568 PySys_WriteStderr("import %s # previously loaded (%s)\n",
569 name, filename);
570 return mod;
571}
572
573
574/* Get the module object corresponding to a module name.
575 First check the modules dictionary if there's one there,
576 if not, create a new one and insert it in the modules dictionary.
577 Because the former action is most common, THIS DOES NOT RETURN A
578 'NEW' REFERENCE! */
579
580PyObject *
581PyImport_AddModule(const char *name)
582{
583 PyObject *modules = PyImport_GetModuleDict();
584 PyObject *m;
585
586 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
587 PyModule_Check(m))
588 return m;
589 m = PyModule_New(name);
590 if (m == NULL)
591 return NULL;
592 if (PyDict_SetItemString(modules, name, m) != 0) {
593 Py_DECREF(m);
594 return NULL;
595 }
596 Py_DECREF(m); /* Yes, it still exists, in modules! */
597
598 return m;
599}
600
601/* Remove name from sys.modules, if it's there. */
602static void
603_RemoveModule(const char *name)
604{
605 PyObject *modules = PyImport_GetModuleDict();
606 if (PyDict_GetItemString(modules, name) == NULL)
607 return;
608 if (PyDict_DelItemString(modules, name) < 0)
609 Py_FatalError("import: deleting existing key in"
610 "sys.modules failed");
611}
612
613/* Execute a code object in a module and return the module object
614 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
615 * removed from sys.modules, to avoid leaving damaged module objects
616 * in sys.modules. The caller may wish to restore the original
617 * module object (if any) in this case; PyImport_ReloadModule is an
618 * example.
619 */
620PyObject *
621PyImport_ExecCodeModule(char *name, PyObject *co)
622{
623 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
624}
625
626PyObject *
627PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
628{
629 PyObject *modules = PyImport_GetModuleDict();
630 PyObject *m, *d, *v;
631
632 m = PyImport_AddModule(name);
633 if (m == NULL)
634 return NULL;
635 /* If the module is being reloaded, we get the old module back
636 and re-use its dict to exec the new code. */
637 d = PyModule_GetDict(m);
638 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
639 if (PyDict_SetItemString(d, "__builtins__",
640 PyEval_GetBuiltins()) != 0)
641 goto error;
642 }
643 /* Remember the filename as the __file__ attribute */
644 v = NULL;
645 if (pathname != NULL) {
646 v = PyString_FromString(pathname);
647 if (v == NULL)
648 PyErr_Clear();
649 }
650 if (v == NULL) {
651 v = ((PyCodeObject *)co)->co_filename;
652 Py_INCREF(v);
653 }
654 if (PyDict_SetItemString(d, "__file__", v) != 0)
655 PyErr_Clear(); /* Not important enough to report */
656 Py_DECREF(v);
657
658 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
659 if (v == NULL)
660 goto error;
661 Py_DECREF(v);
662
663 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
664 PyErr_Format(PyExc_ImportError,
665 "Loaded module %.200s not found in sys.modules",
666 name);
667 return NULL;
668 }
669
670 Py_INCREF(m);
671
672 return m;
673
674 error:
675 _RemoveModule(name);
676 return NULL;
677}
678
679
680/* Given a pathname for a Python source file, fill a buffer with the
681 pathname for the corresponding compiled file. Return the pathname
682 for the compiled file, or NULL if there's no space in the buffer.
683 Doesn't set an exception. */
684
685static char *
686make_compiled_pathname(char *pathname, char *buf, size_t buflen)
687{
688 size_t len = strlen(pathname);
689 if (len+2 > buflen)
690 return NULL;
691
692#ifdef MS_WINDOWS
693 /* Treat .pyw as if it were .py. The case of ".pyw" must match
694 that used in _PyImport_StandardFiletab. */
695 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
696 --len; /* pretend 'w' isn't there */
697#endif
698 memcpy(buf, pathname, len);
699 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
700 buf[len+1] = '\0';
701
702 return buf;
703}
704
705
706/* Given a pathname for a Python source file, its time of last
707 modification, and a pathname for a compiled file, check whether the
708 compiled file represents the same version of the source. If so,
709 return a FILE pointer for the compiled file, positioned just after
710 the header; if not, return NULL.
711 Doesn't set an exception. */
712
713static FILE *
714check_compiled_module(char *pathname, time_t mtime, char *cpathname)
715{
716 FILE *fp;
717 long magic;
718 long pyc_mtime;
719
720 fp = fopen(cpathname, "rb");
721 if (fp == NULL)
722 return NULL;
723 magic = PyMarshal_ReadLongFromFile(fp);
724 if (magic != pyc_magic) {
725 if (Py_VerboseFlag)
726 PySys_WriteStderr("# %s has bad magic\n", cpathname);
727 fclose(fp);
728 return NULL;
729 }
730 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
731 if (pyc_mtime != mtime) {
732 if (Py_VerboseFlag)
733 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
734 fclose(fp);
735 return NULL;
736 }
737 if (Py_VerboseFlag)
738 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
739 return fp;
740}
741
742
743/* Read a code object from a file and check it for validity */
744
745static PyCodeObject *
746read_compiled_module(char *cpathname, FILE *fp)
747{
748 PyObject *co;
749
750 co = PyMarshal_ReadLastObjectFromFile(fp);
751 if (co == NULL)
752 return NULL;
753 if (!PyCode_Check(co)) {
754 PyErr_Format(PyExc_ImportError,
755 "Non-code object in %.200s", cpathname);
756 Py_DECREF(co);
757 return NULL;
758 }
759 return (PyCodeObject *)co;
760}
761
762
763/* Load a module from a compiled file, execute it, and return its
764 module object WITH INCREMENTED REFERENCE COUNT */
765
766static PyObject *
767load_compiled_module(char *name, char *cpathname, FILE *fp)
768{
769 long magic;
770 PyCodeObject *co;
771 PyObject *m;
772
773 magic = PyMarshal_ReadLongFromFile(fp);
774 if (magic != pyc_magic) {
775 PyErr_Format(PyExc_ImportError,
776 "Bad magic number in %.200s", cpathname);
777 return NULL;
778 }
779 (void) PyMarshal_ReadLongFromFile(fp);
780 co = read_compiled_module(cpathname, fp);
781 if (co == NULL)
782 return NULL;
783 if (Py_VerboseFlag)
784 PySys_WriteStderr("import %s # precompiled from %s\n",
785 name, cpathname);
786 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
787 Py_DECREF(co);
788
789 return m;
790}
791
792/* Parse a source file and return the corresponding code object */
793
794static PyCodeObject *
795parse_source_module(const char *pathname, FILE *fp)
796{
797 PyCodeObject *co = NULL;
798 mod_ty mod;
799 PyArena *arena = PyArena_New();
800 if (arena == NULL)
801 return NULL;
802
803 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
804 NULL, arena);
805 if (mod) {
806 co = PyAST_Compile(mod, pathname, NULL, arena);
807 }
808 PyArena_Free(arena);
809 return co;
810}
811
812
813/* Helper to open a bytecode file for writing in exclusive mode */
814
815static FILE *
816open_exclusive(char *filename)
817{
818#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
819 /* Use O_EXCL to avoid a race condition when another process tries to
820 write the same file. When that happens, our open() call fails,
821 which is just fine (since it's only a cache).
822 XXX If the file exists and is writable but the directory is not
823 writable, the file will never be written. Oh well.
824 */
825 int fd;
826 (void) unlink(filename);
827 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
828#ifdef O_BINARY
829 |O_BINARY /* necessary for Windows */
830#endif
831#ifdef __VMS
832 , 0666, "ctxt=bin", "shr=nil"
833#else
834 , 0666
835#endif
836 );
837 if (fd < 0)
838 return NULL;
839 return fdopen(fd, "wb");
840#else
841 /* Best we can do -- on Windows this can't happen anyway */
842 return fopen(filename, "wb");
843#endif
844}
845
846
847/* Write a compiled module to a file, placing the time of last
848 modification of its source into the header.
849 Errors are ignored, if a write error occurs an attempt is made to
850 remove the file. */
851
852static void
853write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
854{
855 FILE *fp;
856
857 fp = open_exclusive(cpathname);
858 if (fp == NULL) {
859 if (Py_VerboseFlag)
860 PySys_WriteStderr(
861 "# can't create %s\n", cpathname);
862 return;
863 }
864 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
865 /* First write a 0 for mtime */
866 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
867 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
868 if (fflush(fp) != 0 || ferror(fp)) {
869 if (Py_VerboseFlag)
870 PySys_WriteStderr("# can't write %s\n", cpathname);
871 /* Don't keep partial file */
872 fclose(fp);
873 (void) unlink(cpathname);
874 return;
875 }
876 /* Now write the true mtime */
877 fseek(fp, 4L, 0);
878 assert(mtime < LONG_MAX);
879 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
880 fflush(fp);
881 fclose(fp);
882 if (Py_VerboseFlag)
883 PySys_WriteStderr("# wrote %s\n", cpathname);
884}
885
886
887/* Load a source module from a given file and return its module
888 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
889 byte-compiled file, use that instead. */
890
891static PyObject *
892load_source_module(char *name, char *pathname, FILE *fp)
893{
894 time_t mtime;
895 FILE *fpc;
896 char buf[MAXPATHLEN+1];
897 char *cpathname;
898 PyCodeObject *co;
899 PyObject *m;
900
901 mtime = PyOS_GetLastModificationTime(pathname, fp);
902 if (mtime == (time_t)(-1)) {
903 PyErr_Format(PyExc_RuntimeError,
904 "unable to get modification time from '%s'",
905 pathname);
906 return NULL;
907 }
908#if SIZEOF_TIME_T > 4
909 /* Python's .pyc timestamp handling presumes that the timestamp fits
910 in 4 bytes. This will be fine until sometime in the year 2038,
911 when a 4-byte signed time_t will overflow.
912 */
913 if (mtime >> 32) {
914 PyErr_SetString(PyExc_OverflowError,
915 "modification time overflows a 4 byte field");
916 return NULL;
917 }
918#endif
919 cpathname = make_compiled_pathname(pathname, buf,
920 (size_t)MAXPATHLEN + 1);
921 if (cpathname != NULL &&
922 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
923 co = read_compiled_module(cpathname, fpc);
924 fclose(fpc);
925 if (co == NULL)
926 return NULL;
927 if (Py_VerboseFlag)
928 PySys_WriteStderr("import %s # precompiled from %s\n",
929 name, cpathname);
930 pathname = cpathname;
931 }
932 else {
933 co = parse_source_module(pathname, fp);
934 if (co == NULL)
935 return NULL;
936 if (Py_VerboseFlag)
937 PySys_WriteStderr("import %s # from %s\n",
938 name, pathname);
939 if (cpathname)
940 write_compiled_module(co, cpathname, mtime);
941 }
942 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
943 Py_DECREF(co);
944
945 return m;
946}
947
948
949/* Forward */
950static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
951static struct filedescr *find_module(char *, char *, PyObject *,
952 char *, size_t, FILE **, PyObject **);
953static struct _frozen *find_frozen(char *name);
954
955/* Load a package and return its module object WITH INCREMENTED
956 REFERENCE COUNT */
957
958static PyObject *
959load_package(char *name, char *pathname)
960{
961 PyObject *m, *d;
962 PyObject *file = NULL;
963 PyObject *path = NULL;
964 int err;
965 char buf[MAXPATHLEN+1];
966 FILE *fp = NULL;
967 struct filedescr *fdp;
968
969 m = PyImport_AddModule(name);
970 if (m == NULL)
971 return NULL;
972 if (Py_VerboseFlag)
973 PySys_WriteStderr("import %s # directory %s\n",
974 name, pathname);
975 d = PyModule_GetDict(m);
976 file = PyString_FromString(pathname);
977 if (file == NULL)
978 goto error;
979 path = Py_BuildValue("[O]", file);
980 if (path == NULL)
981 goto error;
982 err = PyDict_SetItemString(d, "__file__", file);
983 if (err == 0)
984 err = PyDict_SetItemString(d, "__path__", path);
985 if (err != 0)
986 goto error;
987 buf[0] = '\0';
988 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
989 if (fdp == NULL) {
990 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
991 PyErr_Clear();
992 Py_INCREF(m);
993 }
994 else
995 m = NULL;
996 goto cleanup;
997 }
998 m = load_module(name, fp, buf, fdp->type, NULL);
999 if (fp != NULL)
1000 fclose(fp);
1001 goto cleanup;
1002
1003 error:
1004 m = NULL;
1005 cleanup:
1006 Py_XDECREF(path);
1007 Py_XDECREF(file);
1008 return m;
1009}
1010
1011
1012/* Helper to test for built-in module */
1013
1014static int
1015is_builtin(char *name)
1016{
1017 int i;
1018 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1019 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1020 if (PyImport_Inittab[i].initfunc == NULL)
1021 return -1;
1022 else
1023 return 1;
1024 }
1025 }
1026 return 0;
1027}
1028
1029
1030/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1031 possibly by fetching it from the path_importer_cache dict. If it
1032 wasn't yet cached, traverse path_hooks until it a hook is found
1033 that can handle the path item. Return None if no hook could;
1034 this tells our caller it should fall back to the builtin
1035 import mechanism. Cache the result in path_importer_cache.
1036 Returns a borrowed reference. */
1037
1038static PyObject *
1039get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1040 PyObject *p)
1041{
1042 PyObject *importer;
1043 Py_ssize_t j, nhooks;
1044
1045 /* These conditions are the caller's responsibility: */
1046 assert(PyList_Check(path_hooks));
1047 assert(PyDict_Check(path_importer_cache));
1048
1049 nhooks = PyList_Size(path_hooks);
1050 if (nhooks < 0)
1051 return NULL; /* Shouldn't happen */
1052
1053 importer = PyDict_GetItem(path_importer_cache, p);
1054 if (importer != NULL)
1055 return importer;
1056
1057 /* set path_importer_cache[p] to None to avoid recursion */
1058 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1059 return NULL;
1060
1061 for (j = 0; j < nhooks; j++) {
1062 PyObject *hook = PyList_GetItem(path_hooks, j);
1063 if (hook == NULL)
1064 return NULL;
1065 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1066 if (importer != NULL)
1067 break;
1068
1069 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1070 return NULL;
1071 }
1072 PyErr_Clear();
1073 }
1074 if (importer == NULL) {
1075 importer = PyObject_CallFunctionObjArgs(
1076 (PyObject *)&NullImporterType, p, NULL
1077 );
1078 if (importer == NULL) {
1079 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1080 PyErr_Clear();
1081 return Py_None;
1082 }
1083 }
1084 }
1085 if (importer != NULL) {
1086 int err = PyDict_SetItem(path_importer_cache, p, importer);
1087 Py_DECREF(importer);
1088 if (err != 0)
1089 return NULL;
1090 }
1091 return importer;
1092}
1093
1094/* Search the path (default sys.path) for a module. Return the
1095 corresponding filedescr struct, and (via return arguments) the
1096 pathname and an open file. Return NULL if the module is not found. */
1097
1098#ifdef MS_COREDLL
1099extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1100 char *, Py_ssize_t);
1101#endif
1102
1103static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
1104static int find_init_module(char *); /* Forward */
1105static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1106
1107static struct filedescr *
1108find_module(char *fullname, char *subname, PyObject *path, char *buf,
1109 size_t buflen, FILE **p_fp, PyObject **p_loader)
1110{
1111 Py_ssize_t i, npath;
1112 size_t len, namelen;
1113 struct filedescr *fdp = NULL;
1114 char *filemode;
1115 FILE *fp = NULL;
1116 PyObject *path_hooks, *path_importer_cache;
1117#ifndef RISCOS
1118 struct stat statbuf;
1119#endif
1120 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1121 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1122 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1123 char name[MAXPATHLEN+1];
1124#if defined(PYOS_OS2)
1125 size_t saved_len;
1126 size_t saved_namelen;
1127 char *saved_buf = NULL;
1128#endif
1129 if (p_loader != NULL)
1130 *p_loader = NULL;
1131
1132 if (strlen(subname) > MAXPATHLEN) {
1133 PyErr_SetString(PyExc_OverflowError,
1134 "module name is too long");
1135 return NULL;
1136 }
1137 strcpy(name, subname);
1138
1139 /* sys.meta_path import hook */
1140 if (p_loader != NULL) {
1141 PyObject *meta_path;
1142
1143 meta_path = PySys_GetObject("meta_path");
1144 if (meta_path == NULL || !PyList_Check(meta_path)) {
1145 PyErr_SetString(PyExc_ImportError,
1146 "sys.meta_path must be a list of "
1147 "import hooks");
1148 return NULL;
1149 }
1150 Py_INCREF(meta_path); /* zap guard */
1151 npath = PyList_Size(meta_path);
1152 for (i = 0; i < npath; i++) {
1153 PyObject *loader;
1154 PyObject *hook = PyList_GetItem(meta_path, i);
1155 loader = PyObject_CallMethod(hook, "find_module",
1156 "sO", fullname,
1157 path != NULL ?
1158 path : Py_None);
1159 if (loader == NULL) {
1160 Py_DECREF(meta_path);
1161 return NULL; /* true error */
1162 }
1163 if (loader != Py_None) {
1164 /* a loader was found */
1165 *p_loader = loader;
1166 Py_DECREF(meta_path);
1167 return &importhookdescr;
1168 }
1169 Py_DECREF(loader);
1170 }
1171 Py_DECREF(meta_path);
1172 }
1173
1174 if (path != NULL && PyString_Check(path)) {
1175 /* The only type of submodule allowed inside a "frozen"
1176 package are other frozen modules or packages. */
1177 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1178 PyErr_SetString(PyExc_ImportError,
1179 "full frozen module name too long");
1180 return NULL;
1181 }
1182 strcpy(buf, PyString_AsString(path));
1183 strcat(buf, ".");
1184 strcat(buf, name);
1185 strcpy(name, buf);
1186 if (find_frozen(name) != NULL) {
1187 strcpy(buf, name);
1188 return &fd_frozen;
1189 }
1190 PyErr_Format(PyExc_ImportError,
1191 "No frozen submodule named %.200s", name);
1192 return NULL;
1193 }
1194 if (path == NULL) {
1195 if (is_builtin(name)) {
1196 strcpy(buf, name);
1197 return &fd_builtin;
1198 }
1199 if ((find_frozen(name)) != NULL) {
1200 strcpy(buf, name);
1201 return &fd_frozen;
1202 }
1203
1204#ifdef MS_COREDLL
1205 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1206 if (fp != NULL) {
1207 *p_fp = fp;
1208 return fdp;
1209 }
1210#endif
1211 path = PySys_GetObject("path");
1212 }
1213 if (path == NULL || !PyList_Check(path)) {
1214 PyErr_SetString(PyExc_ImportError,
1215 "sys.path must be a list of directory names");
1216 return NULL;
1217 }
1218
1219 path_hooks = PySys_GetObject("path_hooks");
1220 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1221 PyErr_SetString(PyExc_ImportError,
1222 "sys.path_hooks must be a list of "
1223 "import hooks");
1224 return NULL;
1225 }
1226 path_importer_cache = PySys_GetObject("path_importer_cache");
1227 if (path_importer_cache == NULL ||
1228 !PyDict_Check(path_importer_cache)) {
1229 PyErr_SetString(PyExc_ImportError,
1230 "sys.path_importer_cache must be a dict");
1231 return NULL;
1232 }
1233
1234 npath = PyList_Size(path);
1235 namelen = strlen(name);
1236 for (i = 0; i < npath; i++) {
1237 PyObject *copy = NULL;
1238 PyObject *v = PyList_GetItem(path, i);
1239 if (!v)
1240 return NULL;
1241#ifdef Py_USING_UNICODE
1242 if (PyUnicode_Check(v)) {
1243 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1244 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1245 if (copy == NULL)
1246 return NULL;
1247 v = copy;
1248 }
1249 else
1250#endif
1251 if (!PyString_Check(v))
1252 continue;
1253 len = PyString_GET_SIZE(v);
1254 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1255 Py_XDECREF(copy);
1256 continue; /* Too long */
1257 }
1258 strcpy(buf, PyString_AS_STRING(v));
1259 if (strlen(buf) != len) {
1260 Py_XDECREF(copy);
1261 continue; /* v contains '\0' */
1262 }
1263
1264 /* sys.path_hooks import hook */
1265 if (p_loader != NULL) {
1266 PyObject *importer;
1267
1268 importer = get_path_importer(path_importer_cache,
1269 path_hooks, v);
1270 if (importer == NULL) {
1271 Py_XDECREF(copy);
1272 return NULL;
1273 }
1274 /* Note: importer is a borrowed reference */
1275 if (importer != Py_None) {
1276 PyObject *loader;
1277 loader = PyObject_CallMethod(importer,
1278 "find_module",
1279 "s", fullname);
1280 Py_XDECREF(copy);
1281 if (loader == NULL)
1282 return NULL; /* error */
1283 if (loader != Py_None) {
1284 /* a loader was found */
1285 *p_loader = loader;
1286 return &importhookdescr;
1287 }
1288 Py_DECREF(loader);
1289 continue;
1290 }
1291 }
1292 /* no hook was found, use builtin import */
1293
1294 if (len > 0 && buf[len-1] != SEP
1295#ifdef ALTSEP
1296 && buf[len-1] != ALTSEP
1297#endif
1298 )
1299 buf[len++] = SEP;
1300 strcpy(buf+len, name);
1301 len += namelen;
1302
1303 /* Check for package import (buf holds a directory name,
1304 and there's an __init__ module in that directory */
1305#ifdef HAVE_STAT
1306 if (stat(buf, &statbuf) == 0 && /* it exists */
1307 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1308 case_ok(buf, len, namelen, name)) { /* case matches */
1309 if (find_init_module(buf)) { /* and has __init__.py */
1310 Py_XDECREF(copy);
1311 return &fd_package;
1312 }
1313 else {
1314 char warnstr[MAXPATHLEN+80];
1315 sprintf(warnstr, "Not importing directory "
1316 "'%.*s': missing __init__.py",
1317 MAXPATHLEN, buf);
1318 if (PyErr_Warn(PyExc_ImportWarning,
1319 warnstr)) {
1320 Py_XDECREF(copy);
1321 return NULL;
1322 }
1323 }
1324 }
1325#else
1326 /* XXX How are you going to test for directories? */
1327#ifdef RISCOS
1328 if (isdir(buf) &&
1329 case_ok(buf, len, namelen, name)) {
1330 if (find_init_module(buf)) {
1331 Py_XDECREF(copy);
1332 return &fd_package;
1333 }
1334 else {
1335 char warnstr[MAXPATHLEN+80];
1336 sprintf(warnstr, "Not importing directory "
1337 "'%.*s': missing __init__.py",
1338 MAXPATHLEN, buf);
1339 if (PyErr_Warn(PyExc_ImportWarning,
1340 warnstr)) {
1341 Py_XDECREF(copy);
1342 return NULL;
1343 }
1344 }
1345#endif
1346#endif
1347#if defined(PYOS_OS2)
1348 /* take a snapshot of the module spec for restoration
1349 * after the 8 character DLL hackery
1350 */
1351 saved_buf = strdup(buf);
1352 saved_len = len;
1353 saved_namelen = namelen;
1354#endif /* PYOS_OS2 */
1355 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1356#if defined(PYOS_OS2)
1357 /* OS/2 limits DLLs to 8 character names (w/o
1358 extension)
1359 * so if the name is longer than that and its a
1360 * dynamically loaded module we're going to try,
1361 * truncate the name before trying
1362 */
1363 if (strlen(subname) > 8) {
1364 /* is this an attempt to load a C extension? */
1365 const struct filedescr *scan;
1366 scan = _PyImport_DynLoadFiletab;
1367 while (scan->suffix != NULL) {
1368 if (!strcmp(scan->suffix, fdp->suffix))
1369 break;
1370 else
1371 scan++;
1372 }
1373 if (scan->suffix != NULL) {
1374 /* yes, so truncate the name */
1375 namelen = 8;
1376 len -= strlen(subname) - namelen;
1377 buf[len] = '\0';
1378 }
1379 }
1380#endif /* PYOS_OS2 */
1381 strcpy(buf+len, fdp->suffix);
1382 if (Py_VerboseFlag > 1)
1383 PySys_WriteStderr("# trying %s\n", buf);
1384 filemode = fdp->mode;
1385 if (filemode[0] == 'U')
1386 filemode = "r" PY_STDIOTEXTMODE;
1387 fp = fopen(buf, filemode);
1388 if (fp != NULL) {
1389 if (case_ok(buf, len, namelen, name))
1390 break;
1391 else { /* continue search */
1392 fclose(fp);
1393 fp = NULL;
1394 }
1395 }
1396#if defined(PYOS_OS2)
1397 /* restore the saved snapshot */
1398 strcpy(buf, saved_buf);
1399 len = saved_len;
1400 namelen = saved_namelen;
1401#endif
1402 }
1403#if defined(PYOS_OS2)
1404 /* don't need/want the module name snapshot anymore */
1405 if (saved_buf)
1406 {
1407 free(saved_buf);
1408 saved_buf = NULL;
1409 }
1410#endif
1411 Py_XDECREF(copy);
1412 if (fp != NULL)
1413 break;
1414 }
1415 if (fp == NULL) {
1416 PyErr_Format(PyExc_ImportError,
1417 "No module named %.200s", name);
1418 return NULL;
1419 }
1420 *p_fp = fp;
1421 return fdp;
1422}
1423
1424/* Helpers for main.c
1425 * Find the source file corresponding to a named module
1426 */
1427struct filedescr *
1428_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1429 size_t buflen, FILE **p_fp, PyObject **p_loader)
1430{
1431 return find_module((char *) name, (char *) name, path,
1432 buf, buflen, p_fp, p_loader);
1433}
1434
1435PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1436{
1437 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1438}
1439
1440/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1441 * The arguments here are tricky, best shown by example:
1442 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1443 * ^ ^ ^ ^
1444 * |--------------------- buf ---------------------|
1445 * |------------------- len ------------------|
1446 * |------ name -------|
1447 * |----- namelen -----|
1448 * buf is the full path, but len only counts up to (& exclusive of) the
1449 * extension. name is the module name, also exclusive of extension.
1450 *
1451 * We've already done a successful stat() or fopen() on buf, so know that
1452 * there's some match, possibly case-insensitive.
1453 *
1454 * case_ok() is to return 1 if there's a case-sensitive match for
1455 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1456 * exists.
1457 *
1458 * case_ok() is used to implement case-sensitive import semantics even
1459 * on platforms with case-insensitive filesystems. It's trivial to implement
1460 * for case-sensitive filesystems. It's pretty much a cross-platform
1461 * nightmare for systems with case-insensitive filesystems.
1462 */
1463
1464/* First we may need a pile of platform-specific header files; the sequence
1465 * of #if's here should match the sequence in the body of case_ok().
1466 */
1467#if defined(MS_WINDOWS)
1468#include <windows.h>
1469
1470#elif defined(DJGPP)
1471#include <dir.h>
1472
1473#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1474#include <sys/types.h>
1475#include <dirent.h>
1476
1477#elif defined(__KLIBC__)
1478#include <stdlib.h>
1479
1480#elif defined(PYOS_OS2)
1481#define INCL_DOS
1482#define INCL_DOSERRORS
1483#define INCL_NOPMAPI
1484#include <os2.h>
1485
1486#elif defined(RISCOS)
1487#include "oslib/osfscontrol.h"
1488#endif
1489
1490static int
1491case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
1492{
1493/* Pick a platform-specific implementation; the sequence of #if's here should
1494 * match the sequence just above.
1495 */
1496
1497/* MS_WINDOWS */
1498#if defined(MS_WINDOWS)
1499 WIN32_FIND_DATA data;
1500 HANDLE h;
1501
1502 if (Py_GETENV("PYTHONCASEOK") != NULL)
1503 return 1;
1504
1505 h = FindFirstFile(buf, &data);
1506 if (h == INVALID_HANDLE_VALUE) {
1507 PyErr_Format(PyExc_NameError,
1508 "Can't find file for module %.100s\n(filename %.300s)",
1509 name, buf);
1510 return 0;
1511 }
1512 FindClose(h);
1513 return strncmp(data.cFileName, name, namelen) == 0;
1514
1515/* DJGPP */
1516#elif defined(DJGPP)
1517 struct ffblk ffblk;
1518 int done;
1519
1520 if (Py_GETENV("PYTHONCASEOK") != NULL)
1521 return 1;
1522
1523 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1524 if (done) {
1525 PyErr_Format(PyExc_NameError,
1526 "Can't find file for module %.100s\n(filename %.300s)",
1527 name, buf);
1528 return 0;
1529 }
1530 return strncmp(ffblk.ff_name, name, namelen) == 0;
1531
1532/* new-fangled macintosh (macosx) or Cygwin */
1533#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1534 DIR *dirp;
1535 struct dirent *dp;
1536 char dirname[MAXPATHLEN + 1];
1537 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1538
1539 if (Py_GETENV("PYTHONCASEOK") != NULL)
1540 return 1;
1541
1542 /* Copy the dir component into dirname; substitute "." if empty */
1543 if (dirlen <= 0) {
1544 dirname[0] = '.';
1545 dirname[1] = '\0';
1546 }
1547 else {
1548 assert(dirlen <= MAXPATHLEN);
1549 memcpy(dirname, buf, dirlen);
1550 dirname[dirlen] = '\0';
1551 }
1552 /* Open the directory and search the entries for an exact match. */
1553 dirp = opendir(dirname);
1554 if (dirp) {
1555 char *nameWithExt = buf + len - namelen;
1556 while ((dp = readdir(dirp)) != NULL) {
1557 const int thislen =
1558#ifdef _DIRENT_HAVE_D_NAMELEN
1559 dp->d_namlen;
1560#else
1561 strlen(dp->d_name);
1562#endif
1563 if (thislen >= namelen &&
1564 strcmp(dp->d_name, nameWithExt) == 0) {
1565 (void)closedir(dirp);
1566 return 1; /* Found */
1567 }
1568 }
1569 (void)closedir(dirp);
1570 }
1571 return 0 ; /* Not found */
1572
1573/* RISC OS */
1574#elif defined(RISCOS)
1575 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1576 char buf2[MAXPATHLEN+2];
1577 char *nameWithExt = buf+len-namelen;
1578 int canonlen;
1579 os_error *e;
1580
1581 if (Py_GETENV("PYTHONCASEOK") != NULL)
1582 return 1;
1583
1584 /* workaround:
1585 append wildcard, otherwise case of filename wouldn't be touched */
1586 strcpy(buf2, buf);
1587 strcat(buf2, "*");
1588
1589 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1590 canonlen = MAXPATHLEN+1-canonlen;
1591 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1592 return 0;
1593 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1594 return 1; /* match */
1595
1596 return 0;
1597
1598/* OS/2 */
1599#elif defined(__KLIBC__)
1600 char canon[MAXPATHLEN+1];
1601 size_t canonlen;
1602 char *p, *p2;
1603
1604 if (Py_GETENV("PYTHONCASEOK") != NULL)
1605 return 1;
1606
1607 /* This resolves case differences and return and native OS/2
1608 path. Unfortunately, it'll also resolve symbolic links
1609 while of course will screw up a bit... */
1610 if (!_realrealpath(buf, canon, sizeof(canon)))
1611 return 0;
1612 canonlen = strlen(canon);
1613 if (canonlen < namelen)
1614 return 0;
1615 p = strrchr(canon, SEP);
1616 p2 = strrchr(p ? p : canon, ALTSEP);
1617 if (p2)
1618 p = p2;
1619
1620 return strncmp(p ? p + 1 : canon, name, namelen) == 0;
1621
1622#elif defined(PYOS_OS2)
1623 HDIR hdir = 1;
1624 ULONG srchcnt = 1;
1625 FILEFINDBUF3 ffbuf;
1626 APIRET rc;
1627
1628 if (getenv("PYTHONCASEOK") != NULL)
1629 return 1;
1630
1631 rc = DosFindFirst(buf,
1632 &hdir,
1633 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1634 &ffbuf, sizeof(ffbuf),
1635 &srchcnt,
1636 FIL_STANDARD);
1637 if (rc != NO_ERROR)
1638 return 0;
1639 return strncmp(ffbuf.achName, name, namelen) == 0;
1640
1641/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1642#else
1643 return 1;
1644
1645#endif
1646}
1647
1648
1649#ifdef HAVE_STAT
1650/* Helper to look for __init__.py or __init__.py[co] in potential package */
1651static int
1652find_init_module(char *buf)
1653{
1654 const size_t save_len = strlen(buf);
1655 size_t i = save_len;
1656 char *pname; /* pointer to start of __init__ */
1657 struct stat statbuf;
1658
1659/* For calling case_ok(buf, len, namelen, name):
1660 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1661 * ^ ^ ^ ^
1662 * |--------------------- buf ---------------------|
1663 * |------------------- len ------------------|
1664 * |------ name -------|
1665 * |----- namelen -----|
1666 */
1667 if (save_len + 13 >= MAXPATHLEN)
1668 return 0;
1669 buf[i++] = SEP;
1670 pname = buf + i;
1671 strcpy(pname, "__init__.py");
1672 if (stat(buf, &statbuf) == 0) {
1673 if (case_ok(buf,
1674 save_len + 9, /* len("/__init__") */
1675 8, /* len("__init__") */
1676 pname)) {
1677 buf[save_len] = '\0';
1678 return 1;
1679 }
1680 }
1681 i += strlen(pname);
1682 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1683 if (stat(buf, &statbuf) == 0) {
1684 if (case_ok(buf,
1685 save_len + 9, /* len("/__init__") */
1686 8, /* len("__init__") */
1687 pname)) {
1688 buf[save_len] = '\0';
1689 return 1;
1690 }
1691 }
1692 buf[save_len] = '\0';
1693 return 0;
1694}
1695
1696#else
1697
1698#ifdef RISCOS
1699static int
1700find_init_module(buf)
1701 char *buf;
1702{
1703 int save_len = strlen(buf);
1704 int i = save_len;
1705
1706 if (save_len + 13 >= MAXPATHLEN)
1707 return 0;
1708 buf[i++] = SEP;
1709 strcpy(buf+i, "__init__/py");
1710 if (isfile(buf)) {
1711 buf[save_len] = '\0';
1712 return 1;
1713 }
1714
1715 if (Py_OptimizeFlag)
1716 strcpy(buf+i, "o");
1717 else
1718 strcpy(buf+i, "c");
1719 if (isfile(buf)) {
1720 buf[save_len] = '\0';
1721 return 1;
1722 }
1723 buf[save_len] = '\0';
1724 return 0;
1725}
1726#endif /*RISCOS*/
1727
1728#endif /* HAVE_STAT */
1729
1730
1731static int init_builtin(char *); /* Forward */
1732
1733/* Load an external module using the default search path and return
1734 its module object WITH INCREMENTED REFERENCE COUNT */
1735
1736static PyObject *
1737load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
1738{
1739 PyObject *modules;
1740 PyObject *m;
1741 int err;
1742
1743 /* First check that there's an open file (if we need one) */
1744 switch (type) {
1745 case PY_SOURCE:
1746 case PY_COMPILED:
1747 if (fp == NULL) {
1748 PyErr_Format(PyExc_ValueError,
1749 "file object required for import (type code %d)",
1750 type);
1751 return NULL;
1752 }
1753 }
1754
1755 switch (type) {
1756
1757 case PY_SOURCE:
1758 m = load_source_module(name, buf, fp);
1759 break;
1760
1761 case PY_COMPILED:
1762 m = load_compiled_module(name, buf, fp);
1763 break;
1764
1765#ifdef HAVE_DYNAMIC_LOADING
1766 case C_EXTENSION:
1767 m = _PyImport_LoadDynamicModule(name, buf, fp);
1768 break;
1769#endif
1770
1771 case PKG_DIRECTORY:
1772 m = load_package(name, buf);
1773 break;
1774
1775 case C_BUILTIN:
1776 case PY_FROZEN:
1777 if (buf != NULL && buf[0] != '\0')
1778 name = buf;
1779 if (type == C_BUILTIN)
1780 err = init_builtin(name);
1781 else
1782 err = PyImport_ImportFrozenModule(name);
1783 if (err < 0)
1784 return NULL;
1785 if (err == 0) {
1786 PyErr_Format(PyExc_ImportError,
1787 "Purported %s module %.200s not found",
1788 type == C_BUILTIN ?
1789 "builtin" : "frozen",
1790 name);
1791 return NULL;
1792 }
1793 modules = PyImport_GetModuleDict();
1794 m = PyDict_GetItemString(modules, name);
1795 if (m == NULL) {
1796 PyErr_Format(
1797 PyExc_ImportError,
1798 "%s module %.200s not properly initialized",
1799 type == C_BUILTIN ?
1800 "builtin" : "frozen",
1801 name);
1802 return NULL;
1803 }
1804 Py_INCREF(m);
1805 break;
1806
1807 case IMP_HOOK: {
1808 if (loader == NULL) {
1809 PyErr_SetString(PyExc_ImportError,
1810 "import hook without loader");
1811 return NULL;
1812 }
1813 m = PyObject_CallMethod(loader, "load_module", "s", name);
1814 break;
1815 }
1816
1817 default:
1818 PyErr_Format(PyExc_ImportError,
1819 "Don't know how to import %.200s (type code %d)",
1820 name, type);
1821 m = NULL;
1822
1823 }
1824
1825 return m;
1826}
1827
1828
1829/* Initialize a built-in module.
1830 Return 1 for succes, 0 if the module is not found, and -1 with
1831 an exception set if the initialization failed. */
1832
1833static int
1834init_builtin(char *name)
1835{
1836 struct _inittab *p;
1837
1838 if (_PyImport_FindExtension(name, name) != NULL)
1839 return 1;
1840
1841 for (p = PyImport_Inittab; p->name != NULL; p++) {
1842 if (strcmp(name, p->name) == 0) {
1843 if (p->initfunc == NULL) {
1844 PyErr_Format(PyExc_ImportError,
1845 "Cannot re-init internal module %.200s",
1846 name);
1847 return -1;
1848 }
1849 if (Py_VerboseFlag)
1850 PySys_WriteStderr("import %s # builtin\n", name);
1851 (*p->initfunc)();
1852 if (PyErr_Occurred())
1853 return -1;
1854 if (_PyImport_FixupExtension(name, name) == NULL)
1855 return -1;
1856 return 1;
1857 }
1858 }
1859 return 0;
1860}
1861
1862
1863/* Frozen modules */
1864
1865static struct _frozen *
1866find_frozen(char *name)
1867{
1868 struct _frozen *p;
1869
1870 for (p = PyImport_FrozenModules; ; p++) {
1871 if (p->name == NULL)
1872 return NULL;
1873 if (strcmp(p->name, name) == 0)
1874 break;
1875 }
1876 return p;
1877}
1878
1879static PyObject *
1880get_frozen_object(char *name)
1881{
1882 struct _frozen *p = find_frozen(name);
1883 int size;
1884
1885 if (p == NULL) {
1886 PyErr_Format(PyExc_ImportError,
1887 "No such frozen object named %.200s",
1888 name);
1889 return NULL;
1890 }
1891 if (p->code == NULL) {
1892 PyErr_Format(PyExc_ImportError,
1893 "Excluded frozen object named %.200s",
1894 name);
1895 return NULL;
1896 }
1897 size = p->size;
1898 if (size < 0)
1899 size = -size;
1900 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1901}
1902
1903/* Initialize a frozen module.
1904 Return 1 for succes, 0 if the module is not found, and -1 with
1905 an exception set if the initialization failed.
1906 This function is also used from frozenmain.c */
1907
1908int
1909PyImport_ImportFrozenModule(char *name)
1910{
1911 struct _frozen *p = find_frozen(name);
1912 PyObject *co;
1913 PyObject *m;
1914 int ispackage;
1915 int size;
1916
1917 if (p == NULL)
1918 return 0;
1919 if (p->code == NULL) {
1920 PyErr_Format(PyExc_ImportError,
1921 "Excluded frozen object named %.200s",
1922 name);
1923 return -1;
1924 }
1925 size = p->size;
1926 ispackage = (size < 0);
1927 if (ispackage)
1928 size = -size;
1929 if (Py_VerboseFlag)
1930 PySys_WriteStderr("import %s # frozen%s\n",
1931 name, ispackage ? " package" : "");
1932 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1933 if (co == NULL)
1934 return -1;
1935 if (!PyCode_Check(co)) {
1936 PyErr_Format(PyExc_TypeError,
1937 "frozen object %.200s is not a code object",
1938 name);
1939 goto err_return;
1940 }
1941 if (ispackage) {
1942 /* Set __path__ to the package name */
1943 PyObject *d, *s;
1944 int err;
1945 m = PyImport_AddModule(name);
1946 if (m == NULL)
1947 goto err_return;
1948 d = PyModule_GetDict(m);
1949 s = PyString_InternFromString(name);
1950 if (s == NULL)
1951 goto err_return;
1952 err = PyDict_SetItemString(d, "__path__", s);
1953 Py_DECREF(s);
1954 if (err != 0)
1955 goto err_return;
1956 }
1957 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1958 if (m == NULL)
1959 goto err_return;
1960 Py_DECREF(co);
1961 Py_DECREF(m);
1962 return 1;
1963err_return:
1964 Py_DECREF(co);
1965 return -1;
1966}
1967
1968
1969/* Import a module, either built-in, frozen, or external, and return
1970 its module object WITH INCREMENTED REFERENCE COUNT */
1971
1972PyObject *
1973PyImport_ImportModule(const char *name)
1974{
1975 PyObject *pname;
1976 PyObject *result;
1977
1978 pname = PyString_FromString(name);
1979 if (pname == NULL)
1980 return NULL;
1981 result = PyImport_Import(pname);
1982 Py_DECREF(pname);
1983 return result;
1984}
1985
1986/* Forward declarations for helper routines */
1987static PyObject *get_parent(PyObject *globals, char *buf,
1988 Py_ssize_t *p_buflen, int level);
1989static PyObject *load_next(PyObject *mod, PyObject *altmod,
1990 char **p_name, char *buf, Py_ssize_t *p_buflen);
1991static int mark_miss(char *name);
1992static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1993 char *buf, Py_ssize_t buflen, int recursive);
1994static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1995
1996/* The Magnum Opus of dotted-name import :-) */
1997
1998static PyObject *
1999import_module_level(char *name, PyObject *globals, PyObject *locals,
2000 PyObject *fromlist, int level)
2001{
2002 char buf[MAXPATHLEN+1];
2003 Py_ssize_t buflen = 0;
2004 PyObject *parent, *head, *next, *tail;
2005
2006 parent = get_parent(globals, buf, &buflen, level);
2007 if (parent == NULL)
2008 return NULL;
2009
2010 head = load_next(parent, Py_None, &name, buf, &buflen);
2011 if (head == NULL)
2012 return NULL;
2013
2014 tail = head;
2015 Py_INCREF(tail);
2016 while (name) {
2017 next = load_next(tail, tail, &name, buf, &buflen);
2018 Py_DECREF(tail);
2019 if (next == NULL) {
2020 Py_DECREF(head);
2021 return NULL;
2022 }
2023 tail = next;
2024 }
2025 if (tail == Py_None) {
2026 /* If tail is Py_None, both get_parent and load_next found
2027 an empty module name: someone called __import__("") or
2028 doctored faulty bytecode */
2029 Py_DECREF(tail);
2030 Py_DECREF(head);
2031 PyErr_SetString(PyExc_ValueError,
2032 "Empty module name");
2033 return NULL;
2034 }
2035
2036 if (fromlist != NULL) {
2037 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2038 fromlist = NULL;
2039 }
2040
2041 if (fromlist == NULL) {
2042 Py_DECREF(tail);
2043 return head;
2044 }
2045
2046 Py_DECREF(head);
2047 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2048 Py_DECREF(tail);
2049 return NULL;
2050 }
2051
2052 return tail;
2053}
2054
2055/* For DLL compatibility */
2056#undef PyImport_ImportModuleEx
2057PyObject *
2058PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2059 PyObject *fromlist)
2060{
2061 PyObject *result;
2062 lock_import();
2063 result = import_module_level(name, globals, locals, fromlist, -1);
2064 if (unlock_import() < 0) {
2065 Py_XDECREF(result);
2066 PyErr_SetString(PyExc_RuntimeError,
2067 "not holding the import lock");
2068 return NULL;
2069 }
2070 return result;
2071}
2072#define PyImport_ImportModuleEx(n, g, l, f) \
2073 PyImport_ImportModuleLevel(n, g, l, f, -1);
2074
2075PyObject *
2076PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2077 PyObject *fromlist, int level)
2078{
2079 PyObject *result;
2080 lock_import();
2081 result = import_module_level(name, globals, locals, fromlist, level);
2082 if (unlock_import() < 0) {
2083 Py_XDECREF(result);
2084 PyErr_SetString(PyExc_RuntimeError,
2085 "not holding the import lock");
2086 return NULL;
2087 }
2088 return result;
2089}
2090
2091/* Return the package that an import is being performed in. If globals comes
2092 from the module foo.bar.bat (not itself a package), this returns the
2093 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2094 the package's entry in sys.modules is returned, as a borrowed reference.
2095
2096 The *name* of the returned package is returned in buf, with the length of
2097 the name in *p_buflen.
2098
2099 If globals doesn't come from a package or a module in a package, or a
2100 corresponding entry is not found in sys.modules, Py_None is returned.
2101*/
2102static PyObject *
2103get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
2104{
2105 static PyObject *namestr = NULL;
2106 static PyObject *pathstr = NULL;
2107 PyObject *modname, *modpath, *modules, *parent;
2108
2109 if (globals == NULL || !PyDict_Check(globals) || !level)
2110 return Py_None;
2111
2112 if (namestr == NULL) {
2113 namestr = PyString_InternFromString("__name__");
2114 if (namestr == NULL)
2115 return NULL;
2116 }
2117 if (pathstr == NULL) {
2118 pathstr = PyString_InternFromString("__path__");
2119 if (pathstr == NULL)
2120 return NULL;
2121 }
2122
2123 *buf = '\0';
2124 *p_buflen = 0;
2125 modname = PyDict_GetItem(globals, namestr);
2126 if (modname == NULL || !PyString_Check(modname))
2127 return Py_None;
2128
2129 modpath = PyDict_GetItem(globals, pathstr);
2130 if (modpath != NULL) {
2131 Py_ssize_t len = PyString_GET_SIZE(modname);
2132 if (len > MAXPATHLEN) {
2133 PyErr_SetString(PyExc_ValueError,
2134 "Module name too long");
2135 return NULL;
2136 }
2137 strcpy(buf, PyString_AS_STRING(modname));
2138 }
2139 else {
2140 char *start = PyString_AS_STRING(modname);
2141 char *lastdot = strrchr(start, '.');
2142 size_t len;
2143 if (lastdot == NULL && level > 0) {
2144 PyErr_SetString(PyExc_ValueError,
2145 "Attempted relative import in non-package");
2146 return NULL;
2147 }
2148 if (lastdot == NULL)
2149 return Py_None;
2150 len = lastdot - start;
2151 if (len >= MAXPATHLEN) {
2152 PyErr_SetString(PyExc_ValueError,
2153 "Module name too long");
2154 return NULL;
2155 }
2156 strncpy(buf, start, len);
2157 buf[len] = '\0';
2158 }
2159
2160 while (--level > 0) {
2161 char *dot = strrchr(buf, '.');
2162 if (dot == NULL) {
2163 PyErr_SetString(PyExc_ValueError,
2164 "Attempted relative import beyond "
2165 "toplevel package");
2166 return NULL;
2167 }
2168 *dot = '\0';
2169 }
2170 *p_buflen = strlen(buf);
2171
2172 modules = PyImport_GetModuleDict();
2173 parent = PyDict_GetItemString(modules, buf);
2174 if (parent == NULL)
2175 PyErr_Format(PyExc_SystemError,
2176 "Parent module '%.200s' not loaded", buf);
2177 return parent;
2178 /* We expect, but can't guarantee, if parent != None, that:
2179 - parent.__name__ == buf
2180 - parent.__dict__ is globals
2181 If this is violated... Who cares? */
2182}
2183
2184/* altmod is either None or same as mod */
2185static PyObject *
2186load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2187 Py_ssize_t *p_buflen)
2188{
2189 char *name = *p_name;
2190 char *dot = strchr(name, '.');
2191 size_t len;
2192 char *p;
2193 PyObject *result;
2194
2195 if (strlen(name) == 0) {
2196 /* completely empty module name should only happen in
2197 'from . import' (or '__import__("")')*/
2198 Py_INCREF(mod);
2199 *p_name = NULL;
2200 return mod;
2201 }
2202
2203 if (dot == NULL) {
2204 *p_name = NULL;
2205 len = strlen(name);
2206 }
2207 else {
2208 *p_name = dot+1;
2209 len = dot-name;
2210 }
2211 if (len == 0) {
2212 PyErr_SetString(PyExc_ValueError,
2213 "Empty module name");
2214 return NULL;
2215 }
2216
2217 p = buf + *p_buflen;
2218 if (p != buf)
2219 *p++ = '.';
2220 if (p+len-buf >= MAXPATHLEN) {
2221 PyErr_SetString(PyExc_ValueError,
2222 "Module name too long");
2223 return NULL;
2224 }
2225 strncpy(p, name, len);
2226 p[len] = '\0';
2227 *p_buflen = p+len-buf;
2228
2229 result = import_submodule(mod, p, buf);
2230 if (result == Py_None && altmod != mod) {
2231 Py_DECREF(result);
2232 /* Here, altmod must be None and mod must not be None */
2233 result = import_submodule(altmod, p, p);
2234 if (result != NULL && result != Py_None) {
2235 if (mark_miss(buf) != 0) {
2236 Py_DECREF(result);
2237 return NULL;
2238 }
2239 strncpy(buf, name, len);
2240 buf[len] = '\0';
2241 *p_buflen = len;
2242 }
2243 }
2244 if (result == NULL)
2245 return NULL;
2246
2247 if (result == Py_None) {
2248 Py_DECREF(result);
2249 PyErr_Format(PyExc_ImportError,
2250 "No module named %.200s", name);
2251 return NULL;
2252 }
2253
2254 return result;
2255}
2256
2257static int
2258mark_miss(char *name)
2259{
2260 PyObject *modules = PyImport_GetModuleDict();
2261 return PyDict_SetItemString(modules, name, Py_None);
2262}
2263
2264static int
2265ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
2266 int recursive)
2267{
2268 int i;
2269
2270 if (!PyObject_HasAttrString(mod, "__path__"))
2271 return 1;
2272
2273 for (i = 0; ; i++) {
2274 PyObject *item = PySequence_GetItem(fromlist, i);
2275 int hasit;
2276 if (item == NULL) {
2277 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2278 PyErr_Clear();
2279 return 1;
2280 }
2281 return 0;
2282 }
2283 if (!PyString_Check(item)) {
2284 PyErr_SetString(PyExc_TypeError,
2285 "Item in ``from list'' not a string");
2286 Py_DECREF(item);
2287 return 0;
2288 }
2289 if (PyString_AS_STRING(item)[0] == '*') {
2290 PyObject *all;
2291 Py_DECREF(item);
2292 /* See if the package defines __all__ */
2293 if (recursive)
2294 continue; /* Avoid endless recursion */
2295 all = PyObject_GetAttrString(mod, "__all__");
2296 if (all == NULL)
2297 PyErr_Clear();
2298 else {
2299 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2300 Py_DECREF(all);
2301 if (!ret)
2302 return 0;
2303 }
2304 continue;
2305 }
2306 hasit = PyObject_HasAttr(mod, item);
2307 if (!hasit) {
2308 char *subname = PyString_AS_STRING(item);
2309 PyObject *submod;
2310 char *p;
2311 if (buflen + strlen(subname) >= MAXPATHLEN) {
2312 PyErr_SetString(PyExc_ValueError,
2313 "Module name too long");
2314 Py_DECREF(item);
2315 return 0;
2316 }
2317 p = buf + buflen;
2318 *p++ = '.';
2319 strcpy(p, subname);
2320 submod = import_submodule(mod, subname, buf);
2321 Py_XDECREF(submod);
2322 if (submod == NULL) {
2323 Py_DECREF(item);
2324 return 0;
2325 }
2326 }
2327 Py_DECREF(item);
2328 }
2329
2330 /* NOTREACHED */
2331}
2332
2333static int
2334add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2335 PyObject *modules)
2336{
2337 if (mod == Py_None)
2338 return 1;
2339 /* Irrespective of the success of this load, make a
2340 reference to it in the parent package module. A copy gets
2341 saved in the modules dictionary under the full name, so get a
2342 reference from there, if need be. (The exception is when the
2343 load failed with a SyntaxError -- then there's no trace in
2344 sys.modules. In that case, of course, do nothing extra.) */
2345 if (submod == NULL) {
2346 submod = PyDict_GetItemString(modules, fullname);
2347 if (submod == NULL)
2348 return 1;
2349 }
2350 if (PyModule_Check(mod)) {
2351 /* We can't use setattr here since it can give a
2352 * spurious warning if the submodule name shadows a
2353 * builtin name */
2354 PyObject *dict = PyModule_GetDict(mod);
2355 if (!dict)
2356 return 0;
2357 if (PyDict_SetItemString(dict, subname, submod) < 0)
2358 return 0;
2359 }
2360 else {
2361 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2362 return 0;
2363 }
2364 return 1;
2365}
2366
2367static PyObject *
2368import_submodule(PyObject *mod, char *subname, char *fullname)
2369{
2370 PyObject *modules = PyImport_GetModuleDict();
2371 PyObject *m = NULL;
2372
2373 /* Require:
2374 if mod == None: subname == fullname
2375 else: mod.__name__ + "." + subname == fullname
2376 */
2377
2378 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2379 Py_INCREF(m);
2380 }
2381 else {
2382 PyObject *path, *loader = NULL;
2383 char buf[MAXPATHLEN+1];
2384 struct filedescr *fdp;
2385 FILE *fp = NULL;
2386
2387 if (mod == Py_None)
2388 path = NULL;
2389 else {
2390 path = PyObject_GetAttrString(mod, "__path__");
2391 if (path == NULL) {
2392 PyErr_Clear();
2393 Py_INCREF(Py_None);
2394 return Py_None;
2395 }
2396 }
2397
2398 buf[0] = '\0';
2399 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2400 &fp, &loader);
2401 Py_XDECREF(path);
2402 if (fdp == NULL) {
2403 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2404 return NULL;
2405 PyErr_Clear();
2406 Py_INCREF(Py_None);
2407 return Py_None;
2408 }
2409 m = load_module(fullname, fp, buf, fdp->type, loader);
2410 Py_XDECREF(loader);
2411 if (fp)
2412 fclose(fp);
2413 if (!add_submodule(mod, m, fullname, subname, modules)) {
2414 Py_XDECREF(m);
2415 m = NULL;
2416 }
2417 }
2418
2419 return m;
2420}
2421
2422
2423/* Re-import a module of any kind and return its module object, WITH
2424 INCREMENTED REFERENCE COUNT */
2425
2426PyObject *
2427PyImport_ReloadModule(PyObject *m)
2428{
2429 PyObject *modules = PyImport_GetModuleDict();
2430 PyObject *path = NULL, *loader = NULL;
2431 char *name, *subname;
2432 char buf[MAXPATHLEN+1];
2433 struct filedescr *fdp;
2434 FILE *fp = NULL;
2435 PyObject *newm;
2436
2437 if (m == NULL || !PyModule_Check(m)) {
2438 PyErr_SetString(PyExc_TypeError,
2439 "reload() argument must be module");
2440 return NULL;
2441 }
2442 name = PyModule_GetName(m);
2443 if (name == NULL)
2444 return NULL;
2445 if (m != PyDict_GetItemString(modules, name)) {
2446 PyErr_Format(PyExc_ImportError,
2447 "reload(): module %.200s not in sys.modules",
2448 name);
2449 return NULL;
2450 }
2451 subname = strrchr(name, '.');
2452 if (subname == NULL)
2453 subname = name;
2454 else {
2455 PyObject *parentname, *parent;
2456 parentname = PyString_FromStringAndSize(name, (subname-name));
2457 if (parentname == NULL)
2458 return NULL;
2459 parent = PyDict_GetItem(modules, parentname);
2460 if (parent == NULL) {
2461 PyErr_Format(PyExc_ImportError,
2462 "reload(): parent %.200s not in sys.modules",
2463 PyString_AS_STRING(parentname));
2464 Py_DECREF(parentname);
2465 return NULL;
2466 }
2467 Py_DECREF(parentname);
2468 subname++;
2469 path = PyObject_GetAttrString(parent, "__path__");
2470 if (path == NULL)
2471 PyErr_Clear();
2472 }
2473 buf[0] = '\0';
2474 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2475 Py_XDECREF(path);
2476
2477 if (fdp == NULL) {
2478 Py_XDECREF(loader);
2479 return NULL;
2480 }
2481
2482 newm = load_module(name, fp, buf, fdp->type, loader);
2483 Py_XDECREF(loader);
2484
2485 if (fp)
2486 fclose(fp);
2487 if (newm == NULL) {
2488 /* load_module probably removed name from modules because of
2489 * the error. Put back the original module object. We're
2490 * going to return NULL in this case regardless of whether
2491 * replacing name succeeds, so the return value is ignored.
2492 */
2493 PyDict_SetItemString(modules, name, m);
2494 }
2495 return newm;
2496}
2497
2498
2499/* Higher-level import emulator which emulates the "import" statement
2500 more accurately -- it invokes the __import__() function from the
2501 builtins of the current globals. This means that the import is
2502 done using whatever import hooks are installed in the current
2503 environment, e.g. by "rexec".
2504 A dummy list ["__doc__"] is passed as the 4th argument so that
2505 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2506 will return <module "gencache"> instead of <module "win32com">. */
2507
2508PyObject *
2509PyImport_Import(PyObject *module_name)
2510{
2511 static PyObject *silly_list = NULL;
2512 static PyObject *builtins_str = NULL;
2513 static PyObject *import_str = NULL;
2514 PyObject *globals = NULL;
2515 PyObject *import = NULL;
2516 PyObject *builtins = NULL;
2517 PyObject *r = NULL;
2518
2519 /* Initialize constant string objects */
2520 if (silly_list == NULL) {
2521 import_str = PyString_InternFromString("__import__");
2522 if (import_str == NULL)
2523 return NULL;
2524 builtins_str = PyString_InternFromString("__builtins__");
2525 if (builtins_str == NULL)
2526 return NULL;
2527 silly_list = Py_BuildValue("[s]", "__doc__");
2528 if (silly_list == NULL)
2529 return NULL;
2530 }
2531
2532 /* Get the builtins from current globals */
2533 globals = PyEval_GetGlobals();
2534 if (globals != NULL) {
2535 Py_INCREF(globals);
2536 builtins = PyObject_GetItem(globals, builtins_str);
2537 if (builtins == NULL)
2538 goto err;
2539 }
2540 else {
2541 /* No globals -- use standard builtins, and fake globals */
2542 PyErr_Clear();
2543
2544 builtins = PyImport_ImportModuleLevel("__builtin__",
2545 NULL, NULL, NULL, 0);
2546 if (builtins == NULL)
2547 return NULL;
2548 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2549 if (globals == NULL)
2550 goto err;
2551 }
2552
2553 /* Get the __import__ function from the builtins */
2554 if (PyDict_Check(builtins)) {
2555 import = PyObject_GetItem(builtins, import_str);
2556 if (import == NULL)
2557 PyErr_SetObject(PyExc_KeyError, import_str);
2558 }
2559 else
2560 import = PyObject_GetAttr(builtins, import_str);
2561 if (import == NULL)
2562 goto err;
2563
2564 /* Call the _import__ function with the proper argument list */
2565 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2566 globals, silly_list, NULL);
2567
2568 err:
2569 Py_XDECREF(globals);
2570 Py_XDECREF(builtins);
2571 Py_XDECREF(import);
2572
2573 return r;
2574}
2575
2576
2577/* Module 'imp' provides Python access to the primitives used for
2578 importing modules.
2579*/
2580
2581static PyObject *
2582imp_get_magic(PyObject *self, PyObject *noargs)
2583{
2584 char buf[4];
2585
2586 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2587 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2588 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2589 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2590
2591 return PyString_FromStringAndSize(buf, 4);
2592}
2593
2594static PyObject *
2595imp_get_suffixes(PyObject *self, PyObject *noargs)
2596{
2597 PyObject *list;
2598 struct filedescr *fdp;
2599
2600 list = PyList_New(0);
2601 if (list == NULL)
2602 return NULL;
2603 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2604 PyObject *item = Py_BuildValue("ssi",
2605 fdp->suffix, fdp->mode, fdp->type);
2606 if (item == NULL) {
2607 Py_DECREF(list);
2608 return NULL;
2609 }
2610 if (PyList_Append(list, item) < 0) {
2611 Py_DECREF(list);
2612 Py_DECREF(item);
2613 return NULL;
2614 }
2615 Py_DECREF(item);
2616 }
2617 return list;
2618}
2619
2620static PyObject *
2621call_find_module(char *name, PyObject *path)
2622{
2623 extern int fclose(FILE *);
2624 PyObject *fob, *ret;
2625 struct filedescr *fdp;
2626 char pathname[MAXPATHLEN+1];
2627 FILE *fp = NULL;
2628
2629 pathname[0] = '\0';
2630 if (path == Py_None)
2631 path = NULL;
2632 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2633 if (fdp == NULL)
2634 return NULL;
2635 if (fp != NULL) {
2636 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2637 if (fob == NULL) {
2638 fclose(fp);
2639 return NULL;
2640 }
2641 }
2642 else {
2643 fob = Py_None;
2644 Py_INCREF(fob);
2645 }
2646 ret = Py_BuildValue("Os(ssi)",
2647 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2648 Py_DECREF(fob);
2649 return ret;
2650}
2651
2652static PyObject *
2653imp_find_module(PyObject *self, PyObject *args)
2654{
2655 char *name;
2656 PyObject *path = NULL;
2657 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2658 return NULL;
2659 return call_find_module(name, path);
2660}
2661
2662static PyObject *
2663imp_init_builtin(PyObject *self, PyObject *args)
2664{
2665 char *name;
2666 int ret;
2667 PyObject *m;
2668 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2669 return NULL;
2670 ret = init_builtin(name);
2671 if (ret < 0)
2672 return NULL;
2673 if (ret == 0) {
2674 Py_INCREF(Py_None);
2675 return Py_None;
2676 }
2677 m = PyImport_AddModule(name);
2678 Py_XINCREF(m);
2679 return m;
2680}
2681
2682static PyObject *
2683imp_init_frozen(PyObject *self, PyObject *args)
2684{
2685 char *name;
2686 int ret;
2687 PyObject *m;
2688 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2689 return NULL;
2690 ret = PyImport_ImportFrozenModule(name);
2691 if (ret < 0)
2692 return NULL;
2693 if (ret == 0) {
2694 Py_INCREF(Py_None);
2695 return Py_None;
2696 }
2697 m = PyImport_AddModule(name);
2698 Py_XINCREF(m);
2699 return m;
2700}
2701
2702static PyObject *
2703imp_get_frozen_object(PyObject *self, PyObject *args)
2704{
2705 char *name;
2706
2707 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2708 return NULL;
2709 return get_frozen_object(name);
2710}
2711
2712static PyObject *
2713imp_is_builtin(PyObject *self, PyObject *args)
2714{
2715 char *name;
2716 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2717 return NULL;
2718 return PyInt_FromLong(is_builtin(name));
2719}
2720
2721static PyObject *
2722imp_is_frozen(PyObject *self, PyObject *args)
2723{
2724 char *name;
2725 struct _frozen *p;
2726 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2727 return NULL;
2728 p = find_frozen(name);
2729 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2730}
2731
2732static FILE *
2733get_file(char *pathname, PyObject *fob, char *mode)
2734{
2735 FILE *fp;
2736 if (fob == NULL) {
2737 if (mode[0] == 'U')
2738 mode = "r" PY_STDIOTEXTMODE;
2739 fp = fopen(pathname, mode);
2740 if (fp == NULL)
2741 PyErr_SetFromErrno(PyExc_IOError);
2742 }
2743 else {
2744 fp = PyFile_AsFile(fob);
2745 if (fp == NULL)
2746 PyErr_SetString(PyExc_ValueError,
2747 "bad/closed file object");
2748 }
2749 return fp;
2750}
2751
2752static PyObject *
2753imp_load_compiled(PyObject *self, PyObject *args)
2754{
2755 char *name;
2756 char *pathname;
2757 PyObject *fob = NULL;
2758 PyObject *m;
2759 FILE *fp;
2760 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2761 &PyFile_Type, &fob))
2762 return NULL;
2763 fp = get_file(pathname, fob, "rb");
2764 if (fp == NULL)
2765 return NULL;
2766 m = load_compiled_module(name, pathname, fp);
2767 if (fob == NULL)
2768 fclose(fp);
2769 return m;
2770}
2771
2772#ifdef HAVE_DYNAMIC_LOADING
2773
2774static PyObject *
2775imp_load_dynamic(PyObject *self, PyObject *args)
2776{
2777 char *name;
2778 char *pathname;
2779 PyObject *fob = NULL;
2780 PyObject *m;
2781 FILE *fp = NULL;
2782 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2783 &PyFile_Type, &fob))
2784 return NULL;
2785 if (fob) {
2786 fp = get_file(pathname, fob, "r");
2787 if (fp == NULL)
2788 return NULL;
2789 }
2790 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2791 return m;
2792}
2793
2794#endif /* HAVE_DYNAMIC_LOADING */
2795
2796static PyObject *
2797imp_load_source(PyObject *self, PyObject *args)
2798{
2799 char *name;
2800 char *pathname;
2801 PyObject *fob = NULL;
2802 PyObject *m;
2803 FILE *fp;
2804 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2805 &PyFile_Type, &fob))
2806 return NULL;
2807 fp = get_file(pathname, fob, "r");
2808 if (fp == NULL)
2809 return NULL;
2810 m = load_source_module(name, pathname, fp);
2811 if (fob == NULL)
2812 fclose(fp);
2813 return m;
2814}
2815
2816static PyObject *
2817imp_load_module(PyObject *self, PyObject *args)
2818{
2819 char *name;
2820 PyObject *fob;
2821 char *pathname;
2822 char *suffix; /* Unused */
2823 char *mode;
2824 int type;
2825 FILE *fp;
2826
2827 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2828 &name, &fob, &pathname,
2829 &suffix, &mode, &type))
2830 return NULL;
2831 if (*mode) {
2832 /* Mode must start with 'r' or 'U' and must not contain '+'.
2833 Implicit in this test is the assumption that the mode
2834 may contain other modifiers like 'b' or 't'. */
2835
2836 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2837 PyErr_Format(PyExc_ValueError,
2838 "invalid file open mode %.200s", mode);
2839 return NULL;
2840 }
2841 }
2842 if (fob == Py_None)
2843 fp = NULL;
2844 else {
2845 if (!PyFile_Check(fob)) {
2846 PyErr_SetString(PyExc_ValueError,
2847 "load_module arg#2 should be a file or None");
2848 return NULL;
2849 }
2850 fp = get_file(pathname, fob, mode);
2851 if (fp == NULL)
2852 return NULL;
2853 }
2854 return load_module(name, fp, pathname, type, NULL);
2855}
2856
2857static PyObject *
2858imp_load_package(PyObject *self, PyObject *args)
2859{
2860 char *name;
2861 char *pathname;
2862 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2863 return NULL;
2864 return load_package(name, pathname);
2865}
2866
2867static PyObject *
2868imp_new_module(PyObject *self, PyObject *args)
2869{
2870 char *name;
2871 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2872 return NULL;
2873 return PyModule_New(name);
2874}
2875
2876/* Doc strings */
2877
2878PyDoc_STRVAR(doc_imp,
2879"This module provides the components needed to build your own\n\
2880__import__ function. Undocumented functions are obsolete.");
2881
2882PyDoc_STRVAR(doc_find_module,
2883"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2884Search for a module. If path is omitted or None, search for a\n\
2885built-in, frozen or special module and continue search in sys.path.\n\
2886The module name cannot contain '.'; to search for a submodule of a\n\
2887package, pass the submodule name and the package's __path__.");
2888
2889PyDoc_STRVAR(doc_load_module,
2890"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2891Load a module, given information returned by find_module().\n\
2892The module name must include the full package name, if any.");
2893
2894PyDoc_STRVAR(doc_get_magic,
2895"get_magic() -> string\n\
2896Return the magic number for .pyc or .pyo files.");
2897
2898PyDoc_STRVAR(doc_get_suffixes,
2899"get_suffixes() -> [(suffix, mode, type), ...]\n\
2900Return a list of (suffix, mode, type) tuples describing the files\n\
2901that find_module() looks for.");
2902
2903PyDoc_STRVAR(doc_new_module,
2904"new_module(name) -> module\n\
2905Create a new module. Do not enter it in sys.modules.\n\
2906The module name must include the full package name, if any.");
2907
2908PyDoc_STRVAR(doc_lock_held,
2909"lock_held() -> boolean\n\
2910Return True if the import lock is currently held, else False.\n\
2911On platforms without threads, return False.");
2912
2913PyDoc_STRVAR(doc_acquire_lock,
2914"acquire_lock() -> None\n\
2915Acquires the interpreter's import lock for the current thread.\n\
2916This lock should be used by import hooks to ensure thread-safety\n\
2917when importing modules.\n\
2918On platforms without threads, this function does nothing.");
2919
2920PyDoc_STRVAR(doc_release_lock,
2921"release_lock() -> None\n\
2922Release the interpreter's import lock.\n\
2923On platforms without threads, this function does nothing.");
2924
2925static PyMethodDef imp_methods[] = {
2926 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2927 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2928 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2929 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2930 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2931 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2932 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2933 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2934 /* The rest are obsolete */
2935 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2936 {"init_builtin", imp_init_builtin, METH_VARARGS},
2937 {"init_frozen", imp_init_frozen, METH_VARARGS},
2938 {"is_builtin", imp_is_builtin, METH_VARARGS},
2939 {"is_frozen", imp_is_frozen, METH_VARARGS},
2940 {"load_compiled", imp_load_compiled, METH_VARARGS},
2941#ifdef HAVE_DYNAMIC_LOADING
2942 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2943#endif
2944 {"load_package", imp_load_package, METH_VARARGS},
2945 {"load_source", imp_load_source, METH_VARARGS},
2946 {NULL, NULL} /* sentinel */
2947};
2948
2949static int
2950setint(PyObject *d, char *name, int value)
2951{
2952 PyObject *v;
2953 int err;
2954
2955 v = PyInt_FromLong((long)value);
2956 err = PyDict_SetItemString(d, name, v);
2957 Py_XDECREF(v);
2958 return err;
2959}
2960
2961typedef struct {
2962 PyObject_HEAD
2963} NullImporter;
2964
2965static int
2966NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2967{
2968 char *path;
2969
2970 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2971 return -1;
2972
2973 if (!PyArg_ParseTuple(args, "s:NullImporter",
2974 &path))
2975 return -1;
2976
2977 if (strlen(path) == 0) {
2978 PyErr_SetString(PyExc_ImportError, "empty pathname");
2979 return -1;
2980 } else {
2981#ifndef RISCOS
2982 struct stat statbuf;
2983 int rv;
2984
2985 rv = stat(path, &statbuf);
2986 if (rv == 0) {
2987 /* it exists */
2988 if (S_ISDIR(statbuf.st_mode)) {
2989 /* it's a directory */
2990 PyErr_SetString(PyExc_ImportError,
2991 "existing directory");
2992 return -1;
2993 }
2994 }
2995#else
2996 if (object_exists(path)) {
2997 /* it exists */
2998 if (isdir(path)) {
2999 /* it's a directory */
3000 PyErr_SetString(PyExc_ImportError,
3001 "existing directory");
3002 return -1;
3003 }
3004 }
3005#endif
3006 }
3007 return 0;
3008}
3009
3010static PyObject *
3011NullImporter_find_module(NullImporter *self, PyObject *args)
3012{
3013 Py_RETURN_NONE;
3014}
3015
3016static PyMethodDef NullImporter_methods[] = {
3017 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3018 "Always return None"
3019 },
3020 {NULL} /* Sentinel */
3021};
3022
3023
3024static PyTypeObject NullImporterType = {
3025 PyObject_HEAD_INIT(NULL)
3026 0, /*ob_size*/
3027 "imp.NullImporter", /*tp_name*/
3028 sizeof(NullImporter), /*tp_basicsize*/
3029 0, /*tp_itemsize*/
3030 0, /*tp_dealloc*/
3031 0, /*tp_print*/
3032 0, /*tp_getattr*/
3033 0, /*tp_setattr*/
3034 0, /*tp_compare*/
3035 0, /*tp_repr*/
3036 0, /*tp_as_number*/
3037 0, /*tp_as_sequence*/
3038 0, /*tp_as_mapping*/
3039 0, /*tp_hash */
3040 0, /*tp_call*/
3041 0, /*tp_str*/
3042 0, /*tp_getattro*/
3043 0, /*tp_setattro*/
3044 0, /*tp_as_buffer*/
3045 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3046 "Null importer object", /* tp_doc */
3047 0, /* tp_traverse */
3048 0, /* tp_clear */
3049 0, /* tp_richcompare */
3050 0, /* tp_weaklistoffset */
3051 0, /* tp_iter */
3052 0, /* tp_iternext */
3053 NullImporter_methods, /* tp_methods */
3054 0, /* tp_members */
3055 0, /* tp_getset */
3056 0, /* tp_base */
3057 0, /* tp_dict */
3058 0, /* tp_descr_get */
3059 0, /* tp_descr_set */
3060 0, /* tp_dictoffset */
3061 (initproc)NullImporter_init, /* tp_init */
3062 0, /* tp_alloc */
3063 PyType_GenericNew /* tp_new */
3064};
3065
3066
3067PyMODINIT_FUNC
3068initimp(void)
3069{
3070 PyObject *m, *d;
3071
3072 if (PyType_Ready(&NullImporterType) < 0)
3073 goto failure;
3074
3075 m = Py_InitModule4("imp", imp_methods, doc_imp,
3076 NULL, PYTHON_API_VERSION);
3077 if (m == NULL)
3078 goto failure;
3079 d = PyModule_GetDict(m);
3080 if (d == NULL)
3081 goto failure;
3082
3083 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3084 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3085 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3086 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3087 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3088 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3089 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3090 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3091 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3092 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
3093
3094 Py_INCREF(&NullImporterType);
3095 PyModule_AddObject(m, "NullImporter", (PyObject *)&NullImporterType);
3096 failure:
3097 ;
3098}
3099
3100
3101/* API for embedding applications that want to add their own entries
3102 to the table of built-in modules. This should normally be called
3103 *before* Py_Initialize(). When the table resize fails, -1 is
3104 returned and the existing table is unchanged.
3105
3106 After a similar function by Just van Rossum. */
3107
3108int
3109PyImport_ExtendInittab(struct _inittab *newtab)
3110{
3111 static struct _inittab *our_copy = NULL;
3112 struct _inittab *p;
3113 int i, n;
3114
3115 /* Count the number of entries in both tables */
3116 for (n = 0; newtab[n].name != NULL; n++)
3117 ;
3118 if (n == 0)
3119 return 0; /* Nothing to do */
3120 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3121 ;
3122
3123 /* Allocate new memory for the combined table */
3124 p = our_copy;
3125 PyMem_RESIZE(p, struct _inittab, i+n+1);
3126 if (p == NULL)
3127 return -1;
3128
3129 /* Copy the tables into the new memory */
3130 if (our_copy != PyImport_Inittab)
3131 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3132 PyImport_Inittab = our_copy = p;
3133 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3134
3135 return 0;
3136}
3137
3138/* Shorthand to add a single entry given a name and a function */
3139
3140int
3141PyImport_AppendInittab(char *name, void (*initfunc)(void))
3142{
3143 struct _inittab newtab[2];
3144
3145 memset(newtab, '\0', sizeof newtab);
3146
3147 newtab[0].name = name;
3148 newtab[0].initfunc = initfunc;
3149
3150 return PyImport_ExtendInittab(newtab);
3151}
3152
3153#ifdef __cplusplus
3154}
3155#endif
Note: See TracBrowser for help on using the repository browser.