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