blob: 5d80983408a553addb5f678944cdd490cbd87db7 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
28#endif
29
Guido van Rossum21d335e1993-10-15 13:01:11 +000030
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000031/* Magic word to reject .pyc files generated by other Python versions.
32 It should change for each incompatible change to the bytecode.
33
34 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000035 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000036 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Guido van Rossum45aecf42006-03-15 04:58:47 +000038 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000039 -U interpeter flag will cause MAGIC+1 being used. They have been
40 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000041
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000042 There were a variety of old schemes for setting the magic number.
43 The current working scheme is to increment the previous value by
44 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000045
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000046 Known values:
47 Python 1.5: 20121
48 Python 1.5.1: 20121
49 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000050 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000051 Python 2.0: 50823
52 Python 2.0.1: 50823
53 Python 2.1: 60202
54 Python 2.1.1: 60202
55 Python 2.1.2: 60202
56 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000057 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000058 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000059 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000060 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000061 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000062 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000063 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000064 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000065 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000066 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
68 Python 2.5b3: 62111 (fix wrong code: x += yield)
69 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000070 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000071 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000072 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000073 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000074 Python 3000: 3000
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000075 3010 (removed UNARY_CONVERT)
76 3020 (added BUILD_SET)
77 3030 (added keyword-only parameters)
78 3040 (added signature annotations)
79 3050 (print becomes a function)
80 3060 (PEP 3115 metaclass syntax)
81 3070 (PEP 3109 raise changes)
82 3080 (PEP 3137 make __file__ and __name__ unicode)
83 3090 (kill str8 interning)
84 3100 (merge from 2.6a0, see 62151)
85 3102 (__file__ points to source file)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000086 Python 3.0a4: 3110 (WITH_CLEANUP optimization).
Benjamin Petersoneec3d712008-06-11 15:59:43 +000087 Python 3.0a5: 3130 (lexical exception stacking, including POP_EXCEPT)
Antoine Pitrouf289ae62008-12-18 11:06:25 +000088 Python 3.1a0: 3140 (optimize list, set and dict comprehensions:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000089 change LIST_APPEND and SET_ADD, add MAP_ADD)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +000090 Python 3.1a0: 3150 (optimize conditional branches:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000091 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Tim Peters36515e22001-11-18 04:06:29 +000092*/
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +000093#define MAGIC (3150 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000094
Guido van Rossum96774c12000-05-01 20:19:08 +000095/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000096 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000097 compiler works which are enabled by command line switches. */
98static long pyc_magic = MAGIC;
99
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100/* See _PyImport_FixupExtension() below */
101static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000102
Guido van Rossum771c6c81997-10-31 18:37:24 +0000103/* This table is defined in config.c: */
104extern struct _inittab _PyImport_Inittab[];
105
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000106/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000107extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000108
Guido van Rossum771c6c81997-10-31 18:37:24 +0000109struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000110
Guido van Rossumed1170e1999-12-20 21:23:41 +0000111/* these tables define the module suffixes that Python recognizes */
112struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000113
Guido van Rossumed1170e1999-12-20 21:23:41 +0000114static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000115 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000116#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000117 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000118#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000119 {".pyc", "rb", PY_COMPILED},
120 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000121};
122
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000124/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125
126void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000127_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000129 const struct filedescr *scan;
130 struct filedescr *filetab;
131 int countD = 0;
132 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000133
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000134 /* prepare _PyImport_Filetab: copy entries from
135 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
136 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000137#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000138 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
139 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000140#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000141 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
142 ++countS;
143 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
144 if (filetab == NULL)
145 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000146#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000147 memcpy(filetab, _PyImport_DynLoadFiletab,
148 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000149#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000150 memcpy(filetab + countD, _PyImport_StandardFiletab,
151 countS * sizeof(struct filedescr));
152 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000154 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000155
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000156 if (Py_OptimizeFlag) {
157 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
158 for (; filetab->suffix != NULL; filetab++) {
159 if (strcmp(filetab->suffix, ".pyc") == 0)
160 filetab->suffix = ".pyo";
161 }
162 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000163
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000164 {
165 /* Fix the pyc_magic so that byte compiled code created
166 using the all-Unicode method doesn't interfere with
167 code created in normal operation mode. */
168 pyc_magic = MAGIC + 1;
169 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170}
171
Guido van Rossum25ce5661997-08-02 03:10:38 +0000172void
Just van Rossum52e14d62002-12-30 22:08:05 +0000173_PyImportHooks_Init(void)
174{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175 PyObject *v, *path_hooks = NULL, *zimpimport;
176 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000178 /* adding sys.path_hooks and sys.path_importer_cache, setting up
179 zipimport */
180 if (PyType_Ready(&PyNullImporter_Type) < 0)
181 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000182
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000183 if (Py_VerboseFlag)
184 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000185
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000186 v = PyList_New(0);
187 if (v == NULL)
188 goto error;
189 err = PySys_SetObject("meta_path", v);
190 Py_DECREF(v);
191 if (err)
192 goto error;
193 v = PyDict_New();
194 if (v == NULL)
195 goto error;
196 err = PySys_SetObject("path_importer_cache", v);
197 Py_DECREF(v);
198 if (err)
199 goto error;
200 path_hooks = PyList_New(0);
201 if (path_hooks == NULL)
202 goto error;
203 err = PySys_SetObject("path_hooks", path_hooks);
204 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000205 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000206 PyErr_Print();
207 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
208 "path_importer_cache, or NullImporter failed"
209 );
210 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000211
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000212 zimpimport = PyImport_ImportModule("zipimport");
213 if (zimpimport == NULL) {
214 PyErr_Clear(); /* No zip import module -- okay */
215 if (Py_VerboseFlag)
216 PySys_WriteStderr("# can't import zipimport\n");
217 }
218 else {
219 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
220 "zipimporter");
221 Py_DECREF(zimpimport);
222 if (zipimporter == NULL) {
223 PyErr_Clear(); /* No zipimporter object -- okay */
224 if (Py_VerboseFlag)
225 PySys_WriteStderr(
226 "# can't import zipimport.zipimporter\n");
227 }
228 else {
229 /* sys.path_hooks.append(zipimporter) */
230 err = PyList_Append(path_hooks, zipimporter);
231 Py_DECREF(zipimporter);
232 if (err)
233 goto error;
234 if (Py_VerboseFlag)
235 PySys_WriteStderr(
236 "# installed zipimport hook\n");
237 }
238 }
239 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000240}
241
242void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000243_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000245 Py_XDECREF(extensions);
246 extensions = NULL;
247 PyMem_DEL(_PyImport_Filetab);
248 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249}
250
251
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000252/* Locking primitives to prevent parallel imports of the same module
253 in different threads to return with a partially loaded module.
254 These calls are serialized by the global interpreter lock. */
255
256#ifdef WITH_THREAD
257
Guido van Rossum49b56061998-10-01 20:42:43 +0000258#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000259
Guido van Rossum65d5b571998-12-21 19:32:43 +0000260static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000261static long import_lock_thread = -1;
262static int import_lock_level = 0;
263
Benjamin Peterson51838562009-10-04 20:35:30 +0000264void
265_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000266{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000267 long me = PyThread_get_thread_ident();
268 if (me == -1)
269 return; /* Too bad */
270 if (import_lock == NULL) {
271 import_lock = PyThread_allocate_lock();
272 if (import_lock == NULL)
273 return; /* Nothing much we can do. */
274 }
275 if (import_lock_thread == me) {
276 import_lock_level++;
277 return;
278 }
279 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
280 {
281 PyThreadState *tstate = PyEval_SaveThread();
282 PyThread_acquire_lock(import_lock, 1);
283 PyEval_RestoreThread(tstate);
284 }
285 import_lock_thread = me;
286 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287}
288
Benjamin Peterson51838562009-10-04 20:35:30 +0000289int
290_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000291{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000292 long me = PyThread_get_thread_ident();
293 if (me == -1 || import_lock == NULL)
294 return 0; /* Too bad */
295 if (import_lock_thread != me)
296 return -1;
297 import_lock_level--;
298 if (import_lock_level == 0) {
299 import_lock_thread = -1;
300 PyThread_release_lock(import_lock);
301 }
302 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000303}
304
Benjamin Peterson51838562009-10-04 20:35:30 +0000305/* This function used to be called from PyOS_AfterFork to ensure that newly
306 created child processes do not share locks with the parent, but for some
307 reason only on AIX systems. Instead of re-initializing the lock, we now
308 acquire the import lock around fork() calls. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000309
310void
311_PyImport_ReInitLock(void)
312{
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000313}
314
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000315#endif
316
Tim Peters69232342001-08-30 05:16:13 +0000317static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000318imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000319{
Tim Peters69232342001-08-30 05:16:13 +0000320#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000321 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000322#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000323 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000324#endif
325}
326
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000327static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000328imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000329{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000331 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000333 Py_INCREF(Py_None);
334 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000335}
336
337static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000338imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000339{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000340#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000341 if (_PyImport_ReleaseLock() < 0) {
342 PyErr_SetString(PyExc_RuntimeError,
343 "not holding the import lock");
344 return NULL;
345 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000347 Py_INCREF(Py_None);
348 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000349}
350
Guido van Rossumd8faa362007-04-27 19:54:29 +0000351static void
352imp_modules_reloading_clear(void)
353{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000354 PyInterpreterState *interp = PyThreadState_Get()->interp;
355 if (interp->modules_reloading != NULL)
356 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000357}
358
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359/* Helper for sys */
360
361PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000362PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000364 PyInterpreterState *interp = PyThreadState_GET()->interp;
365 if (interp->modules == NULL)
366 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
367 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368}
369
Guido van Rossum3f5da241990-12-20 15:06:42 +0000370
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000371/* List of names to clear in sys */
372static char* sys_deletes[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000373 "path", "argv", "ps1", "ps2",
374 "last_type", "last_value", "last_traceback",
375 "path_hooks", "path_importer_cache", "meta_path",
376 /* misc stuff */
377 "flags", "float_info",
378 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000379};
380
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000381static char* sys_files[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000382 "stdin", "__stdin__",
383 "stdout", "__stdout__",
384 "stderr", "__stderr__",
385 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000386};
387
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000388
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000389/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000390
Guido van Rossum3f5da241990-12-20 15:06:42 +0000391void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000392PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000393{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000394 Py_ssize_t pos, ndone;
395 char *name;
396 PyObject *key, *value, *dict;
397 PyInterpreterState *interp = PyThreadState_GET()->interp;
398 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000399
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000400 if (modules == NULL)
401 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000402
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000403 /* Delete some special variables first. These are common
404 places where user values hide and people complain when their
405 destructors fail. Since the modules containing them are
406 deleted *last* of all, they would come too late in the normal
407 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000408
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000409 value = PyDict_GetItemString(modules, "builtins");
410 if (value != NULL && PyModule_Check(value)) {
411 dict = PyModule_GetDict(value);
412 if (Py_VerboseFlag)
413 PySys_WriteStderr("# clear builtins._\n");
414 PyDict_SetItemString(dict, "_", Py_None);
415 }
416 value = PyDict_GetItemString(modules, "sys");
417 if (value != NULL && PyModule_Check(value)) {
418 char **p;
419 PyObject *v;
420 dict = PyModule_GetDict(value);
421 for (p = sys_deletes; *p != NULL; p++) {
422 if (Py_VerboseFlag)
423 PySys_WriteStderr("# clear sys.%s\n", *p);
424 PyDict_SetItemString(dict, *p, Py_None);
425 }
426 for (p = sys_files; *p != NULL; p+=2) {
427 if (Py_VerboseFlag)
428 PySys_WriteStderr("# restore sys.%s\n", *p);
429 v = PyDict_GetItemString(dict, *(p+1));
430 if (v == NULL)
431 v = Py_None;
432 PyDict_SetItemString(dict, *p, v);
433 }
434 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000436 /* First, delete __main__ */
437 value = PyDict_GetItemString(modules, "__main__");
438 if (value != NULL && PyModule_Check(value)) {
439 if (Py_VerboseFlag)
440 PySys_WriteStderr("# cleanup __main__\n");
441 _PyModule_Clear(value);
442 PyDict_SetItemString(modules, "__main__", Py_None);
443 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000445 /* The special treatment of "builtins" here is because even
446 when it's not referenced as a module, its dictionary is
447 referenced by almost every module's __builtins__. Since
448 deleting a module clears its dictionary (even if there are
449 references left to it), we need to delete the "builtins"
450 module last. Likewise, we don't delete sys until the very
451 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000452
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000453 Also note that we 'delete' modules by replacing their entry
454 in the modules dict with None, rather than really deleting
455 them; this avoids a rehash of the modules dictionary and
456 also marks them as "non existent" so they won't be
457 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000458
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000459 /* Next, repeatedly delete modules with a reference count of
460 one (skipping builtins and sys) and delete them */
461 do {
462 ndone = 0;
463 pos = 0;
464 while (PyDict_Next(modules, &pos, &key, &value)) {
465 if (value->ob_refcnt != 1)
466 continue;
467 if (PyUnicode_Check(key) && PyModule_Check(value)) {
468 name = _PyUnicode_AsString(key);
469 if (strcmp(name, "builtins") == 0)
470 continue;
471 if (strcmp(name, "sys") == 0)
472 continue;
473 if (Py_VerboseFlag)
474 PySys_WriteStderr(
475 "# cleanup[1] %s\n", name);
476 _PyModule_Clear(value);
477 PyDict_SetItem(modules, key, Py_None);
478 ndone++;
479 }
480 }
481 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000482
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000483 /* Next, delete all modules (still skipping builtins and sys) */
484 pos = 0;
485 while (PyDict_Next(modules, &pos, &key, &value)) {
486 if (PyUnicode_Check(key) && PyModule_Check(value)) {
487 name = _PyUnicode_AsString(key);
488 if (strcmp(name, "builtins") == 0)
489 continue;
490 if (strcmp(name, "sys") == 0)
491 continue;
492 if (Py_VerboseFlag)
493 PySys_WriteStderr("# cleanup[2] %s\n", name);
494 _PyModule_Clear(value);
495 PyDict_SetItem(modules, key, Py_None);
496 }
497 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000498
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000499 /* Next, delete sys and builtins (in that order) */
500 value = PyDict_GetItemString(modules, "sys");
501 if (value != NULL && PyModule_Check(value)) {
502 if (Py_VerboseFlag)
503 PySys_WriteStderr("# cleanup sys\n");
504 _PyModule_Clear(value);
505 PyDict_SetItemString(modules, "sys", Py_None);
506 }
507 value = PyDict_GetItemString(modules, "builtins");
508 if (value != NULL && PyModule_Check(value)) {
509 if (Py_VerboseFlag)
510 PySys_WriteStderr("# cleanup builtins\n");
511 _PyModule_Clear(value);
512 PyDict_SetItemString(modules, "builtins", Py_None);
513 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000514
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000515 /* Finally, clear and delete the modules directory */
516 PyDict_Clear(modules);
517 interp->modules = NULL;
518 Py_DECREF(modules);
519 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000520}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000521
522
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000523/* Helper for pythonrun.c -- return magic number */
524
525long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000526PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000528 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000529}
530
531
Guido van Rossum25ce5661997-08-02 03:10:38 +0000532/* Magic for extension modules (built-in as well as dynamically
533 loaded). To prevent initializing an extension module more than
534 once, we keep a static dictionary 'extensions' keyed by module name
535 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000536 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537 dictionary is stored by calling _PyImport_FixupExtension()
538 immediately after the module initialization function succeeds. A
539 copy can be retrieved from there by calling
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000540 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000541
Martin v. Löwis1a214512008-06-11 05:26:20 +0000542 Modules which do support multiple multiple initialization set
543 their m_size field to a non-negative number (indicating the size
544 of the module-specific state). They are still recorded in the
545 extensions dictionary, to avoid loading shared libraries twice.
546*/
547
548int
549_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000551 PyObject *modules, *dict;
552 struct PyModuleDef *def;
553 if (extensions == NULL) {
554 extensions = PyDict_New();
555 if (extensions == NULL)
556 return -1;
557 }
558 if (mod == NULL || !PyModule_Check(mod)) {
559 PyErr_BadInternalCall();
560 return -1;
561 }
562 def = PyModule_GetDef(mod);
563 if (!def) {
564 PyErr_BadInternalCall();
565 return -1;
566 }
567 modules = PyImport_GetModuleDict();
568 if (PyDict_SetItemString(modules, name, mod) < 0)
569 return -1;
570 if (_PyState_AddModule(mod, def) < 0) {
571 PyDict_DelItemString(modules, name);
572 return -1;
573 }
574 if (def->m_size == -1) {
575 if (def->m_base.m_copy) {
576 /* Somebody already imported the module,
577 likely under a different name.
578 XXX this should really not happen. */
579 Py_DECREF(def->m_base.m_copy);
580 def->m_base.m_copy = NULL;
581 }
582 dict = PyModule_GetDict(mod);
583 if (dict == NULL)
584 return -1;
585 def->m_base.m_copy = PyDict_Copy(dict);
586 if (def->m_base.m_copy == NULL)
587 return -1;
588 }
589 PyDict_SetItemString(extensions, filename, (PyObject*)def);
590 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591}
592
593PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000594_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000596 PyObject *mod, *mdict;
597 PyModuleDef* def;
598 if (extensions == NULL)
599 return NULL;
600 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
601 if (def == NULL)
602 return NULL;
603 if (def->m_size == -1) {
604 /* Module does not support repeated initialization */
605 if (def->m_base.m_copy == NULL)
606 return NULL;
607 mod = PyImport_AddModule(name);
608 if (mod == NULL)
609 return NULL;
610 mdict = PyModule_GetDict(mod);
611 if (mdict == NULL)
612 return NULL;
613 if (PyDict_Update(mdict, def->m_base.m_copy))
614 return NULL;
615 }
616 else {
617 if (def->m_base.m_init == NULL)
618 return NULL;
619 mod = def->m_base.m_init();
620 if (mod == NULL)
621 return NULL;
622 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
623 Py_DECREF(mod);
624 }
625 if (_PyState_AddModule(mod, def) < 0) {
626 PyDict_DelItemString(PyImport_GetModuleDict(), name);
627 Py_DECREF(mod);
628 return NULL;
629 }
630 if (Py_VerboseFlag)
631 PySys_WriteStderr("import %s # previously loaded (%s)\n",
632 name, filename);
633 return mod;
634
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635}
636
637
638/* Get the module object corresponding to a module name.
639 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000640 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000641 Because the former action is most common, THIS DOES NOT RETURN A
642 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643
Guido van Rossum79f25d91997-04-29 20:08:16 +0000644PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000645PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000647 PyObject *modules = PyImport_GetModuleDict();
648 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000649
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000650 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
651 PyModule_Check(m))
652 return m;
653 m = PyModule_New(name);
654 if (m == NULL)
655 return NULL;
656 if (PyDict_SetItemString(modules, name, m) != 0) {
657 Py_DECREF(m);
658 return NULL;
659 }
660 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000661
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000662 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000663}
664
Tim Peters1cd70172004-08-02 03:52:12 +0000665/* Remove name from sys.modules, if it's there. */
666static void
667_RemoveModule(const char *name)
668{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000669 PyObject *modules = PyImport_GetModuleDict();
670 if (PyDict_GetItemString(modules, name) == NULL)
671 return;
672 if (PyDict_DelItemString(modules, name) < 0)
673 Py_FatalError("import: deleting existing key in"
674 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000675}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000676
Christian Heimes3b06e532008-01-07 20:12:44 +0000677static PyObject * get_sourcefile(const char *file);
678
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000679/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000680 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
681 * removed from sys.modules, to avoid leaving damaged module objects
682 * in sys.modules. The caller may wish to restore the original
683 * module object (if any) in this case; PyImport_ReloadModule is an
684 * example.
685 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000687PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000688{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000689 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000690}
691
692PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000693PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000694{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000695 PyObject *modules = PyImport_GetModuleDict();
696 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000698 m = PyImport_AddModule(name);
699 if (m == NULL)
700 return NULL;
701 /* If the module is being reloaded, we get the old module back
702 and re-use its dict to exec the new code. */
703 d = PyModule_GetDict(m);
704 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
705 if (PyDict_SetItemString(d, "__builtins__",
706 PyEval_GetBuiltins()) != 0)
707 goto error;
708 }
709 /* Remember the filename as the __file__ attribute */
710 v = NULL;
711 if (pathname != NULL) {
712 v = get_sourcefile(pathname);
713 if (v == NULL)
714 PyErr_Clear();
715 }
716 if (v == NULL) {
717 v = ((PyCodeObject *)co)->co_filename;
718 Py_INCREF(v);
719 }
720 if (PyDict_SetItemString(d, "__file__", v) != 0)
721 PyErr_Clear(); /* Not important enough to report */
722 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000723
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000724 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
725 if (v == NULL)
726 goto error;
727 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000728
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000729 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
730 PyErr_Format(PyExc_ImportError,
731 "Loaded module %.200s not found in sys.modules",
732 name);
733 return NULL;
734 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000735
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000736 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000738 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000739
740 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000741 _RemoveModule(name);
742 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743}
744
745
746/* Given a pathname for a Python source file, fill a buffer with the
747 pathname for the corresponding compiled file. Return the pathname
748 for the compiled file, or NULL if there's no space in the buffer.
749 Doesn't set an exception. */
750
751static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000752make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000753{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000754 size_t len = strlen(pathname);
755 if (len+2 > buflen)
756 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000757
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000758#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000759 /* Treat .pyw as if it were .py. The case of ".pyw" must match
760 that used in _PyImport_StandardFiletab. */
761 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
762 --len; /* pretend 'w' isn't there */
Tim Petersc1731372001-08-04 08:12:36 +0000763#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000764 memcpy(buf, pathname, len);
765 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
766 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000768 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769}
770
771
772/* Given a pathname for a Python source file, its time of last
773 modification, and a pathname for a compiled file, check whether the
774 compiled file represents the same version of the source. If so,
775 return a FILE pointer for the compiled file, positioned just after
776 the header; if not, return NULL.
777 Doesn't set an exception. */
778
779static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000780check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000782 FILE *fp;
783 long magic;
784 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000786 fp = fopen(cpathname, "rb");
787 if (fp == NULL)
788 return NULL;
789 magic = PyMarshal_ReadLongFromFile(fp);
790 if (magic != pyc_magic) {
791 if (Py_VerboseFlag)
792 PySys_WriteStderr("# %s has bad magic\n", cpathname);
793 fclose(fp);
794 return NULL;
795 }
796 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
797 if (pyc_mtime != mtime) {
798 if (Py_VerboseFlag)
799 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
800 fclose(fp);
801 return NULL;
802 }
803 if (Py_VerboseFlag)
804 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
805 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806}
807
808
809/* Read a code object from a file and check it for validity */
810
Guido van Rossum79f25d91997-04-29 20:08:16 +0000811static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000812read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000814 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000816 co = PyMarshal_ReadLastObjectFromFile(fp);
817 if (co == NULL)
818 return NULL;
819 if (!PyCode_Check(co)) {
820 PyErr_Format(PyExc_ImportError,
821 "Non-code object in %.200s", cpathname);
822 Py_DECREF(co);
823 return NULL;
824 }
825 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826}
827
828
829/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000830 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000831
Guido van Rossum79f25d91997-04-29 20:08:16 +0000832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000833load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000835 long magic;
836 PyCodeObject *co;
837 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000838
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000839 magic = PyMarshal_ReadLongFromFile(fp);
840 if (magic != pyc_magic) {
841 PyErr_Format(PyExc_ImportError,
842 "Bad magic number in %.200s", cpathname);
843 return NULL;
844 }
845 (void) PyMarshal_ReadLongFromFile(fp);
846 co = read_compiled_module(cpathname, fp);
847 if (co == NULL)
848 return NULL;
849 if (Py_VerboseFlag)
850 PySys_WriteStderr("import %s # precompiled from %s\n",
851 name, cpathname);
852 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
853 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000854
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000855 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000856}
857
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000858/* Parse a source file and return the corresponding code object */
859
Guido van Rossum79f25d91997-04-29 20:08:16 +0000860static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000862{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000863 PyCodeObject *co = NULL;
864 mod_ty mod;
865 PyCompilerFlags flags;
866 PyArena *arena = PyArena_New();
867 if (arena == NULL)
868 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000869
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000870 flags.cf_flags = 0;
871 mod = PyParser_ASTFromFile(fp, pathname, NULL,
872 Py_file_input, 0, 0, &flags,
873 NULL, arena);
874 if (mod) {
875 co = PyAST_Compile(mod, pathname, NULL, arena);
876 }
877 PyArena_Free(arena);
878 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879}
880
881
Guido van Rossum55a83382000-09-20 20:31:38 +0000882/* Helper to open a bytecode file for writing in exclusive mode */
883
884static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +0000885open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000886{
887#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000888 /* Use O_EXCL to avoid a race condition when another process tries to
889 write the same file. When that happens, our open() call fails,
890 which is just fine (since it's only a cache).
891 XXX If the file exists and is writable but the directory is not
892 writable, the file will never be written. Oh well.
893 */
894 int fd;
895 (void) unlink(filename);
896 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +0000897#ifdef O_BINARY
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000898 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +0000899#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000900#ifdef __VMS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000901 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000902#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000903 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000904#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000905 );
906 if (fd < 0)
907 return NULL;
908 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +0000909#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000910 /* Best we can do -- on Windows this can't happen anyway */
911 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +0000912#endif
913}
914
915
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916/* Write a compiled module to a file, placing the time of last
917 modification of its source into the header.
918 Errors are ignored, if a write error occurs an attempt is made to
919 remove the file. */
920
921static void
Christian Heimes05e8be12008-02-23 18:30:17 +0000922write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000923{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000924 FILE *fp;
925 time_t mtime = srcstat->st_mtime;
R. David Murray07fc01f2009-07-19 01:59:05 +0000926#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000927 mode_t mode = srcstat->st_mode & ~S_IEXEC;
R. David Murray07fc01f2009-07-19 01:59:05 +0000928#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000929 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
930#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000932 fp = open_exclusive(cpathname, mode);
933 if (fp == NULL) {
934 if (Py_VerboseFlag)
935 PySys_WriteStderr(
936 "# can't create %s\n", cpathname);
937 return;
938 }
939 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
940 /* First write a 0 for mtime */
941 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
942 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
943 if (fflush(fp) != 0 || ferror(fp)) {
944 if (Py_VerboseFlag)
945 PySys_WriteStderr("# can't write %s\n", cpathname);
946 /* Don't keep partial file */
947 fclose(fp);
948 (void) unlink(cpathname);
949 return;
950 }
951 /* Now write the true mtime */
952 fseek(fp, 4L, 0);
953 assert(mtime < LONG_MAX);
954 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
955 fflush(fp);
956 fclose(fp);
957 if (Py_VerboseFlag)
958 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000959}
960
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000961static void
962update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
963{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000964 PyObject *constants, *tmp;
965 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000966
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000967 if (PyUnicode_Compare(co->co_filename, oldname))
968 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000969
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000970 tmp = co->co_filename;
971 co->co_filename = newname;
972 Py_INCREF(co->co_filename);
973 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000974
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000975 constants = co->co_consts;
976 n = PyTuple_GET_SIZE(constants);
977 for (i = 0; i < n; i++) {
978 tmp = PyTuple_GET_ITEM(constants, i);
979 if (PyCode_Check(tmp))
980 update_code_filenames((PyCodeObject *)tmp,
981 oldname, newname);
982 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000983}
984
985static int
986update_compiled_module(PyCodeObject *co, char *pathname)
987{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000988 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000989
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000990 newname = PyUnicode_DecodeFSDefault(pathname);
991 if (newname == NULL)
992 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000993
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000994 if (!PyUnicode_Compare(co->co_filename, newname)) {
995 Py_DECREF(newname);
996 return 0;
997 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000998
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000999 oldname = co->co_filename;
1000 Py_INCREF(oldname);
1001 update_code_filenames(co, oldname, newname);
1002 Py_DECREF(oldname);
1003 Py_DECREF(newname);
1004 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001005}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001006
1007/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001008 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1009 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010
Guido van Rossum79f25d91997-04-29 20:08:16 +00001011static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001012load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001013{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001014 struct stat st;
1015 FILE *fpc;
1016 char buf[MAXPATHLEN+1];
1017 char *cpathname;
1018 PyCodeObject *co;
1019 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001021 if (fstat(fileno(fp), &st) != 0) {
1022 PyErr_Format(PyExc_RuntimeError,
1023 "unable to get file status from '%s'",
1024 pathname);
1025 return NULL;
1026 }
1027#if SIZEOF_TIME_T > 4
1028 /* Python's .pyc timestamp handling presumes that the timestamp fits
1029 in 4 bytes. This will be fine until sometime in the year 2038,
1030 when a 4-byte signed time_t will overflow.
1031 */
1032 if (st.st_mtime >> 32) {
1033 PyErr_SetString(PyExc_OverflowError,
1034 "modification time overflows a 4 byte field");
1035 return NULL;
1036 }
1037#endif
1038 cpathname = make_compiled_pathname(pathname, buf,
1039 (size_t)MAXPATHLEN + 1);
1040 if (cpathname != NULL &&
1041 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1042 co = read_compiled_module(cpathname, fpc);
1043 fclose(fpc);
1044 if (co == NULL)
1045 return NULL;
1046 if (update_compiled_module(co, pathname) < 0)
1047 return NULL;
1048 if (Py_VerboseFlag)
1049 PySys_WriteStderr("import %s # precompiled from %s\n",
1050 name, cpathname);
1051 pathname = cpathname;
1052 }
1053 else {
1054 co = parse_source_module(pathname, fp);
1055 if (co == NULL)
1056 return NULL;
1057 if (Py_VerboseFlag)
1058 PySys_WriteStderr("import %s # from %s\n",
1059 name, pathname);
1060 if (cpathname) {
1061 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1062 if (ro == NULL || !PyObject_IsTrue(ro))
1063 write_compiled_module(co, cpathname, &st);
1064 }
1065 }
1066 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
1067 Py_DECREF(co);
1068
1069 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070}
1071
Christian Heimes3b06e532008-01-07 20:12:44 +00001072/* Get source file -> unicode or None
1073 * Returns the path to the py file if available, else the given path
1074 */
1075static PyObject *
1076get_sourcefile(const char *file)
1077{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001078 char py[MAXPATHLEN + 1];
1079 Py_ssize_t len;
1080 PyObject *u;
1081 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001083 if (!file || !*file) {
1084 Py_RETURN_NONE;
1085 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001086
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001087 len = strlen(file);
1088 /* match '*.py?' */
1089 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1090 return PyUnicode_DecodeFSDefault(file);
1091 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001092
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001093 strncpy(py, file, len-1);
1094 py[len-1] = '\0';
1095 if (stat(py, &statbuf) == 0 &&
1096 S_ISREG(statbuf.st_mode)) {
1097 u = PyUnicode_DecodeFSDefault(py);
1098 }
1099 else {
1100 u = PyUnicode_DecodeFSDefault(file);
1101 }
1102 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001103}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001104
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001105/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001106static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1107static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001108 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001109static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001110
1111/* Load a package and return its module object WITH INCREMENTED
1112 REFERENCE COUNT */
1113
1114static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001115load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001116{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001117 PyObject *m, *d;
1118 PyObject *file = NULL;
1119 PyObject *path = NULL;
1120 int err;
1121 char buf[MAXPATHLEN+1];
1122 FILE *fp = NULL;
1123 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001124
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001125 m = PyImport_AddModule(name);
1126 if (m == NULL)
1127 return NULL;
1128 if (Py_VerboseFlag)
1129 PySys_WriteStderr("import %s # directory %s\n",
1130 name, pathname);
1131 d = PyModule_GetDict(m);
1132 file = get_sourcefile(pathname);
1133 if (file == NULL)
1134 goto error;
1135 path = Py_BuildValue("[O]", file);
1136 if (path == NULL)
1137 goto error;
1138 err = PyDict_SetItemString(d, "__file__", file);
1139 if (err == 0)
1140 err = PyDict_SetItemString(d, "__path__", path);
1141 if (err != 0)
1142 goto error;
1143 buf[0] = '\0';
1144 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1145 if (fdp == NULL) {
1146 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1147 PyErr_Clear();
1148 Py_INCREF(m);
1149 }
1150 else
1151 m = NULL;
1152 goto cleanup;
1153 }
1154 m = load_module(name, fp, buf, fdp->type, NULL);
1155 if (fp != NULL)
1156 fclose(fp);
1157 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001158
1159 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001160 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001161 cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001162 Py_XDECREF(path);
1163 Py_XDECREF(file);
1164 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001165}
1166
1167
1168/* Helper to test for built-in module */
1169
1170static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001171is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001173 int i;
1174 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1175 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1176 if (PyImport_Inittab[i].initfunc == NULL)
1177 return -1;
1178 else
1179 return 1;
1180 }
1181 }
1182 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001183}
1184
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001185
Just van Rossum52e14d62002-12-30 22:08:05 +00001186/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1187 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001188 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001189 that can handle the path item. Return None if no hook could;
1190 this tells our caller it should fall back to the builtin
1191 import mechanism. Cache the result in path_importer_cache.
1192 Returns a borrowed reference. */
1193
1194static PyObject *
1195get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001196 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001197{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001198 PyObject *importer;
1199 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001200
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001201 /* These conditions are the caller's responsibility: */
1202 assert(PyList_Check(path_hooks));
1203 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001204
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001205 nhooks = PyList_Size(path_hooks);
1206 if (nhooks < 0)
1207 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001208
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001209 importer = PyDict_GetItem(path_importer_cache, p);
1210 if (importer != NULL)
1211 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001213 /* set path_importer_cache[p] to None to avoid recursion */
1214 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1215 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001216
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001217 for (j = 0; j < nhooks; j++) {
1218 PyObject *hook = PyList_GetItem(path_hooks, j);
1219 if (hook == NULL)
1220 return NULL;
1221 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1222 if (importer != NULL)
1223 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001224
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001225 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1226 return NULL;
1227 }
1228 PyErr_Clear();
1229 }
1230 if (importer == NULL) {
1231 importer = PyObject_CallFunctionObjArgs(
1232 (PyObject *)&PyNullImporter_Type, p, NULL
1233 );
1234 if (importer == NULL) {
1235 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1236 PyErr_Clear();
1237 return Py_None;
1238 }
1239 }
1240 }
1241 if (importer != NULL) {
1242 int err = PyDict_SetItem(path_importer_cache, p, importer);
1243 Py_DECREF(importer);
1244 if (err != 0)
1245 return NULL;
1246 }
1247 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001248}
1249
Christian Heimes9cd17752007-11-18 19:35:23 +00001250PyAPI_FUNC(PyObject *)
1251PyImport_GetImporter(PyObject *path) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001252 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001253
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001254 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1255 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1256 importer = get_path_importer(path_importer_cache,
1257 path_hooks, path);
1258 }
1259 }
1260 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1261 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001262}
1263
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001264/* Search the path (default sys.path) for a module. Return the
1265 corresponding filedescr struct, and (via return arguments) the
1266 pathname and an open file. Return NULL if the module is not found. */
1267
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001268#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001269extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001270 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001271#endif
1272
Martin v. Löwis18e16552006-02-15 17:27:45 +00001273static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001274static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001275static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001276
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001278find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001279 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001280{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001281 Py_ssize_t i, npath;
1282 size_t len, namelen;
1283 struct filedescr *fdp = NULL;
1284 char *filemode;
1285 FILE *fp = NULL;
1286 PyObject *path_hooks, *path_importer_cache;
1287 struct stat statbuf;
1288 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1289 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1290 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1291 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001292#if defined(PYOS_OS2)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001293 size_t saved_len;
1294 size_t saved_namelen;
1295 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001296#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001297 if (p_loader != NULL)
1298 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001299
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001300 if (strlen(subname) > MAXPATHLEN) {
1301 PyErr_SetString(PyExc_OverflowError,
1302 "module name is too long");
1303 return NULL;
1304 }
1305 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001306
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001307 /* sys.meta_path import hook */
1308 if (p_loader != NULL) {
1309 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001310
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001311 meta_path = PySys_GetObject("meta_path");
1312 if (meta_path == NULL || !PyList_Check(meta_path)) {
1313 PyErr_SetString(PyExc_ImportError,
1314 "sys.meta_path must be a list of "
1315 "import hooks");
1316 return NULL;
1317 }
1318 Py_INCREF(meta_path); /* zap guard */
1319 npath = PyList_Size(meta_path);
1320 for (i = 0; i < npath; i++) {
1321 PyObject *loader;
1322 PyObject *hook = PyList_GetItem(meta_path, i);
1323 loader = PyObject_CallMethod(hook, "find_module",
1324 "sO", fullname,
1325 path != NULL ?
1326 path : Py_None);
1327 if (loader == NULL) {
1328 Py_DECREF(meta_path);
1329 return NULL; /* true error */
1330 }
1331 if (loader != Py_None) {
1332 /* a loader was found */
1333 *p_loader = loader;
1334 Py_DECREF(meta_path);
1335 return &importhookdescr;
1336 }
1337 Py_DECREF(loader);
1338 }
1339 Py_DECREF(meta_path);
1340 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001341
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001342 if (find_frozen(fullname) != NULL) {
1343 strcpy(buf, fullname);
1344 return &fd_frozen;
1345 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001346
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001347 if (path == NULL) {
1348 if (is_builtin(name)) {
1349 strcpy(buf, name);
1350 return &fd_builtin;
1351 }
Guido van Rossumac279101996-08-22 23:10:58 +00001352#ifdef MS_COREDLL
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001353 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1354 if (fp != NULL) {
1355 *p_fp = fp;
1356 return fdp;
1357 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001358#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001359 path = PySys_GetObject("path");
1360 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001361
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001362 if (path == NULL || !PyList_Check(path)) {
1363 PyErr_SetString(PyExc_ImportError,
1364 "sys.path must be a list of directory names");
1365 return NULL;
1366 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001367
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001368 path_hooks = PySys_GetObject("path_hooks");
1369 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1370 PyErr_SetString(PyExc_ImportError,
1371 "sys.path_hooks must be a list of "
1372 "import hooks");
1373 return NULL;
1374 }
1375 path_importer_cache = PySys_GetObject("path_importer_cache");
1376 if (path_importer_cache == NULL ||
1377 !PyDict_Check(path_importer_cache)) {
1378 PyErr_SetString(PyExc_ImportError,
1379 "sys.path_importer_cache must be a dict");
1380 return NULL;
1381 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001382
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001383 npath = PyList_Size(path);
1384 namelen = strlen(name);
1385 for (i = 0; i < npath; i++) {
1386 PyObject *v = PyList_GetItem(path, i);
1387 PyObject *origv = v;
1388 const char *base;
1389 Py_ssize_t size;
1390 if (!v)
1391 return NULL;
1392 if (PyUnicode_Check(v)) {
1393 v = PyUnicode_AsEncodedString(v,
1394 Py_FileSystemDefaultEncoding, NULL);
1395 if (v == NULL)
1396 return NULL;
1397 }
1398 else if (!PyBytes_Check(v))
1399 continue;
1400 else
1401 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001402
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001403 base = PyBytes_AS_STRING(v);
1404 size = PyBytes_GET_SIZE(v);
1405 len = size;
1406 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1407 Py_DECREF(v);
1408 continue; /* Too long */
1409 }
1410 strcpy(buf, base);
1411 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001412
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001413 if (strlen(buf) != len) {
1414 continue; /* v contains '\0' */
1415 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001416
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001417 /* sys.path_hooks import hook */
1418 if (p_loader != NULL) {
1419 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001420
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001421 importer = get_path_importer(path_importer_cache,
1422 path_hooks, origv);
1423 if (importer == NULL) {
1424 return NULL;
1425 }
1426 /* Note: importer is a borrowed reference */
1427 if (importer != Py_None) {
1428 PyObject *loader;
1429 loader = PyObject_CallMethod(importer,
1430 "find_module",
1431 "s", fullname);
1432 if (loader == NULL)
1433 return NULL; /* error */
1434 if (loader != Py_None) {
1435 /* a loader was found */
1436 *p_loader = loader;
1437 return &importhookdescr;
1438 }
1439 Py_DECREF(loader);
1440 continue;
1441 }
1442 }
1443 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001445 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001446#ifdef ALTSEP
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001447 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001448#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001449 )
1450 buf[len++] = SEP;
1451 strcpy(buf+len, name);
1452 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001454 /* Check for package import (buf holds a directory name,
1455 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001456#ifdef HAVE_STAT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001457 if (stat(buf, &statbuf) == 0 && /* it exists */
1458 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1459 case_ok(buf, len, namelen, name)) { /* case matches */
1460 if (find_init_module(buf)) { /* and has __init__.py */
1461 return &fd_package;
1462 }
1463 else {
1464 char warnstr[MAXPATHLEN+80];
1465 sprintf(warnstr, "Not importing directory "
1466 "'%.*s': missing __init__.py",
1467 MAXPATHLEN, buf);
1468 if (PyErr_WarnEx(PyExc_ImportWarning,
1469 warnstr, 1)) {
1470 return NULL;
1471 }
1472 }
1473 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001474#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001475#if defined(PYOS_OS2)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001476 /* take a snapshot of the module spec for restoration
1477 * after the 8 character DLL hackery
1478 */
1479 saved_buf = strdup(buf);
1480 saved_len = len;
1481 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001482#endif /* PYOS_OS2 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001483 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001484#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001485 /* OS/2 limits DLLs to 8 character names (w/o
1486 extension)
1487 * so if the name is longer than that and its a
1488 * dynamically loaded module we're going to try,
1489 * truncate the name before trying
1490 */
1491 if (strlen(subname) > 8) {
1492 /* is this an attempt to load a C extension? */
1493 const struct filedescr *scan;
1494 scan = _PyImport_DynLoadFiletab;
1495 while (scan->suffix != NULL) {
1496 if (!strcmp(scan->suffix, fdp->suffix))
1497 break;
1498 else
1499 scan++;
1500 }
1501 if (scan->suffix != NULL) {
1502 /* yes, so truncate the name */
1503 namelen = 8;
1504 len -= strlen(subname) - namelen;
1505 buf[len] = '\0';
1506 }
1507 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001508#endif /* PYOS_OS2 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001509 strcpy(buf+len, fdp->suffix);
1510 if (Py_VerboseFlag > 1)
1511 PySys_WriteStderr("# trying %s\n", buf);
1512 filemode = fdp->mode;
1513 if (filemode[0] == 'U')
1514 filemode = "r" PY_STDIOTEXTMODE;
1515 fp = fopen(buf, filemode);
1516 if (fp != NULL) {
1517 if (case_ok(buf, len, namelen, name))
1518 break;
1519 else { /* continue search */
1520 fclose(fp);
1521 fp = NULL;
1522 }
1523 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001524#if defined(PYOS_OS2)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001525 /* restore the saved snapshot */
1526 strcpy(buf, saved_buf);
1527 len = saved_len;
1528 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001529#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001530 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001531#if defined(PYOS_OS2)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001532 /* don't need/want the module name snapshot anymore */
1533 if (saved_buf)
1534 {
1535 free(saved_buf);
1536 saved_buf = NULL;
1537 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001538#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001539 if (fp != NULL)
1540 break;
1541 }
1542 if (fp == NULL) {
1543 PyErr_Format(PyExc_ImportError,
1544 "No module named %.200s", name);
1545 return NULL;
1546 }
1547 *p_fp = fp;
1548 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001549}
1550
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001551/* Helpers for main.c
1552 * Find the source file corresponding to a named module
1553 */
1554struct filedescr *
1555_PyImport_FindModule(const char *name, PyObject *path, char *buf,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001556 size_t buflen, FILE **p_fp, PyObject **p_loader)
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001557{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001558 return find_module((char *) name, (char *) name, path,
1559 buf, buflen, p_fp, p_loader);
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001560}
1561
1562PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1563{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001564 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001565}
1566
Martin v. Löwis18e16552006-02-15 17:27:45 +00001567/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001568 * The arguments here are tricky, best shown by example:
1569 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1570 * ^ ^ ^ ^
1571 * |--------------------- buf ---------------------|
1572 * |------------------- len ------------------|
1573 * |------ name -------|
1574 * |----- namelen -----|
1575 * buf is the full path, but len only counts up to (& exclusive of) the
1576 * extension. name is the module name, also exclusive of extension.
1577 *
1578 * We've already done a successful stat() or fopen() on buf, so know that
1579 * there's some match, possibly case-insensitive.
1580 *
Tim Peters50d8d372001-02-28 05:34:27 +00001581 * case_ok() is to return 1 if there's a case-sensitive match for
1582 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1583 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001584 *
Tim Peters50d8d372001-02-28 05:34:27 +00001585 * case_ok() is used to implement case-sensitive import semantics even
1586 * on platforms with case-insensitive filesystems. It's trivial to implement
1587 * for case-sensitive filesystems. It's pretty much a cross-platform
1588 * nightmare for systems with case-insensitive filesystems.
1589 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001590
Tim Peters50d8d372001-02-28 05:34:27 +00001591/* First we may need a pile of platform-specific header files; the sequence
1592 * of #if's here should match the sequence in the body of case_ok().
1593 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001594#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001595#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001596
Tim Peters50d8d372001-02-28 05:34:27 +00001597#elif defined(DJGPP)
1598#include <dir.h>
1599
Jason Tishler7961aa62005-05-20 00:56:54 +00001600#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001601#include <sys/types.h>
1602#include <dirent.h>
1603
Andrew MacIntyred9400542002-02-26 11:41:34 +00001604#elif defined(PYOS_OS2)
1605#define INCL_DOS
1606#define INCL_DOSERRORS
1607#define INCL_NOPMAPI
1608#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001609#endif
1610
Guido van Rossum0980bd91998-02-13 17:18:36 +00001611static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001612case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001613{
Tim Peters50d8d372001-02-28 05:34:27 +00001614/* Pick a platform-specific implementation; the sequence of #if's here should
1615 * match the sequence just above.
1616 */
1617
Jason Tishler7961aa62005-05-20 00:56:54 +00001618/* MS_WINDOWS */
1619#if defined(MS_WINDOWS)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001620 WIN32_FIND_DATA data;
1621 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001622
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001623 if (Py_GETENV("PYTHONCASEOK") != NULL)
1624 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001625
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001626 h = FindFirstFile(buf, &data);
1627 if (h == INVALID_HANDLE_VALUE) {
1628 PyErr_Format(PyExc_NameError,
1629 "Can't find file for module %.100s\n(filename %.300s)",
1630 name, buf);
1631 return 0;
1632 }
1633 FindClose(h);
1634 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001635
1636/* DJGPP */
1637#elif defined(DJGPP)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001638 struct ffblk ffblk;
1639 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001640
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001641 if (Py_GETENV("PYTHONCASEOK") != NULL)
1642 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001643
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001644 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1645 if (done) {
1646 PyErr_Format(PyExc_NameError,
1647 "Can't find file for module %.100s\n(filename %.300s)",
1648 name, buf);
1649 return 0;
1650 }
1651 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001652
Jason Tishler7961aa62005-05-20 00:56:54 +00001653/* new-fangled macintosh (macosx) or Cygwin */
1654#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001655 DIR *dirp;
1656 struct dirent *dp;
1657 char dirname[MAXPATHLEN + 1];
1658 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001660 if (Py_GETENV("PYTHONCASEOK") != NULL)
1661 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001662
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001663 /* Copy the dir component into dirname; substitute "." if empty */
1664 if (dirlen <= 0) {
1665 dirname[0] = '.';
1666 dirname[1] = '\0';
1667 }
1668 else {
1669 assert(dirlen <= MAXPATHLEN);
1670 memcpy(dirname, buf, dirlen);
1671 dirname[dirlen] = '\0';
1672 }
1673 /* Open the directory and search the entries for an exact match. */
1674 dirp = opendir(dirname);
1675 if (dirp) {
1676 char *nameWithExt = buf + len - namelen;
1677 while ((dp = readdir(dirp)) != NULL) {
1678 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001679#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001680 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001681#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001682 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001683#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001684 if (thislen >= namelen &&
1685 strcmp(dp->d_name, nameWithExt) == 0) {
1686 (void)closedir(dirp);
1687 return 1; /* Found */
1688 }
1689 }
1690 (void)closedir(dirp);
1691 }
1692 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001693
Andrew MacIntyred9400542002-02-26 11:41:34 +00001694/* OS/2 */
1695#elif defined(PYOS_OS2)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001696 HDIR hdir = 1;
1697 ULONG srchcnt = 1;
1698 FILEFINDBUF3 ffbuf;
1699 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001700
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001701 if (Py_GETENV("PYTHONCASEOK") != NULL)
1702 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001703
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001704 rc = DosFindFirst(buf,
1705 &hdir,
1706 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1707 &ffbuf, sizeof(ffbuf),
1708 &srchcnt,
1709 FIL_STANDARD);
1710 if (rc != NO_ERROR)
1711 return 0;
1712 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001713
Tim Peters50d8d372001-02-28 05:34:27 +00001714/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1715#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001716 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001717
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001718#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001719}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001720
Guido van Rossum0980bd91998-02-13 17:18:36 +00001721
Guido van Rossum197346f1997-10-31 18:38:52 +00001722#ifdef HAVE_STAT
1723/* Helper to look for __init__.py or __init__.py[co] in potential package */
1724static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001725find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001726{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001727 const size_t save_len = strlen(buf);
1728 size_t i = save_len;
1729 char *pname; /* pointer to start of __init__ */
1730 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00001731
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001732/* For calling case_ok(buf, len, namelen, name):
1733 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1734 * ^ ^ ^ ^
1735 * |--------------------- buf ---------------------|
1736 * |------------------- len ------------------|
1737 * |------ name -------|
1738 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00001739 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001740 if (save_len + 13 >= MAXPATHLEN)
1741 return 0;
1742 buf[i++] = SEP;
1743 pname = buf + i;
1744 strcpy(pname, "__init__.py");
1745 if (stat(buf, &statbuf) == 0) {
1746 if (case_ok(buf,
1747 save_len + 9, /* len("/__init__") */
1748 8, /* len("__init__") */
1749 pname)) {
1750 buf[save_len] = '\0';
1751 return 1;
1752 }
1753 }
1754 i += strlen(pname);
1755 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1756 if (stat(buf, &statbuf) == 0) {
1757 if (case_ok(buf,
1758 save_len + 9, /* len("/__init__") */
1759 8, /* len("__init__") */
1760 pname)) {
1761 buf[save_len] = '\0';
1762 return 1;
1763 }
1764 }
1765 buf[save_len] = '\0';
1766 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00001767}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001768
Guido van Rossum197346f1997-10-31 18:38:52 +00001769#endif /* HAVE_STAT */
1770
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001771
Tim Petersdbd9ba62000-07-09 03:09:57 +00001772static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001773
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001775 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776
Guido van Rossum79f25d91997-04-29 20:08:16 +00001777static PyObject *
Georg Brandl01a30522009-08-13 08:37:59 +00001778load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001779{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001780 PyObject *modules;
1781 PyObject *m;
1782 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001783
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001784 /* First check that there's an open file (if we need one) */
1785 switch (type) {
1786 case PY_SOURCE:
1787 case PY_COMPILED:
1788 if (fp == NULL) {
1789 PyErr_Format(PyExc_ValueError,
1790 "file object required for import (type code %d)",
1791 type);
1792 return NULL;
1793 }
1794 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001795
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001796 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001797
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001798 case PY_SOURCE:
1799 m = load_source_module(name, pathname, fp);
1800 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001802 case PY_COMPILED:
1803 m = load_compiled_module(name, pathname, fp);
1804 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001805
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001806#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001807 case C_EXTENSION:
1808 m = _PyImport_LoadDynamicModule(name, pathname, fp);
1809 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001810#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001811
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001812 case PKG_DIRECTORY:
1813 m = load_package(name, pathname);
1814 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001815
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001816 case C_BUILTIN:
1817 case PY_FROZEN:
1818 if (pathname != NULL && pathname[0] != '\0')
1819 name = pathname;
1820 if (type == C_BUILTIN)
1821 err = init_builtin(name);
1822 else
1823 err = PyImport_ImportFrozenModule(name);
1824 if (err < 0)
1825 return NULL;
1826 if (err == 0) {
1827 PyErr_Format(PyExc_ImportError,
1828 "Purported %s module %.200s not found",
1829 type == C_BUILTIN ?
1830 "builtin" : "frozen",
1831 name);
1832 return NULL;
1833 }
1834 modules = PyImport_GetModuleDict();
1835 m = PyDict_GetItemString(modules, name);
1836 if (m == NULL) {
1837 PyErr_Format(
1838 PyExc_ImportError,
1839 "%s module %.200s not properly initialized",
1840 type == C_BUILTIN ?
1841 "builtin" : "frozen",
1842 name);
1843 return NULL;
1844 }
1845 Py_INCREF(m);
1846 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001847
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001848 case IMP_HOOK: {
1849 if (loader == NULL) {
1850 PyErr_SetString(PyExc_ImportError,
1851 "import hook without loader");
1852 return NULL;
1853 }
1854 m = PyObject_CallMethod(loader, "load_module", "s", name);
1855 break;
1856 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001857
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001858 default:
1859 PyErr_Format(PyExc_ImportError,
1860 "Don't know how to import %.200s (type code %d)",
1861 name, type);
1862 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001863
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001864 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001865
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001866 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001867}
1868
1869
1870/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001871 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001872 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001873
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001874static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001875init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001876{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001877 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001878
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001879 if (_PyImport_FindExtension(name, name) != NULL)
1880 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001881
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 for (p = PyImport_Inittab; p->name != NULL; p++) {
1883 PyObject *mod;
1884 if (strcmp(name, p->name) == 0) {
1885 if (p->initfunc == NULL) {
1886 PyErr_Format(PyExc_ImportError,
1887 "Cannot re-init internal module %.200s",
1888 name);
1889 return -1;
1890 }
1891 if (Py_VerboseFlag)
1892 PySys_WriteStderr("import %s # builtin\n", name);
1893 mod = (*p->initfunc)();
1894 if (mod == 0)
1895 return -1;
1896 if (_PyImport_FixupExtension(mod, name, name) < 0)
1897 return -1;
1898 /* FixupExtension has put the module into sys.modules,
1899 so we can release our own reference. */
1900 Py_DECREF(mod);
1901 return 1;
1902 }
1903 }
1904 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001905}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001906
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001907
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001908/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001909
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001910static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001911find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001912{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001913 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001914
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001915 if (!name)
1916 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001917
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001918 for (p = PyImport_FrozenModules; ; p++) {
1919 if (p->name == NULL)
1920 return NULL;
1921 if (strcmp(p->name, name) == 0)
1922 break;
1923 }
1924 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001925}
1926
Guido van Rossum79f25d91997-04-29 20:08:16 +00001927static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001928get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001929{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001930 struct _frozen *p = find_frozen(name);
1931 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001932
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001933 if (p == NULL) {
1934 PyErr_Format(PyExc_ImportError,
1935 "No such frozen object named %.200s",
1936 name);
1937 return NULL;
1938 }
1939 if (p->code == NULL) {
1940 PyErr_Format(PyExc_ImportError,
1941 "Excluded frozen object named %.200s",
1942 name);
1943 return NULL;
1944 }
1945 size = p->size;
1946 if (size < 0)
1947 size = -size;
1948 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001949}
1950
Brett Cannon8d110132009-03-15 02:20:16 +00001951static PyObject *
1952is_frozen_package(char *name)
1953{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001954 struct _frozen *p = find_frozen(name);
1955 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001956
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001957 if (p == NULL) {
1958 PyErr_Format(PyExc_ImportError,
1959 "No such frozen object named %.200s",
1960 name);
1961 return NULL;
1962 }
Brett Cannon8d110132009-03-15 02:20:16 +00001963
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001964 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001965
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001966 if (size < 0)
1967 Py_RETURN_TRUE;
1968 else
1969 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001970}
1971
1972
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001973/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001974 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001975 an exception set if the initialization failed.
1976 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001977
1978int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001979PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001980{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001981 struct _frozen *p = find_frozen(name);
1982 PyObject *co;
1983 PyObject *m;
1984 int ispackage;
1985 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001986
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001987 if (p == NULL)
1988 return 0;
1989 if (p->code == NULL) {
1990 PyErr_Format(PyExc_ImportError,
1991 "Excluded frozen object named %.200s",
1992 name);
1993 return -1;
1994 }
1995 size = p->size;
1996 ispackage = (size < 0);
1997 if (ispackage)
1998 size = -size;
1999 if (Py_VerboseFlag)
2000 PySys_WriteStderr("import %s # frozen%s\n",
2001 name, ispackage ? " package" : "");
2002 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2003 if (co == NULL)
2004 return -1;
2005 if (!PyCode_Check(co)) {
2006 PyErr_Format(PyExc_TypeError,
2007 "frozen object %.200s is not a code object",
2008 name);
2009 goto err_return;
2010 }
2011 if (ispackage) {
2012 /* Set __path__ to the package name */
2013 PyObject *d, *s, *l;
2014 int err;
2015 m = PyImport_AddModule(name);
2016 if (m == NULL)
2017 goto err_return;
2018 d = PyModule_GetDict(m);
2019 s = PyUnicode_InternFromString(name);
2020 if (s == NULL)
2021 goto err_return;
2022 l = PyList_New(1);
2023 if (l == NULL) {
2024 Py_DECREF(s);
2025 goto err_return;
2026 }
2027 PyList_SET_ITEM(l, 0, s);
2028 err = PyDict_SetItemString(d, "__path__", l);
2029 Py_DECREF(l);
2030 if (err != 0)
2031 goto err_return;
2032 }
2033 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2034 if (m == NULL)
2035 goto err_return;
2036 Py_DECREF(co);
2037 Py_DECREF(m);
2038 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002039err_return:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002040 Py_DECREF(co);
2041 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002042}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002043
2044
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002045/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002046 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002047
Guido van Rossum79f25d91997-04-29 20:08:16 +00002048PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002049PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002050{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002051 PyObject *pname;
2052 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002053
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002054 pname = PyUnicode_FromString(name);
2055 if (pname == NULL)
2056 return NULL;
2057 result = PyImport_Import(pname);
2058 Py_DECREF(pname);
2059 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002060}
2061
Christian Heimes072c0f12008-01-03 23:01:04 +00002062/* Import a module without blocking
2063 *
2064 * At first it tries to fetch the module from sys.modules. If the module was
2065 * never loaded before it loads it with PyImport_ImportModule() unless another
2066 * thread holds the import lock. In the latter case the function raises an
2067 * ImportError instead of blocking.
2068 *
2069 * Returns the module object with incremented ref count.
2070 */
2071PyObject *
2072PyImport_ImportModuleNoBlock(const char *name)
2073{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002074 PyObject *result;
2075 PyObject *modules;
2076 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002077
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002078 /* Try to get the module from sys.modules[name] */
2079 modules = PyImport_GetModuleDict();
2080 if (modules == NULL)
2081 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002083 result = PyDict_GetItemString(modules, name);
2084 if (result != NULL) {
2085 Py_INCREF(result);
2086 return result;
2087 }
2088 else {
2089 PyErr_Clear();
2090 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002091#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002092 /* check the import lock
2093 * me might be -1 but I ignore the error here, the lock function
2094 * takes care of the problem */
2095 me = PyThread_get_thread_ident();
2096 if (import_lock_thread == -1 || import_lock_thread == me) {
2097 /* no thread or me is holding the lock */
2098 return PyImport_ImportModule(name);
2099 }
2100 else {
2101 PyErr_Format(PyExc_ImportError,
2102 "Failed to import %.200s because the import lock"
2103 "is held by another thread.",
2104 name);
2105 return NULL;
2106 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002107#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002108 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002109#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002110}
2111
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002112/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002113static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002114 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002115static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002116 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002117static int mark_miss(char *name);
2118static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002119 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002120static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002121
2122/* The Magnum Opus of dotted-name import :-) */
2123
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002124static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002125import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002126 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002128 char buf[MAXPATHLEN+1];
2129 Py_ssize_t buflen = 0;
2130 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002131
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002132 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002133#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002134 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002135#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002136 ) {
2137 PyErr_SetString(PyExc_ImportError,
2138 "Import by filename is not supported.");
2139 return NULL;
2140 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002142 parent = get_parent(globals, buf, &buflen, level);
2143 if (parent == NULL)
2144 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002145
Florent Xicluna2760a662010-08-16 22:40:45 +00002146 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2147 &buflen);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002148 if (head == NULL)
2149 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002151 tail = head;
2152 Py_INCREF(tail);
2153 while (name) {
2154 next = load_next(tail, tail, &name, buf, &buflen);
2155 Py_DECREF(tail);
2156 if (next == NULL) {
2157 Py_DECREF(head);
2158 return NULL;
2159 }
2160 tail = next;
2161 }
2162 if (tail == Py_None) {
2163 /* If tail is Py_None, both get_parent and load_next found
2164 an empty module name: someone called __import__("") or
2165 doctored faulty bytecode */
2166 Py_DECREF(tail);
2167 Py_DECREF(head);
2168 PyErr_SetString(PyExc_ValueError,
2169 "Empty module name");
2170 return NULL;
2171 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002172
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002173 if (fromlist != NULL) {
2174 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2175 fromlist = NULL;
2176 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002178 if (fromlist == NULL) {
2179 Py_DECREF(tail);
2180 return head;
2181 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002182
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002183 Py_DECREF(head);
2184 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2185 Py_DECREF(tail);
2186 return NULL;
2187 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002189 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002190}
2191
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002192PyObject *
2193PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002194 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002195{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002196 PyObject *result;
2197 _PyImport_AcquireLock();
2198 result = import_module_level(name, globals, locals, fromlist, level);
2199 if (_PyImport_ReleaseLock() < 0) {
2200 Py_XDECREF(result);
2201 PyErr_SetString(PyExc_RuntimeError,
2202 "not holding the import lock");
2203 return NULL;
2204 }
2205 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002206}
2207
Fred Drake87590902004-05-28 20:21:36 +00002208/* Return the package that an import is being performed in. If globals comes
2209 from the module foo.bar.bat (not itself a package), this returns the
2210 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002211 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002212
2213 The *name* of the returned package is returned in buf, with the length of
2214 the name in *p_buflen.
2215
2216 If globals doesn't come from a package or a module in a package, or a
2217 corresponding entry is not found in sys.modules, Py_None is returned.
2218*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002219static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002220get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002221{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002222 static PyObject *namestr = NULL;
2223 static PyObject *pathstr = NULL;
2224 static PyObject *pkgstr = NULL;
2225 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2226 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002228 if (globals == NULL || !PyDict_Check(globals) || !level)
2229 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002230
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002231 if (namestr == NULL) {
2232 namestr = PyUnicode_InternFromString("__name__");
2233 if (namestr == NULL)
2234 return NULL;
2235 }
2236 if (pathstr == NULL) {
2237 pathstr = PyUnicode_InternFromString("__path__");
2238 if (pathstr == NULL)
2239 return NULL;
2240 }
2241 if (pkgstr == NULL) {
2242 pkgstr = PyUnicode_InternFromString("__package__");
2243 if (pkgstr == NULL)
2244 return NULL;
2245 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002246
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002247 *buf = '\0';
2248 *p_buflen = 0;
2249 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002251 if ((pkgname != NULL) && (pkgname != Py_None)) {
2252 /* __package__ is set, so use it */
2253 char *pkgname_str;
2254 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002256 if (!PyUnicode_Check(pkgname)) {
2257 PyErr_SetString(PyExc_ValueError,
2258 "__package__ set to non-string");
2259 return NULL;
2260 }
2261 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2262 if (len == 0) {
2263 if (level > 0) {
2264 PyErr_SetString(PyExc_ValueError,
2265 "Attempted relative import in non-package");
2266 return NULL;
2267 }
2268 return Py_None;
2269 }
2270 if (len > MAXPATHLEN) {
2271 PyErr_SetString(PyExc_ValueError,
2272 "Package name too long");
2273 return NULL;
2274 }
2275 strcpy(buf, pkgname_str);
2276 } else {
2277 /* __package__ not set, so figure it out and set it */
2278 modname = PyDict_GetItem(globals, namestr);
2279 if (modname == NULL || !PyUnicode_Check(modname))
2280 return Py_None;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002281
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002282 modpath = PyDict_GetItem(globals, pathstr);
2283 if (modpath != NULL) {
2284 /* __path__ is set, so modname is already the package name */
2285 char *modname_str;
2286 Py_ssize_t len;
2287 int error;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002288
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002289 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2290 if (len > MAXPATHLEN) {
2291 PyErr_SetString(PyExc_ValueError,
2292 "Module name too long");
2293 return NULL;
2294 }
2295 strcpy(buf, modname_str);
2296 error = PyDict_SetItem(globals, pkgstr, modname);
2297 if (error) {
2298 PyErr_SetString(PyExc_ValueError,
2299 "Could not set __package__");
2300 return NULL;
2301 }
2302 } else {
2303 /* Normal module, so work out the package name if any */
2304 char *start = _PyUnicode_AsString(modname);
2305 char *lastdot = strrchr(start, '.');
2306 size_t len;
2307 int error;
2308 if (lastdot == NULL && level > 0) {
2309 PyErr_SetString(PyExc_ValueError,
2310 "Attempted relative import in non-package");
2311 return NULL;
2312 }
2313 if (lastdot == NULL) {
2314 error = PyDict_SetItem(globals, pkgstr, Py_None);
2315 if (error) {
2316 PyErr_SetString(PyExc_ValueError,
2317 "Could not set __package__");
2318 return NULL;
2319 }
2320 return Py_None;
2321 }
2322 len = lastdot - start;
2323 if (len >= MAXPATHLEN) {
2324 PyErr_SetString(PyExc_ValueError,
2325 "Module name too long");
2326 return NULL;
2327 }
2328 strncpy(buf, start, len);
2329 buf[len] = '\0';
2330 pkgname = PyUnicode_FromString(buf);
2331 if (pkgname == NULL) {
2332 return NULL;
2333 }
2334 error = PyDict_SetItem(globals, pkgstr, pkgname);
2335 Py_DECREF(pkgname);
2336 if (error) {
2337 PyErr_SetString(PyExc_ValueError,
2338 "Could not set __package__");
2339 return NULL;
2340 }
2341 }
2342 }
2343 while (--level > 0) {
2344 char *dot = strrchr(buf, '.');
2345 if (dot == NULL) {
2346 PyErr_SetString(PyExc_ValueError,
2347 "Attempted relative import beyond "
2348 "toplevel package");
2349 return NULL;
2350 }
2351 *dot = '\0';
2352 }
2353 *p_buflen = strlen(buf);
2354
2355 modules = PyImport_GetModuleDict();
2356 parent = PyDict_GetItemString(modules, buf);
2357 if (parent == NULL) {
2358 if (orig_level < 1) {
2359 PyObject *err_msg = PyBytes_FromFormat(
2360 "Parent module '%.200s' not found "
2361 "while handling absolute import", buf);
2362 if (err_msg == NULL) {
2363 return NULL;
2364 }
2365 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2366 PyBytes_AsString(err_msg), 1)) {
2367 *buf = '\0';
2368 *p_buflen = 0;
2369 parent = Py_None;
2370 }
2371 Py_DECREF(err_msg);
2372 } else {
2373 PyErr_Format(PyExc_SystemError,
2374 "Parent module '%.200s' not loaded, "
2375 "cannot perform relative import", buf);
2376 }
2377 }
2378 return parent;
2379 /* We expect, but can't guarantee, if parent != None, that:
2380 - parent.__name__ == buf
2381 - parent.__dict__ is globals
2382 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002383}
2384
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002385/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002386static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002387load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002388 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002389{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002390 char *name = *p_name;
2391 char *dot = strchr(name, '.');
2392 size_t len;
2393 char *p;
2394 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002395
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002396 if (strlen(name) == 0) {
2397 /* completely empty module name should only happen in
2398 'from . import' (or '__import__("")')*/
2399 Py_INCREF(mod);
2400 *p_name = NULL;
2401 return mod;
2402 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002403
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002404 if (dot == NULL) {
2405 *p_name = NULL;
2406 len = strlen(name);
2407 }
2408 else {
2409 *p_name = dot+1;
2410 len = dot-name;
2411 }
2412 if (len == 0) {
2413 PyErr_SetString(PyExc_ValueError,
2414 "Empty module name");
2415 return NULL;
2416 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002417
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002418 p = buf + *p_buflen;
2419 if (p != buf)
2420 *p++ = '.';
2421 if (p+len-buf >= MAXPATHLEN) {
2422 PyErr_SetString(PyExc_ValueError,
2423 "Module name too long");
2424 return NULL;
2425 }
2426 strncpy(p, name, len);
2427 p[len] = '\0';
2428 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002429
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002430 result = import_submodule(mod, p, buf);
2431 if (result == Py_None && altmod != mod) {
2432 Py_DECREF(result);
2433 /* Here, altmod must be None and mod must not be None */
2434 result = import_submodule(altmod, p, p);
2435 if (result != NULL && result != Py_None) {
2436 if (mark_miss(buf) != 0) {
2437 Py_DECREF(result);
2438 return NULL;
2439 }
2440 strncpy(buf, name, len);
2441 buf[len] = '\0';
2442 *p_buflen = len;
2443 }
2444 }
2445 if (result == NULL)
2446 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002447
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002448 if (result == Py_None) {
2449 Py_DECREF(result);
2450 PyErr_Format(PyExc_ImportError,
2451 "No module named %.200s", name);
2452 return NULL;
2453 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002454
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002455 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002456}
2457
2458static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002459mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002460{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002461 PyObject *modules = PyImport_GetModuleDict();
2462 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002463}
2464
2465static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002466ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002467 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002468{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002469 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002470
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002471 if (!PyObject_HasAttrString(mod, "__path__"))
2472 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002474 for (i = 0; ; i++) {
2475 PyObject *item = PySequence_GetItem(fromlist, i);
2476 int hasit;
2477 if (item == NULL) {
2478 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2479 PyErr_Clear();
2480 return 1;
2481 }
2482 return 0;
2483 }
2484 if (!PyUnicode_Check(item)) {
2485 PyErr_SetString(PyExc_TypeError,
2486 "Item in ``from list'' not a string");
2487 Py_DECREF(item);
2488 return 0;
2489 }
2490 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2491 PyObject *all;
2492 Py_DECREF(item);
2493 /* See if the package defines __all__ */
2494 if (recursive)
2495 continue; /* Avoid endless recursion */
2496 all = PyObject_GetAttrString(mod, "__all__");
2497 if (all == NULL)
2498 PyErr_Clear();
2499 else {
2500 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2501 Py_DECREF(all);
2502 if (!ret)
2503 return 0;
2504 }
2505 continue;
2506 }
2507 hasit = PyObject_HasAttr(mod, item);
2508 if (!hasit) {
2509 PyObject *item8;
2510 char *subname;
2511 PyObject *submod;
2512 char *p;
2513 if (!Py_FileSystemDefaultEncoding) {
2514 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2515 PyUnicode_GetSize(item),
2516 NULL);
2517 } else {
2518 item8 = PyUnicode_AsEncodedString(item,
2519 Py_FileSystemDefaultEncoding, NULL);
2520 }
2521 if (!item8) {
2522 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2523 return 0;
2524 }
2525 subname = PyBytes_AS_STRING(item8);
2526 if (buflen + strlen(subname) >= MAXPATHLEN) {
2527 PyErr_SetString(PyExc_ValueError,
2528 "Module name too long");
2529 Py_DECREF(item);
2530 return 0;
2531 }
2532 p = buf + buflen;
2533 *p++ = '.';
2534 strcpy(p, subname);
2535 submod = import_submodule(mod, subname, buf);
2536 Py_DECREF(item8);
2537 Py_XDECREF(submod);
2538 if (submod == NULL) {
2539 Py_DECREF(item);
2540 return 0;
2541 }
2542 }
2543 Py_DECREF(item);
2544 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002545
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002546 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002547}
2548
Neil Schemenauer00b09662003-06-16 21:03:07 +00002549static int
2550add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002551 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002552{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002553 if (mod == Py_None)
2554 return 1;
2555 /* Irrespective of the success of this load, make a
2556 reference to it in the parent package module. A copy gets
2557 saved in the modules dictionary under the full name, so get a
2558 reference from there, if need be. (The exception is when the
2559 load failed with a SyntaxError -- then there's no trace in
2560 sys.modules. In that case, of course, do nothing extra.) */
2561 if (submod == NULL) {
2562 submod = PyDict_GetItemString(modules, fullname);
2563 if (submod == NULL)
2564 return 1;
2565 }
2566 if (PyModule_Check(mod)) {
2567 /* We can't use setattr here since it can give a
2568 * spurious warning if the submodule name shadows a
2569 * builtin name */
2570 PyObject *dict = PyModule_GetDict(mod);
2571 if (!dict)
2572 return 0;
2573 if (PyDict_SetItemString(dict, subname, submod) < 0)
2574 return 0;
2575 }
2576 else {
2577 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2578 return 0;
2579 }
2580 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002581}
2582
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002583static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002584import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002585{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002586 PyObject *modules = PyImport_GetModuleDict();
2587 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002588
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002589 /* Require:
2590 if mod == None: subname == fullname
2591 else: mod.__name__ + "." + subname == fullname
2592 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002594 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2595 Py_INCREF(m);
2596 }
2597 else {
2598 PyObject *path, *loader = NULL;
2599 char buf[MAXPATHLEN+1];
2600 struct filedescr *fdp;
2601 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002602
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002603 if (mod == Py_None)
2604 path = NULL;
2605 else {
2606 path = PyObject_GetAttrString(mod, "__path__");
2607 if (path == NULL) {
2608 PyErr_Clear();
2609 Py_INCREF(Py_None);
2610 return Py_None;
2611 }
2612 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002613
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002614 buf[0] = '\0';
2615 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2616 &fp, &loader);
2617 Py_XDECREF(path);
2618 if (fdp == NULL) {
2619 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2620 return NULL;
2621 PyErr_Clear();
2622 Py_INCREF(Py_None);
2623 return Py_None;
2624 }
2625 m = load_module(fullname, fp, buf, fdp->type, loader);
2626 Py_XDECREF(loader);
2627 if (fp)
2628 fclose(fp);
2629 if (!add_submodule(mod, m, fullname, subname, modules)) {
2630 Py_XDECREF(m);
2631 m = NULL;
2632 }
2633 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002634
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002635 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002636}
2637
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002638
2639/* Re-import a module of any kind and return its module object, WITH
2640 INCREMENTED REFERENCE COUNT */
2641
Guido van Rossum79f25d91997-04-29 20:08:16 +00002642PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002643PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002644{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002645 PyInterpreterState *interp = PyThreadState_Get()->interp;
2646 PyObject *modules_reloading = interp->modules_reloading;
2647 PyObject *modules = PyImport_GetModuleDict();
2648 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2649 char *name, *subname;
2650 char buf[MAXPATHLEN+1];
2651 struct filedescr *fdp;
2652 FILE *fp = NULL;
2653 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002654
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002655 if (modules_reloading == NULL) {
2656 Py_FatalError("PyImport_ReloadModule: "
2657 "no modules_reloading dictionary!");
2658 return NULL;
2659 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002660
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002661 if (m == NULL || !PyModule_Check(m)) {
2662 PyErr_SetString(PyExc_TypeError,
2663 "reload() argument must be module");
2664 return NULL;
2665 }
2666 name = (char*)PyModule_GetName(m);
2667 if (name == NULL)
2668 return NULL;
2669 if (m != PyDict_GetItemString(modules, name)) {
2670 PyErr_Format(PyExc_ImportError,
2671 "reload(): module %.200s not in sys.modules",
2672 name);
2673 return NULL;
2674 }
2675 existing_m = PyDict_GetItemString(modules_reloading, name);
2676 if (existing_m != NULL) {
2677 /* Due to a recursive reload, this module is already
2678 being reloaded. */
2679 Py_INCREF(existing_m);
2680 return existing_m;
2681 }
2682 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2683 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002684
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002685 subname = strrchr(name, '.');
2686 if (subname == NULL)
2687 subname = name;
2688 else {
2689 PyObject *parentname, *parent;
2690 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2691 if (parentname == NULL) {
2692 imp_modules_reloading_clear();
2693 return NULL;
2694 }
2695 parent = PyDict_GetItem(modules, parentname);
2696 if (parent == NULL) {
2697 PyErr_Format(PyExc_ImportError,
2698 "reload(): parent %U not in sys.modules",
2699 parentname);
2700 Py_DECREF(parentname);
2701 imp_modules_reloading_clear();
2702 return NULL;
2703 }
2704 Py_DECREF(parentname);
2705 subname++;
2706 path = PyObject_GetAttrString(parent, "__path__");
2707 if (path == NULL)
2708 PyErr_Clear();
2709 }
2710 buf[0] = '\0';
2711 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2712 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002713
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002714 if (fdp == NULL) {
2715 Py_XDECREF(loader);
2716 imp_modules_reloading_clear();
2717 return NULL;
2718 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002719
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002720 newm = load_module(name, fp, buf, fdp->type, loader);
2721 Py_XDECREF(loader);
2722
2723 if (fp)
2724 fclose(fp);
2725 if (newm == NULL) {
2726 /* load_module probably removed name from modules because of
2727 * the error. Put back the original module object. We're
2728 * going to return NULL in this case regardless of whether
2729 * replacing name succeeds, so the return value is ignored.
2730 */
2731 PyDict_SetItemString(modules, name, m);
2732 }
2733 imp_modules_reloading_clear();
2734 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002735}
2736
2737
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002738/* Higher-level import emulator which emulates the "import" statement
2739 more accurately -- it invokes the __import__() function from the
2740 builtins of the current globals. This means that the import is
2741 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002742 environment, e.g. by "rexec".
2743 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002744 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002745 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002746
2747PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002748PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002749{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002750 static PyObject *silly_list = NULL;
2751 static PyObject *builtins_str = NULL;
2752 static PyObject *import_str = NULL;
2753 PyObject *globals = NULL;
2754 PyObject *import = NULL;
2755 PyObject *builtins = NULL;
2756 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002757
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002758 /* Initialize constant string objects */
2759 if (silly_list == NULL) {
2760 import_str = PyUnicode_InternFromString("__import__");
2761 if (import_str == NULL)
2762 return NULL;
2763 builtins_str = PyUnicode_InternFromString("__builtins__");
2764 if (builtins_str == NULL)
2765 return NULL;
2766 silly_list = Py_BuildValue("[s]", "__doc__");
2767 if (silly_list == NULL)
2768 return NULL;
2769 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002771 /* Get the builtins from current globals */
2772 globals = PyEval_GetGlobals();
2773 if (globals != NULL) {
2774 Py_INCREF(globals);
2775 builtins = PyObject_GetItem(globals, builtins_str);
2776 if (builtins == NULL)
2777 goto err;
2778 }
2779 else {
2780 /* No globals -- use standard builtins, and fake globals */
2781 builtins = PyImport_ImportModuleLevel("builtins",
2782 NULL, NULL, NULL, 0);
2783 if (builtins == NULL)
2784 return NULL;
2785 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2786 if (globals == NULL)
2787 goto err;
2788 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002789
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002790 /* Get the __import__ function from the builtins */
2791 if (PyDict_Check(builtins)) {
2792 import = PyObject_GetItem(builtins, import_str);
2793 if (import == NULL)
2794 PyErr_SetObject(PyExc_KeyError, import_str);
2795 }
2796 else
2797 import = PyObject_GetAttr(builtins, import_str);
2798 if (import == NULL)
2799 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002801 /* Call the __import__ function with the proper argument list
2802 * Always use absolute import here. */
2803 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2804 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002805
2806 err:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002807 Py_XDECREF(globals);
2808 Py_XDECREF(builtins);
2809 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002810
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002811 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002812}
2813
2814
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002815/* Module 'imp' provides Python access to the primitives used for
2816 importing modules.
2817*/
2818
Guido van Rossum79f25d91997-04-29 20:08:16 +00002819static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002820imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002821{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002822 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002823
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002824 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2825 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2826 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2827 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002828
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002829 return PyBytes_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002830}
2831
Guido van Rossum79f25d91997-04-29 20:08:16 +00002832static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002833imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002834{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002835 PyObject *list;
2836 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002837
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002838 list = PyList_New(0);
2839 if (list == NULL)
2840 return NULL;
2841 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2842 PyObject *item = Py_BuildValue("ssi",
2843 fdp->suffix, fdp->mode, fdp->type);
2844 if (item == NULL) {
2845 Py_DECREF(list);
2846 return NULL;
2847 }
2848 if (PyList_Append(list, item) < 0) {
2849 Py_DECREF(list);
2850 Py_DECREF(item);
2851 return NULL;
2852 }
2853 Py_DECREF(item);
2854 }
2855 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002856}
2857
Guido van Rossum79f25d91997-04-29 20:08:16 +00002858static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002859call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002860{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002861 extern int fclose(FILE *);
2862 PyObject *fob, *ret;
2863 PyObject *pathobj;
2864 struct filedescr *fdp;
2865 char pathname[MAXPATHLEN+1];
2866 FILE *fp = NULL;
2867 int fd = -1;
2868 char *found_encoding = NULL;
2869 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002870
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002871 pathname[0] = '\0';
2872 if (path == Py_None)
2873 path = NULL;
2874 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2875 if (fdp == NULL)
2876 return NULL;
2877 if (fp != NULL) {
2878 fd = fileno(fp);
2879 if (fd != -1)
2880 fd = dup(fd);
2881 fclose(fp);
2882 fp = NULL;
2883 }
2884 if (fd != -1) {
2885 if (strchr(fdp->mode, 'b') == NULL) {
2886 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
2887 memory. */
2888 found_encoding = PyTokenizer_FindEncoding(fd);
2889 lseek(fd, 0, 0); /* Reset position */
2890 if (found_encoding == NULL && PyErr_Occurred())
2891 return NULL;
2892 encoding = (found_encoding != NULL) ? found_encoding :
2893 (char*)PyUnicode_GetDefaultEncoding();
2894 }
2895 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
2896 (char*)encoding, NULL, NULL, 1);
2897 if (fob == NULL) {
2898 close(fd);
2899 PyMem_FREE(found_encoding);
2900 return NULL;
2901 }
2902 }
2903 else {
2904 fob = Py_None;
2905 Py_INCREF(fob);
2906 }
2907 pathobj = PyUnicode_DecodeFSDefault(pathname);
2908 ret = Py_BuildValue("NN(ssi)",
2909 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
2910 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002911
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002912 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002913}
2914
Guido van Rossum79f25d91997-04-29 20:08:16 +00002915static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002916imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002917{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002918 char *name;
2919 PyObject *ret, *path = NULL;
2920 if (!PyArg_ParseTuple(args, "es|O:find_module",
2921 Py_FileSystemDefaultEncoding, &name,
2922 &path))
2923 return NULL;
2924 ret = call_find_module(name, path);
2925 PyMem_Free(name);
2926 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002927}
2928
2929static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002930imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002931{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002932 char *name;
2933 int ret;
2934 PyObject *m;
2935 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2936 return NULL;
2937 ret = init_builtin(name);
2938 if (ret < 0)
2939 return NULL;
2940 if (ret == 0) {
2941 Py_INCREF(Py_None);
2942 return Py_None;
2943 }
2944 m = PyImport_AddModule(name);
2945 Py_XINCREF(m);
2946 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002947}
2948
Guido van Rossum79f25d91997-04-29 20:08:16 +00002949static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002950imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002951{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002952 char *name;
2953 int ret;
2954 PyObject *m;
2955 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2956 return NULL;
2957 ret = PyImport_ImportFrozenModule(name);
2958 if (ret < 0)
2959 return NULL;
2960 if (ret == 0) {
2961 Py_INCREF(Py_None);
2962 return Py_None;
2963 }
2964 m = PyImport_AddModule(name);
2965 Py_XINCREF(m);
2966 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002967}
2968
Guido van Rossum79f25d91997-04-29 20:08:16 +00002969static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002970imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002971{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002972 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002973
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002974 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2975 return NULL;
2976 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002977}
2978
Guido van Rossum79f25d91997-04-29 20:08:16 +00002979static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00002980imp_is_frozen_package(PyObject *self, PyObject *args)
2981{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002982 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002983
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002984 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
2985 return NULL;
2986 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002987}
2988
2989static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002990imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002991{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002992 char *name;
2993 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2994 return NULL;
2995 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002996}
2997
Guido van Rossum79f25d91997-04-29 20:08:16 +00002998static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002999imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003000{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003001 char *name;
3002 struct _frozen *p;
3003 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3004 return NULL;
3005 p = find_frozen(name);
3006 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003007}
3008
3009static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003010get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003011{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003012 FILE *fp;
3013 if (mode[0] == 'U')
3014 mode = "r" PY_STDIOTEXTMODE;
3015 if (fob == NULL) {
3016 fp = fopen(pathname, mode);
3017 }
3018 else {
3019 int fd = PyObject_AsFileDescriptor(fob);
3020 if (fd == -1)
3021 return NULL;
3022 if (!_PyVerify_fd(fd))
3023 goto error;
3024 /* the FILE struct gets a new fd, so that it can be closed
3025 * independently of the file descriptor given
3026 */
3027 fd = dup(fd);
3028 if (fd == -1)
3029 goto error;
3030 fp = fdopen(fd, mode);
3031 }
3032 if (fp)
3033 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003034error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003035 PyErr_SetFromErrno(PyExc_IOError);
3036 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003037}
3038
Guido van Rossum79f25d91997-04-29 20:08:16 +00003039static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003040imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003041{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003042 char *name;
3043 char *pathname;
3044 PyObject *fob = NULL;
3045 PyObject *m;
3046 FILE *fp;
3047 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3048 &name,
3049 Py_FileSystemDefaultEncoding, &pathname,
3050 &fob))
3051 return NULL;
3052 fp = get_file(pathname, fob, "rb");
3053 if (fp == NULL) {
3054 PyMem_Free(pathname);
3055 return NULL;
3056 }
3057 m = load_compiled_module(name, pathname, fp);
3058 fclose(fp);
3059 PyMem_Free(pathname);
3060 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003061}
3062
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003063#ifdef HAVE_DYNAMIC_LOADING
3064
Guido van Rossum79f25d91997-04-29 20:08:16 +00003065static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003066imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003067{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003068 char *name;
3069 char *pathname;
3070 PyObject *fob = NULL;
3071 PyObject *m;
3072 FILE *fp = NULL;
3073 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
3074 &name,
3075 Py_FileSystemDefaultEncoding, &pathname,
3076 &fob))
3077 return NULL;
3078 if (fob) {
3079 fp = get_file(pathname, fob, "r");
3080 if (fp == NULL) {
3081 PyMem_Free(pathname);
3082 return NULL;
3083 }
3084 }
3085 m = _PyImport_LoadDynamicModule(name, pathname, fp);
3086 PyMem_Free(pathname);
3087 if (fp)
3088 fclose(fp);
3089 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003090}
3091
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003092#endif /* HAVE_DYNAMIC_LOADING */
3093
Guido van Rossum79f25d91997-04-29 20:08:16 +00003094static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003095imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003096{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003097 char *name;
3098 char *pathname;
3099 PyObject *fob = NULL;
3100 PyObject *m;
3101 FILE *fp;
3102 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3103 &name,
3104 Py_FileSystemDefaultEncoding, &pathname,
3105 &fob))
3106 return NULL;
3107 fp = get_file(pathname, fob, "r");
3108 if (fp == NULL) {
3109 PyMem_Free(pathname);
3110 return NULL;
3111 }
3112 m = load_source_module(name, pathname, fp);
3113 PyMem_Free(pathname);
3114 fclose(fp);
3115 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116}
3117
Guido van Rossum79f25d91997-04-29 20:08:16 +00003118static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003119imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003120{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003121 char *name;
3122 PyObject *fob;
3123 char *pathname;
3124 PyObject * ret;
3125 char *suffix; /* Unused */
3126 char *mode;
3127 int type;
3128 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003130 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3131 &name, &fob,
3132 Py_FileSystemDefaultEncoding, &pathname,
3133 &suffix, &mode, &type))
3134 return NULL;
3135 if (*mode) {
3136 /* Mode must start with 'r' or 'U' and must not contain '+'.
3137 Implicit in this test is the assumption that the mode
3138 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003139
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003140 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3141 PyErr_Format(PyExc_ValueError,
3142 "invalid file open mode %.200s", mode);
3143 PyMem_Free(pathname);
3144 return NULL;
3145 }
3146 }
3147 if (fob == Py_None)
3148 fp = NULL;
3149 else {
3150 fp = get_file(NULL, fob, mode);
3151 if (fp == NULL) {
3152 PyMem_Free(pathname);
3153 return NULL;
3154 }
3155 }
3156 ret = load_module(name, fp, pathname, type, NULL);
3157 PyMem_Free(pathname);
3158 if (fp)
3159 fclose(fp);
3160 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003161}
3162
3163static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003164imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003165{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003166 char *name;
3167 char *pathname;
3168 PyObject * ret;
3169 if (!PyArg_ParseTuple(args, "ses:load_package",
3170 &name, Py_FileSystemDefaultEncoding, &pathname))
3171 return NULL;
3172 ret = load_package(name, pathname);
3173 PyMem_Free(pathname);
3174 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003175}
3176
3177static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003178imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003179{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003180 char *name;
3181 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3182 return NULL;
3183 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003184}
3185
Christian Heimes13a7a212008-01-07 17:13:09 +00003186static PyObject *
3187imp_reload(PyObject *self, PyObject *v)
3188{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003189 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003190}
3191
3192PyDoc_STRVAR(doc_reload,
3193"reload(module) -> module\n\
3194\n\
3195Reload the module. The module must have been successfully imported before.");
3196
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003197/* Doc strings */
3198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003199PyDoc_STRVAR(doc_imp,
3200"This module provides the components needed to build your own\n\
3201__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003203PyDoc_STRVAR(doc_find_module,
3204"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003205Search for a module. If path is omitted or None, search for a\n\
3206built-in, frozen or special module and continue search in sys.path.\n\
3207The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003208package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003210PyDoc_STRVAR(doc_load_module,
3211"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003212Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003213The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003215PyDoc_STRVAR(doc_get_magic,
3216"get_magic() -> string\n\
3217Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003219PyDoc_STRVAR(doc_get_suffixes,
3220"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003221Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003222that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003224PyDoc_STRVAR(doc_new_module,
3225"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003226Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003227The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003229PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003230"lock_held() -> boolean\n\
3231Return True if the import lock is currently held, else False.\n\
3232On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003233
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003234PyDoc_STRVAR(doc_acquire_lock,
3235"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003236Acquires the interpreter's import lock for the current thread.\n\
3237This lock should be used by import hooks to ensure thread-safety\n\
3238when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003239On platforms without threads, this function does nothing.");
3240
3241PyDoc_STRVAR(doc_release_lock,
3242"release_lock() -> None\n\
3243Release the interpreter's import lock.\n\
3244On platforms without threads, this function does nothing.");
3245
Guido van Rossum79f25d91997-04-29 20:08:16 +00003246static PyMethodDef imp_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003247 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3248 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3249 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3250 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3251 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3252 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3253 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3254 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3255 {"reload", imp_reload, METH_O, doc_reload},
3256 /* The rest are obsolete */
3257 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3258 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3259 {"init_builtin", imp_init_builtin, METH_VARARGS},
3260 {"init_frozen", imp_init_frozen, METH_VARARGS},
3261 {"is_builtin", imp_is_builtin, METH_VARARGS},
3262 {"is_frozen", imp_is_frozen, METH_VARARGS},
3263 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003264#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003265 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003266#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003267 {"load_package", imp_load_package, METH_VARARGS},
3268 {"load_source", imp_load_source, METH_VARARGS},
3269 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003270};
3271
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003272static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003273setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003274{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003275 PyObject *v;
3276 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003277
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003278 v = PyLong_FromLong((long)value);
3279 err = PyDict_SetItemString(d, name, v);
3280 Py_XDECREF(v);
3281 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003282}
3283
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003284typedef struct {
3285 PyObject_HEAD
3286} NullImporter;
3287
3288static int
3289NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3290{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003291 char *path;
3292 Py_ssize_t pathlen;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003294 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3295 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003296
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003297 if (!PyArg_ParseTuple(args, "es:NullImporter",
3298 Py_FileSystemDefaultEncoding, &path))
3299 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003300
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003301 pathlen = strlen(path);
3302 if (pathlen == 0) {
3303 PyMem_Free(path);
3304 PyErr_SetString(PyExc_ImportError, "empty pathname");
3305 return -1;
3306 } else {
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003307#ifndef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003308 struct stat statbuf;
3309 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003310
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003311 rv = stat(path, &statbuf);
3312 PyMem_Free(path);
3313 if (rv == 0) {
3314 /* it exists */
3315 if (S_ISDIR(statbuf.st_mode)) {
3316 /* it's a directory */
3317 PyErr_SetString(PyExc_ImportError,
3318 "existing directory");
3319 return -1;
3320 }
3321 }
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003322#else /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003323 DWORD rv;
3324 /* see issue1293 and issue3677:
3325 * stat() on Windows doesn't recognise paths like
3326 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3327 */
3328 rv = GetFileAttributesA(path);
3329 PyMem_Free(path);
3330 if (rv != INVALID_FILE_ATTRIBUTES) {
3331 /* it exists */
3332 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3333 /* it's a directory */
3334 PyErr_SetString(PyExc_ImportError,
3335 "existing directory");
3336 return -1;
3337 }
3338 }
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003339#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003340 }
3341 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003342}
3343
3344static PyObject *
3345NullImporter_find_module(NullImporter *self, PyObject *args)
3346{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003347 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003348}
3349
3350static PyMethodDef NullImporter_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003351 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3352 "Always return None"
3353 },
3354 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003355};
3356
3357
Christian Heimes9cd17752007-11-18 19:35:23 +00003358PyTypeObject PyNullImporter_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003359 PyVarObject_HEAD_INIT(NULL, 0)
3360 "imp.NullImporter", /*tp_name*/
3361 sizeof(NullImporter), /*tp_basicsize*/
3362 0, /*tp_itemsize*/
3363 0, /*tp_dealloc*/
3364 0, /*tp_print*/
3365 0, /*tp_getattr*/
3366 0, /*tp_setattr*/
3367 0, /*tp_reserved*/
3368 0, /*tp_repr*/
3369 0, /*tp_as_number*/
3370 0, /*tp_as_sequence*/
3371 0, /*tp_as_mapping*/
3372 0, /*tp_hash */
3373 0, /*tp_call*/
3374 0, /*tp_str*/
3375 0, /*tp_getattro*/
3376 0, /*tp_setattro*/
3377 0, /*tp_as_buffer*/
3378 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3379 "Null importer object", /* tp_doc */
3380 0, /* tp_traverse */
3381 0, /* tp_clear */
3382 0, /* tp_richcompare */
3383 0, /* tp_weaklistoffset */
3384 0, /* tp_iter */
3385 0, /* tp_iternext */
3386 NullImporter_methods, /* tp_methods */
3387 0, /* tp_members */
3388 0, /* tp_getset */
3389 0, /* tp_base */
3390 0, /* tp_dict */
3391 0, /* tp_descr_get */
3392 0, /* tp_descr_set */
3393 0, /* tp_dictoffset */
3394 (initproc)NullImporter_init, /* tp_init */
3395 0, /* tp_alloc */
3396 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003397};
3398
Martin v. Löwis1a214512008-06-11 05:26:20 +00003399static struct PyModuleDef impmodule = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003400 PyModuleDef_HEAD_INIT,
3401 "imp",
3402 doc_imp,
3403 0,
3404 imp_methods,
3405 NULL,
3406 NULL,
3407 NULL,
3408 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003409};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003410
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003411PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003412PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003413{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003414 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003415
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003416 if (PyType_Ready(&PyNullImporter_Type) < 0)
3417 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003418
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003419 m = PyModule_Create(&impmodule);
3420 if (m == NULL)
3421 goto failure;
3422 d = PyModule_GetDict(m);
3423 if (d == NULL)
3424 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003425
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003426 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3427 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3428 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3429 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3430 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3431 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3432 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3433 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3434 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3435 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003436
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003437 Py_INCREF(&PyNullImporter_Type);
3438 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3439 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003440 failure:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003441 Py_XDECREF(m);
3442 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +00003443
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003444}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003445
3446
Guido van Rossumb18618d2000-05-03 23:44:39 +00003447/* API for embedding applications that want to add their own entries
3448 to the table of built-in modules. This should normally be called
3449 *before* Py_Initialize(). When the table resize fails, -1 is
3450 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003451
3452 After a similar function by Just van Rossum. */
3453
3454int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003455PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003456{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003457 static struct _inittab *our_copy = NULL;
3458 struct _inittab *p;
3459 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003460
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003461 /* Count the number of entries in both tables */
3462 for (n = 0; newtab[n].name != NULL; n++)
3463 ;
3464 if (n == 0)
3465 return 0; /* Nothing to do */
3466 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3467 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003468
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003469 /* Allocate new memory for the combined table */
3470 p = our_copy;
3471 PyMem_RESIZE(p, struct _inittab, i+n+1);
3472 if (p == NULL)
3473 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003474
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003475 /* Copy the tables into the new memory */
3476 if (our_copy != PyImport_Inittab)
3477 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3478 PyImport_Inittab = our_copy = p;
3479 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003480
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003481 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003482}
3483
3484/* Shorthand to add a single entry given a name and a function */
3485
3486int
Brett Cannona826f322009-04-02 03:41:46 +00003487PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003488{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003489 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003490
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003491 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003492
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003493 newtab[0].name = (char *)name;
3494 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003495
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003496 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003497}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003498
3499#ifdef __cplusplus
3500}
3501#endif