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