blob: 33cb81c8dcdd8e4bf87aabb852a902d6a960ee9a [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
22extern "C" {
23#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
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000030extern time_t PyOS_GetLastModificationTime(char *, FILE *);
31 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Guido van Rossum45aecf42006-03-15 04:58:47 +000040 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000041 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000048 Known values:
49 Python 1.5: 20121
50 Python 1.5.1: 20121
51 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Python 2.0: 50823
54 Python 2.0.1: 50823
55 Python 2.1: 60202
56 Python 2.1.1: 60202
57 Python 2.1.2: 60202
58 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000059 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000060 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000061 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000062 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000063 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000064 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000065 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000066 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000067 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000068 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
70 Python 2.5b3: 62111 (fix wrong code: x += yield)
71 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
72 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000073 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000074 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000075 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000076 Python 3000: 3000
Brett Cannone2e23ef2006-08-25 05:05:30 +000077 3010 (removed UNARY_CONVERT)
Guido van Rossum86e58e22006-08-28 15:27:34 +000078 3020 (added BUILD_SET)
Guido van Rossum4f72a782006-10-27 23:31:49 +000079 3030 (added keyword-only parameters)
Guido van Rossum3203bdc2006-12-28 21:03:31 +000080 3040 (added signature annotations)
Guido van Rossum452bf512007-02-09 05:32:43 +000081 3050 (print becomes a function)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000082 3060 (PEP 3115 metaclass syntax)
Guido van Rossum00bc0e02007-10-15 02:52:41 +000083 3070 (PEP 3109 raise changes)
84 3080 (PEP 3137 make __file__ and __name__ unicode)
Guido van Rossum98297ee2007-11-06 21:34:58 +000085 3090 (kill str8 interning)
Christian Heimes99170a52007-12-19 02:07:34 +000086 3100 (merge from 2.6a0, see 62151)
Christian Heimes3b06e532008-01-07 20:12:44 +000087 3102 (__file__ points to source file)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000088 Python 3.0a4: 3110 (WITH_CLEANUP optimization).
Tim Peters36515e22001-11-18 04:06:29 +000089*/
Christian Heimesdd15f6c2008-03-16 00:07:10 +000090#define MAGIC (3110 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000091
Guido van Rossum96774c12000-05-01 20:19:08 +000092/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000093 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000094 compiler works which are enabled by command line switches. */
95static long pyc_magic = MAGIC;
96
Guido van Rossum25ce5661997-08-02 03:10:38 +000097/* See _PyImport_FixupExtension() below */
98static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000099
Guido van Rossum771c6c81997-10-31 18:37:24 +0000100/* This table is defined in config.c: */
101extern struct _inittab _PyImport_Inittab[];
102
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000103/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000104extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000105
Guido van Rossum771c6c81997-10-31 18:37:24 +0000106struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000107
Guido van Rossumed1170e1999-12-20 21:23:41 +0000108/* these tables define the module suffixes that Python recognizes */
109struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000110
Guido van Rossumed1170e1999-12-20 21:23:41 +0000111static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000112 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000113#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000114 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000115#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000116 {".pyc", "rb", PY_COMPILED},
117 {0, 0}
118};
119
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000121/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122
123void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000124_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000126 const struct filedescr *scan;
127 struct filedescr *filetab;
128 int countD = 0;
129 int countS = 0;
130
131 /* prepare _PyImport_Filetab: copy entries from
132 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
133 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000134#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
136 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000137#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
139 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 if (filetab == NULL)
142 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000143#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000144 memcpy(filetab, _PyImport_DynLoadFiletab,
145 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000146#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000147 memcpy(filetab + countD, _PyImport_StandardFiletab,
148 countS * sizeof(struct filedescr));
149 filetab[countD + countS].suffix = NULL;
150
151 _PyImport_Filetab = filetab;
152
Guido van Rossum0824f631997-03-11 18:37:35 +0000153 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000154 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
155 for (; filetab->suffix != NULL; filetab++) {
156 if (strcmp(filetab->suffix, ".pyc") == 0)
157 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000158 }
159 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000160
Guido van Rossum572dbf82007-04-27 23:53:51 +0000161 {
Guido van Rossum96774c12000-05-01 20:19:08 +0000162 /* Fix the pyc_magic so that byte compiled code created
163 using the all-Unicode method doesn't interfere with
164 code created in normal operation mode. */
165 pyc_magic = MAGIC + 1;
166 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167}
168
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169void
Just van Rossum52e14d62002-12-30 22:08:05 +0000170_PyImportHooks_Init(void)
171{
172 PyObject *v, *path_hooks = NULL, *zimpimport;
173 int err = 0;
174
175 /* adding sys.path_hooks and sys.path_importer_cache, setting up
176 zipimport */
Christian Heimes9cd17752007-11-18 19:35:23 +0000177 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000178 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000179
180 if (Py_VerboseFlag)
181 PySys_WriteStderr("# installing zipimport hook\n");
182
183 v = PyList_New(0);
184 if (v == NULL)
185 goto error;
186 err = PySys_SetObject("meta_path", v);
187 Py_DECREF(v);
188 if (err)
189 goto error;
190 v = PyDict_New();
191 if (v == NULL)
192 goto error;
193 err = PySys_SetObject("path_importer_cache", v);
194 Py_DECREF(v);
195 if (err)
196 goto error;
197 path_hooks = PyList_New(0);
198 if (path_hooks == NULL)
199 goto error;
200 err = PySys_SetObject("path_hooks", path_hooks);
201 if (err) {
202 error:
203 PyErr_Print();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
205 "path_importer_cache, or NullImporter failed"
206 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000207 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000208
Just van Rossum52e14d62002-12-30 22:08:05 +0000209 zimpimport = PyImport_ImportModule("zipimport");
210 if (zimpimport == NULL) {
211 PyErr_Clear(); /* No zip import module -- okay */
212 if (Py_VerboseFlag)
213 PySys_WriteStderr("# can't import zipimport\n");
214 }
215 else {
216 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
217 "zipimporter");
218 Py_DECREF(zimpimport);
219 if (zipimporter == NULL) {
220 PyErr_Clear(); /* No zipimporter object -- okay */
221 if (Py_VerboseFlag)
222 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000223 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000224 }
225 else {
226 /* sys.path_hooks.append(zipimporter) */
227 err = PyList_Append(path_hooks, zipimporter);
228 Py_DECREF(zipimporter);
229 if (err)
230 goto error;
231 if (Py_VerboseFlag)
232 PySys_WriteStderr(
233 "# installed zipimport hook\n");
234 }
235 }
236 Py_DECREF(path_hooks);
237}
238
239void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000240_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241{
242 Py_XDECREF(extensions);
243 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000244 PyMem_DEL(_PyImport_Filetab);
245 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000246}
247
248
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000249/* Locking primitives to prevent parallel imports of the same module
250 in different threads to return with a partially loaded module.
251 These calls are serialized by the global interpreter lock. */
252
253#ifdef WITH_THREAD
254
Guido van Rossum49b56061998-10-01 20:42:43 +0000255#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000256
Guido van Rossum65d5b571998-12-21 19:32:43 +0000257static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000258static long import_lock_thread = -1;
259static int import_lock_level = 0;
260
261static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000262lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000263{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000264 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265 if (me == -1)
266 return; /* Too bad */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000267 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000268 import_lock = PyThread_allocate_lock();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269 if (import_lock == NULL)
270 return; /* Nothing much we can do. */
271 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272 if (import_lock_thread == me) {
273 import_lock_level++;
274 return;
275 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
277 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000278 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000279 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280 PyEval_RestoreThread(tstate);
281 }
282 import_lock_thread = me;
283 import_lock_level = 1;
284}
285
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000286static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000287unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000288{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000289 long me = PyThread_get_thread_ident();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000290 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000291 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000292 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000293 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000294 import_lock_level--;
295 if (import_lock_level == 0) {
296 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000297 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000298 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000299 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300}
301
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000302/* This function is called from PyOS_AfterFork to ensure that newly
303 created child processes do not share locks with the parent. */
304
305void
306_PyImport_ReInitLock(void)
307{
308#ifdef _AIX
309 if (import_lock != NULL)
310 import_lock = PyThread_allocate_lock();
311#endif
312}
313
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000314#else
315
316#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000317#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000318
319#endif
320
Tim Peters69232342001-08-30 05:16:13 +0000321static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000322imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000323{
Tim Peters69232342001-08-30 05:16:13 +0000324#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000325 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000326#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000327 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000328#endif
329}
330
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000332imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000334#ifdef WITH_THREAD
335 lock_import();
336#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000337 Py_INCREF(Py_None);
338 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000339}
340
341static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000342imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000344#ifdef WITH_THREAD
345 if (unlock_import() < 0) {
346 PyErr_SetString(PyExc_RuntimeError,
347 "not holding the import lock");
348 return NULL;
349 }
350#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000351 Py_INCREF(Py_None);
352 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353}
354
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355static void
356imp_modules_reloading_clear(void)
357{
358 PyInterpreterState *interp = PyThreadState_Get()->interp;
359 if (interp->modules_reloading != NULL)
360 PyDict_Clear(interp->modules_reloading);
361}
362
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363/* Helper for sys */
364
365PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000366PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000368 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369 if (interp->modules == NULL)
370 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
371 return interp->modules;
372}
373
Guido van Rossum3f5da241990-12-20 15:06:42 +0000374
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375/* List of names to clear in sys */
376static char* sys_deletes[] = {
Collin Winter670e6922007-03-21 02:57:17 +0000377 "path", "argv", "ps1", "ps2",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000378 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000379 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000380 /* misc stuff */
381 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000382 NULL
383};
384
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000385static char* sys_files[] = {
386 "stdin", "__stdin__",
387 "stdout", "__stdout__",
388 "stderr", "__stderr__",
389 NULL
390};
391
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000393/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000399 char *name;
400 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000401 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000402 PyObject *modules = interp->modules;
403
404 if (modules == NULL)
405 return; /* Already done */
406
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000407 /* Delete some special variables first. These are common
408 places where user values hide and people complain when their
409 destructors fail. Since the modules containing them are
410 deleted *last* of all, they would come too late in the normal
411 destruction order. Sigh. */
412
Georg Brandl1a3284e2007-12-02 09:40:06 +0000413 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414 if (value != NULL && PyModule_Check(value)) {
415 dict = PyModule_GetDict(value);
416 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000417 PySys_WriteStderr("# clear builtins._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000418 PyDict_SetItemString(dict, "_", Py_None);
419 }
420 value = PyDict_GetItemString(modules, "sys");
421 if (value != NULL && PyModule_Check(value)) {
422 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000423 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000424 dict = PyModule_GetDict(value);
425 for (p = sys_deletes; *p != NULL; p++) {
426 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000427 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000428 PyDict_SetItemString(dict, *p, Py_None);
429 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430 for (p = sys_files; *p != NULL; p+=2) {
431 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000432 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000433 v = PyDict_GetItemString(dict, *(p+1));
434 if (v == NULL)
435 v = Py_None;
436 PyDict_SetItemString(dict, *p, v);
437 }
438 }
439
440 /* First, delete __main__ */
441 value = PyDict_GetItemString(modules, "__main__");
442 if (value != NULL && PyModule_Check(value)) {
443 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000444 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000445 _PyModule_Clear(value);
446 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000447 }
448
Georg Brandl1a3284e2007-12-02 09:40:06 +0000449 /* The special treatment of "builtins" here is because even
Guido van Rossum758eec01998-01-19 21:58:26 +0000450 when it's not referenced as a module, its dictionary is
451 referenced by almost every module's __builtins__. Since
452 deleting a module clears its dictionary (even if there are
Georg Brandl1a3284e2007-12-02 09:40:06 +0000453 references left to it), we need to delete the "builtins"
Guido van Rossum758eec01998-01-19 21:58:26 +0000454 module last. Likewise, we don't delete sys until the very
455 end because it is implicitly referenced (e.g. by print).
456
457 Also note that we 'delete' modules by replacing their entry
458 in the modules dict with None, rather than really deleting
459 them; this avoids a rehash of the modules dictionary and
460 also marks them as "non existent" so they won't be
461 re-imported. */
462
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000463 /* Next, repeatedly delete modules with a reference count of
Georg Brandl1a3284e2007-12-02 09:40:06 +0000464 one (skipping builtins and sys) and delete them */
Guido van Rossum758eec01998-01-19 21:58:26 +0000465 do {
466 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000467 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000468 while (PyDict_Next(modules, &pos, &key, &value)) {
469 if (value->ob_refcnt != 1)
470 continue;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000471 if (PyUnicode_Check(key) && PyModule_Check(value)) {
472 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000473 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 continue;
475 if (strcmp(name, "sys") == 0)
476 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000477 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000478 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000479 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000480 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000481 PyDict_SetItem(modules, key, Py_None);
482 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000483 }
484 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000485 } while (ndone > 0);
486
Georg Brandl1a3284e2007-12-02 09:40:06 +0000487 /* Next, delete all modules (still skipping builtins and sys) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000488 pos = 0;
489 while (PyDict_Next(modules, &pos, &key, &value)) {
Neal Norwitz80e7f272007-08-26 06:45:23 +0000490 if (PyUnicode_Check(key) && PyModule_Check(value)) {
491 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000492 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000493 continue;
494 if (strcmp(name, "sys") == 0)
495 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000496 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000497 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000498 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000499 PyDict_SetItem(modules, key, Py_None);
500 }
501 }
502
Georg Brandl1a3284e2007-12-02 09:40:06 +0000503 /* Next, delete sys and builtins (in that order) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000504 value = PyDict_GetItemString(modules, "sys");
505 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000506 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000507 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000508 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000509 PyDict_SetItemString(modules, "sys", Py_None);
510 }
Georg Brandl1a3284e2007-12-02 09:40:06 +0000511 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossum758eec01998-01-19 21:58:26 +0000512 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000513 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000514 PySys_WriteStderr("# cleanup builtins\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000515 _PyModule_Clear(value);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000516 PyDict_SetItemString(modules, "builtins", Py_None);
Guido van Rossum758eec01998-01-19 21:58:26 +0000517 }
518
519 /* Finally, clear and delete the modules directory */
520 PyDict_Clear(modules);
521 interp->modules = NULL;
522 Py_DECREF(modules);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000524}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000525
526
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527/* Helper for pythonrun.c -- return magic number */
528
529long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000531{
Guido van Rossum96774c12000-05-01 20:19:08 +0000532 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000533}
534
535
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536/* Magic for extension modules (built-in as well as dynamically
537 loaded). To prevent initializing an extension module more than
538 once, we keep a static dictionary 'extensions' keyed by module name
539 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000540 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541 dictionary is stored by calling _PyImport_FixupExtension()
542 immediately after the module initialization function succeeds. A
543 copy can be retrieved from there by calling
544 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545
Guido van Rossum79f25d91997-04-29 20:08:16 +0000546PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549 PyObject *modules, *mod, *dict, *copy;
550 if (extensions == NULL) {
551 extensions = PyDict_New();
552 if (extensions == NULL)
553 return NULL;
554 }
555 modules = PyImport_GetModuleDict();
556 mod = PyDict_GetItemString(modules, name);
557 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000558 PyErr_Format(PyExc_SystemError,
559 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560 return NULL;
561 }
562 dict = PyModule_GetDict(mod);
563 if (dict == NULL)
564 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000565 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566 if (copy == NULL)
567 return NULL;
568 PyDict_SetItemString(extensions, filename, copy);
569 Py_DECREF(copy);
570 return copy;
571}
572
573PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000576 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 if (extensions == NULL)
578 return NULL;
579 dict = PyDict_GetItemString(extensions, filename);
580 if (dict == NULL)
581 return NULL;
582 mod = PyImport_AddModule(name);
583 if (mod == NULL)
584 return NULL;
585 mdict = PyModule_GetDict(mod);
586 if (mdict == NULL)
587 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000588 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000591 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592 name, filename);
593 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594}
595
596
597/* Get the module object corresponding to a module name.
598 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000599 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000600 Because the former action is most common, THIS DOES NOT RETURN A
601 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602
Guido van Rossum79f25d91997-04-29 20:08:16 +0000603PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000604PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000607 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000608
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000610 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000612 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000613 if (m == NULL)
614 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000617 return NULL;
618 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000619 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620
621 return m;
622}
623
Tim Peters1cd70172004-08-02 03:52:12 +0000624/* Remove name from sys.modules, if it's there. */
625static void
626_RemoveModule(const char *name)
627{
628 PyObject *modules = PyImport_GetModuleDict();
629 if (PyDict_GetItemString(modules, name) == NULL)
630 return;
631 if (PyDict_DelItemString(modules, name) < 0)
632 Py_FatalError("import: deleting existing key in"
633 "sys.modules failed");
634}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635
Christian Heimes3b06e532008-01-07 20:12:44 +0000636static PyObject * get_sourcefile(const char *file);
637
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000638/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000639 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
640 * removed from sys.modules, to avoid leaving damaged module objects
641 * in sys.modules. The caller may wish to restore the original
642 * module object (if any) in this case; PyImport_ReloadModule is an
643 * example.
644 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000645PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000647{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000648 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
649}
650
651PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000653{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656
Guido van Rossum79f25d91997-04-29 20:08:16 +0000657 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658 if (m == NULL)
659 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000660 /* If the module is being reloaded, we get the old module back
661 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000662 d = PyModule_GetDict(m);
663 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
664 if (PyDict_SetItemString(d, "__builtins__",
665 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000666 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000667 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000668 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000669 v = NULL;
670 if (pathname != NULL) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000671 v = get_sourcefile(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000672 if (v == NULL)
673 PyErr_Clear();
674 }
675 if (v == NULL) {
676 v = ((PyCodeObject *)co)->co_filename;
677 Py_INCREF(v);
678 }
679 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000680 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000681 Py_DECREF(v);
682
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000683 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000685 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000687
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000689 PyErr_Format(PyExc_ImportError,
690 "Loaded module %.200s not found in sys.modules",
691 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000692 return NULL;
693 }
694
Guido van Rossum79f25d91997-04-29 20:08:16 +0000695 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
697 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000698
699 error:
700 _RemoveModule(name);
701 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702}
703
704
705/* Given a pathname for a Python source file, fill a buffer with the
706 pathname for the corresponding compiled file. Return the pathname
707 for the compiled file, or NULL if there's no space in the buffer.
708 Doesn't set an exception. */
709
710static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712{
Tim Petersc1731372001-08-04 08:12:36 +0000713 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714 if (len+2 > buflen)
715 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000716
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000717#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000718 /* Treat .pyw as if it were .py. The case of ".pyw" must match
719 that used in _PyImport_StandardFiletab. */
720 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
721 --len; /* pretend 'w' isn't there */
722#endif
723 memcpy(buf, pathname, len);
724 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
725 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000726
727 return buf;
728}
729
730
731/* Given a pathname for a Python source file, its time of last
732 modification, and a pathname for a compiled file, check whether the
733 compiled file represents the same version of the source. If so,
734 return a FILE pointer for the compiled file, positioned just after
735 the header; if not, return NULL.
736 Doesn't set an exception. */
737
738static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000739check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740{
741 FILE *fp;
742 long magic;
743 long pyc_mtime;
744
745 fp = fopen(cpathname, "rb");
746 if (fp == NULL)
747 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000748 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000749 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000750 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000751 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000752 fclose(fp);
753 return NULL;
754 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000758 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759 fclose(fp);
760 return NULL;
761 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000762 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000763 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000764 return fp;
765}
766
767
768/* Read a code object from a file and check it for validity */
769
Guido van Rossum79f25d91997-04-29 20:08:16 +0000770static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000771read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000772{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000773 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000774
Tim Petersd9b9ac82001-01-28 00:27:39 +0000775 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000776 if (co == NULL)
777 return NULL;
778 if (!PyCode_Check(co)) {
779 PyErr_Format(PyExc_ImportError,
780 "Non-code object in %.200s", cpathname);
781 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000782 return NULL;
783 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785}
786
787
788/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000789 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000790
Guido van Rossum79f25d91997-04-29 20:08:16 +0000791static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000792load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793{
794 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000795 PyCodeObject *co;
796 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797
Guido van Rossum79f25d91997-04-29 20:08:16 +0000798 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000799 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000800 PyErr_Format(PyExc_ImportError,
801 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000802 return NULL;
803 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000804 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000805 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806 if (co == NULL)
807 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000808 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000809 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000811 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000812 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
814 return m;
815}
816
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817/* Parse a source file and return the corresponding code object */
818
Guido van Rossum79f25d91997-04-29 20:08:16 +0000819static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822 PyCodeObject *co = NULL;
823 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +0000824 PyCompilerFlags flags;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000825 PyArena *arena = PyArena_New();
826 if (arena == NULL)
827 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000828
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000829 mod = PyParser_ASTFromFile(fp, pathname, NULL,
Christian Heimes4d6ec852008-03-26 22:34:47 +0000830 Py_file_input, 0, 0, &flags,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000831 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000833 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000835 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836 return co;
837}
838
839
Guido van Rossum55a83382000-09-20 20:31:38 +0000840/* Helper to open a bytecode file for writing in exclusive mode */
841
842static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +0000843open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000844{
845#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
846 /* Use O_EXCL to avoid a race condition when another process tries to
847 write the same file. When that happens, our open() call fails,
848 which is just fine (since it's only a cache).
849 XXX If the file exists and is writable but the directory is not
850 writable, the file will never be written. Oh well.
851 */
852 int fd;
853 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000854 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
855#ifdef O_BINARY
856 |O_BINARY /* necessary for Windows */
857#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000858#ifdef __VMS
Christian Heimes05e8be12008-02-23 18:30:17 +0000859 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000860#else
Christian Heimes05e8be12008-02-23 18:30:17 +0000861 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000862#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000863 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000864 if (fd < 0)
865 return NULL;
866 return fdopen(fd, "wb");
867#else
868 /* Best we can do -- on Windows this can't happen anyway */
869 return fopen(filename, "wb");
870#endif
871}
872
873
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874/* Write a compiled module to a file, placing the time of last
875 modification of its source into the header.
876 Errors are ignored, if a write error occurs an attempt is made to
877 remove the file. */
878
879static void
Christian Heimes05e8be12008-02-23 18:30:17 +0000880write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881{
882 FILE *fp;
Christian Heimes05e8be12008-02-23 18:30:17 +0000883 time_t mtime = srcstat->st_mtime;
884 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885
Christian Heimes05e8be12008-02-23 18:30:17 +0000886 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000888 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000889 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890 "# can't create %s\n", cpathname);
891 return;
892 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000893 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000894 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000895 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
896 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000897 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000898 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000899 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900 /* Don't keep partial file */
901 fclose(fp);
902 (void) unlink(cpathname);
903 return;
904 }
905 /* Now write the true mtime */
906 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000908 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000909 fflush(fp);
910 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000912 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000913}
914
915
916/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000917 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
918 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000919
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000921load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000922{
Christian Heimes05e8be12008-02-23 18:30:17 +0000923 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000924 FILE *fpc;
925 char buf[MAXPATHLEN+1];
926 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000927 PyCodeObject *co;
928 PyObject *m;
Christian Heimes05e8be12008-02-23 18:30:17 +0000929
930 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000931 PyErr_Format(PyExc_RuntimeError,
Christian Heimes05e8be12008-02-23 18:30:17 +0000932 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000933 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000934 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000935 }
Fred Drake4c82b232000-06-30 16:18:57 +0000936#if SIZEOF_TIME_T > 4
937 /* Python's .pyc timestamp handling presumes that the timestamp fits
938 in 4 bytes. This will be fine until sometime in the year 2038,
939 when a 4-byte signed time_t will overflow.
940 */
Christian Heimes05e8be12008-02-23 18:30:17 +0000941 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000942 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000943 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000944 return NULL;
945 }
946#endif
Tim Peters36515e22001-11-18 04:06:29 +0000947 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000948 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949 if (cpathname != NULL &&
Christian Heimes05e8be12008-02-23 18:30:17 +0000950 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000951 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000952 fclose(fpc);
953 if (co == NULL)
954 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000955 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000956 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000957 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000958 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000959 }
960 else {
961 co = parse_source_module(pathname, fp);
962 if (co == NULL)
963 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000964 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000965 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000966 name, pathname);
Christian Heimes790c8232008-01-07 21:14:23 +0000967 if (cpathname) {
968 PyObject *ro = PySys_GetObject("dont_write_bytecode");
969 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes05e8be12008-02-23 18:30:17 +0000970 write_compiled_module(co, cpathname, &st);
Christian Heimes790c8232008-01-07 21:14:23 +0000971 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000972 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000973 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000974 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000975
976 return m;
977}
978
Christian Heimes3b06e532008-01-07 20:12:44 +0000979/* Get source file -> unicode or None
980 * Returns the path to the py file if available, else the given path
981 */
982static PyObject *
983get_sourcefile(const char *file)
984{
985 char py[MAXPATHLEN + 1];
986 Py_ssize_t len;
987 PyObject *u;
988 struct stat statbuf;
989
990 if (!file || !*file) {
991 Py_RETURN_NONE;
992 }
993
994 len = strlen(file);
Christian Heimes3540b502008-01-11 07:03:05 +0000995 /* match '*.py?' */
996 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000997 return PyUnicode_DecodeFSDefault(file);
998 }
999
1000 strncpy(py, file, len-1);
Martin v. Löwis5021ebc2008-03-22 22:07:13 +00001001 py[len-1] = '\0';
Christian Heimes3b06e532008-01-07 20:12:44 +00001002 if (stat(py, &statbuf) == 0 &&
1003 S_ISREG(statbuf.st_mode)) {
1004 u = PyUnicode_DecodeFSDefault(py);
1005 }
1006 else {
1007 u = PyUnicode_DecodeFSDefault(file);
1008 }
1009 return u;
1010}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001013static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1014static struct filedescr *find_module(char *, char *, PyObject *,
1015 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001016static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017
1018/* Load a package and return its module object WITH INCREMENTED
1019 REFERENCE COUNT */
1020
1021static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001022load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001023{
Tim Peters1cd70172004-08-02 03:52:12 +00001024 PyObject *m, *d;
1025 PyObject *file = NULL;
1026 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027 int err;
1028 char buf[MAXPATHLEN+1];
1029 FILE *fp = NULL;
1030 struct filedescr *fdp;
1031
1032 m = PyImport_AddModule(name);
1033 if (m == NULL)
1034 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001035 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001036 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001037 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001038 d = PyModule_GetDict(m);
Christian Heimes3b06e532008-01-07 20:12:44 +00001039 file = get_sourcefile(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001040 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001041 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001042 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001043 if (path == NULL)
1044 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001045 err = PyDict_SetItemString(d, "__file__", file);
1046 if (err == 0)
1047 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001048 if (err != 0)
1049 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001050 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001051 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001052 if (fdp == NULL) {
1053 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1054 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001055 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001056 }
1057 else
1058 m = NULL;
1059 goto cleanup;
1060 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001061 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062 if (fp != NULL)
1063 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001064 goto cleanup;
1065
1066 error:
1067 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001068 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001069 Py_XDECREF(path);
1070 Py_XDECREF(file);
1071 return m;
1072}
1073
1074
1075/* Helper to test for built-in module */
1076
1077static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001078is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001079{
1080 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001081 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1082 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1083 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001084 return -1;
1085 else
1086 return 1;
1087 }
1088 }
1089 return 0;
1090}
1091
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001092
Just van Rossum52e14d62002-12-30 22:08:05 +00001093/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1094 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001095 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001096 that can handle the path item. Return None if no hook could;
1097 this tells our caller it should fall back to the builtin
1098 import mechanism. Cache the result in path_importer_cache.
1099 Returns a borrowed reference. */
1100
1101static PyObject *
1102get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1103 PyObject *p)
1104{
1105 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001106 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001107
1108 /* These conditions are the caller's responsibility: */
1109 assert(PyList_Check(path_hooks));
1110 assert(PyDict_Check(path_importer_cache));
1111
1112 nhooks = PyList_Size(path_hooks);
1113 if (nhooks < 0)
1114 return NULL; /* Shouldn't happen */
1115
1116 importer = PyDict_GetItem(path_importer_cache, p);
1117 if (importer != NULL)
1118 return importer;
1119
1120 /* set path_importer_cache[p] to None to avoid recursion */
1121 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1122 return NULL;
1123
1124 for (j = 0; j < nhooks; j++) {
1125 PyObject *hook = PyList_GetItem(path_hooks, j);
1126 if (hook == NULL)
1127 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001129 if (importer != NULL)
1130 break;
1131
1132 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1133 return NULL;
1134 }
1135 PyErr_Clear();
1136 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001137 if (importer == NULL) {
1138 importer = PyObject_CallFunctionObjArgs(
Christian Heimes9cd17752007-11-18 19:35:23 +00001139 (PyObject *)&PyNullImporter_Type, p, NULL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001140 );
1141 if (importer == NULL) {
1142 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1143 PyErr_Clear();
1144 return Py_None;
1145 }
1146 }
1147 }
1148 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001149 int err = PyDict_SetItem(path_importer_cache, p, importer);
1150 Py_DECREF(importer);
1151 if (err != 0)
1152 return NULL;
1153 }
1154 return importer;
1155}
1156
Christian Heimes9cd17752007-11-18 19:35:23 +00001157PyAPI_FUNC(PyObject *)
1158PyImport_GetImporter(PyObject *path) {
1159 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1160
1161 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1162 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1163 importer = get_path_importer(path_importer_cache,
1164 path_hooks, path);
1165 }
1166 }
1167 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1168 return importer;
1169}
1170
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171/* Search the path (default sys.path) for a module. Return the
1172 corresponding filedescr struct, and (via return arguments) the
1173 pathname and an open file. Return NULL if the module is not found. */
1174
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001175#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001176extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001177 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001178#endif
1179
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001181static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001182static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001183
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001184static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001185find_module(char *fullname, char *subname, PyObject *path, char *buf,
1186 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001187{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001188 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001189 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001190 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001191 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001192 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001193 PyObject *path_hooks, *path_importer_cache;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001194 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001195 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1196 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1197 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001198 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001199#if defined(PYOS_OS2)
1200 size_t saved_len;
1201 size_t saved_namelen;
1202 char *saved_buf = NULL;
1203#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001204 if (p_loader != NULL)
1205 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001206
Just van Rossum52e14d62002-12-30 22:08:05 +00001207 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001208 PyErr_SetString(PyExc_OverflowError,
1209 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001210 return NULL;
1211 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001212 strcpy(name, subname);
1213
1214 /* sys.meta_path import hook */
1215 if (p_loader != NULL) {
1216 PyObject *meta_path;
1217
1218 meta_path = PySys_GetObject("meta_path");
1219 if (meta_path == NULL || !PyList_Check(meta_path)) {
1220 PyErr_SetString(PyExc_ImportError,
1221 "sys.meta_path must be a list of "
1222 "import hooks");
1223 return NULL;
1224 }
1225 Py_INCREF(meta_path); /* zap guard */
1226 npath = PyList_Size(meta_path);
1227 for (i = 0; i < npath; i++) {
1228 PyObject *loader;
1229 PyObject *hook = PyList_GetItem(meta_path, i);
1230 loader = PyObject_CallMethod(hook, "find_module",
1231 "sO", fullname,
1232 path != NULL ?
1233 path : Py_None);
1234 if (loader == NULL) {
1235 Py_DECREF(meta_path);
1236 return NULL; /* true error */
1237 }
1238 if (loader != Py_None) {
1239 /* a loader was found */
1240 *p_loader = loader;
1241 Py_DECREF(meta_path);
1242 return &importhookdescr;
1243 }
1244 Py_DECREF(loader);
1245 }
1246 Py_DECREF(meta_path);
1247 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001248
Guido van Rossum13d77992007-07-23 03:16:50 +00001249 if (path != NULL && PyUnicode_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001250 /* The only type of submodule allowed inside a "frozen"
1251 package are other frozen modules or packages. */
Guido van Rossum13d77992007-07-23 03:16:50 +00001252 char *p = PyUnicode_AsString(path);
1253 if (strlen(p) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001254 PyErr_SetString(PyExc_ImportError,
1255 "full frozen module name too long");
1256 return NULL;
1257 }
Guido van Rossum13d77992007-07-23 03:16:50 +00001258 strcpy(buf, p);
Guido van Rossum0506a431998-08-11 15:07:39 +00001259 strcat(buf, ".");
1260 strcat(buf, name);
1261 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001262 if (find_frozen(name) != NULL) {
1263 strcpy(buf, name);
1264 return &fd_frozen;
1265 }
1266 PyErr_Format(PyExc_ImportError,
1267 "No frozen submodule named %.200s", name);
1268 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001269 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001270 if (path == NULL) {
1271 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001272 strcpy(buf, name);
1273 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001274 }
Greg Ward201baee2001-10-04 14:52:06 +00001275 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001276 strcpy(buf, name);
1277 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001278 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001279
Guido van Rossumac279101996-08-22 23:10:58 +00001280#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001281 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1282 if (fp != NULL) {
1283 *p_fp = fp;
1284 return fdp;
1285 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001286#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001287 path = PySys_GetObject("path");
1288 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001289 if (path == NULL || !PyList_Check(path)) {
1290 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001291 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001292 return NULL;
1293 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001294
1295 path_hooks = PySys_GetObject("path_hooks");
1296 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1297 PyErr_SetString(PyExc_ImportError,
1298 "sys.path_hooks must be a list of "
1299 "import hooks");
1300 return NULL;
1301 }
1302 path_importer_cache = PySys_GetObject("path_importer_cache");
1303 if (path_importer_cache == NULL ||
1304 !PyDict_Check(path_importer_cache)) {
1305 PyErr_SetString(PyExc_ImportError,
1306 "sys.path_importer_cache must be a dict");
1307 return NULL;
1308 }
1309
Guido van Rossum79f25d91997-04-29 20:08:16 +00001310 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001311 namelen = strlen(name);
1312 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001313 PyObject *v = PyList_GetItem(path, i);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001314 PyObject *origv = v;
Guido van Rossum6262cc72007-05-09 23:29:27 +00001315 const char *base;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001316 Py_ssize_t size;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001317 if (!v)
1318 return NULL;
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001319 if (PyUnicode_Check(v)) {
1320 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1321 if (v == NULL)
1322 return NULL;
1323 }
1324 if (!PyString_Check(v))
1325 continue;
1326 base = PyString_AS_STRING(v);
1327 size = PyString_GET_SIZE(v);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001328 len = size;
Walter Dörwald3430d702002-06-17 10:43:59 +00001329 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001330 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001331 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001332 strcpy(buf, base);
Walter Dörwald3430d702002-06-17 10:43:59 +00001333 if (strlen(buf) != len) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001334 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001335 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001336
1337 /* sys.path_hooks import hook */
1338 if (p_loader != NULL) {
1339 PyObject *importer;
1340
1341 importer = get_path_importer(path_importer_cache,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001342 path_hooks, origv);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001343 if (importer == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001345 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346 /* Note: importer is a borrowed reference */
1347 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001348 PyObject *loader;
1349 loader = PyObject_CallMethod(importer,
1350 "find_module",
1351 "s", fullname);
1352 if (loader == NULL)
1353 return NULL; /* error */
1354 if (loader != Py_None) {
1355 /* a loader was found */
1356 *p_loader = loader;
1357 return &importhookdescr;
1358 }
1359 Py_DECREF(loader);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001360 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001361 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001362 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001364
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001365 if (len > 0 && buf[len-1] != SEP
1366#ifdef ALTSEP
1367 && buf[len-1] != ALTSEP
1368#endif
1369 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001370 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001371 strcpy(buf+len, name);
1372 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001373
1374 /* Check for package import (buf holds a directory name,
1375 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001376#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001377 if (stat(buf, &statbuf) == 0 && /* it exists */
1378 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001379 case_ok(buf, len, namelen, name)) { /* case matches */
1380 if (find_init_module(buf)) { /* and has __init__.py */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001381 return &fd_package;
1382 }
1383 else {
1384 char warnstr[MAXPATHLEN+80];
1385 sprintf(warnstr, "Not importing directory "
1386 "'%.*s': missing __init__.py",
1387 MAXPATHLEN, buf);
Skip Montanaro46fc3372007-08-12 11:44:53 +00001388 if (PyErr_WarnEx(PyExc_ImportWarning,
1389 warnstr, 1)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390 return NULL;
1391 }
1392 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001393 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001394#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001395#if defined(PYOS_OS2)
1396 /* take a snapshot of the module spec for restoration
1397 * after the 8 character DLL hackery
1398 */
1399 saved_buf = strdup(buf);
1400 saved_len = len;
1401 saved_namelen = namelen;
1402#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001403 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001404#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001405 /* OS/2 limits DLLs to 8 character names (w/o
1406 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001407 * so if the name is longer than that and its a
1408 * dynamically loaded module we're going to try,
1409 * truncate the name before trying
1410 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001411 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001412 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001413 const struct filedescr *scan;
1414 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001415 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001416 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001417 break;
1418 else
1419 scan++;
1420 }
1421 if (scan->suffix != NULL) {
1422 /* yes, so truncate the name */
1423 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001424 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001425 buf[len] = '\0';
1426 }
1427 }
1428#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001429 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001430 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001431 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001432 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001433 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001434 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001435 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001436 if (fp != NULL) {
1437 if (case_ok(buf, len, namelen, name))
1438 break;
1439 else { /* continue search */
1440 fclose(fp);
1441 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001442 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001443 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001444#if defined(PYOS_OS2)
1445 /* restore the saved snapshot */
1446 strcpy(buf, saved_buf);
1447 len = saved_len;
1448 namelen = saved_namelen;
1449#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001450 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001451#if defined(PYOS_OS2)
1452 /* don't need/want the module name snapshot anymore */
1453 if (saved_buf)
1454 {
1455 free(saved_buf);
1456 saved_buf = NULL;
1457 }
1458#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001459 if (fp != NULL)
1460 break;
1461 }
1462 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001463 PyErr_Format(PyExc_ImportError,
1464 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001465 return NULL;
1466 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001467 *p_fp = fp;
1468 return fdp;
1469}
1470
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001471/* Helpers for main.c
1472 * Find the source file corresponding to a named module
1473 */
1474struct filedescr *
1475_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1476 size_t buflen, FILE **p_fp, PyObject **p_loader)
1477{
1478 return find_module((char *) name, (char *) name, path,
1479 buf, buflen, p_fp, p_loader);
1480}
1481
1482PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1483{
1484 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1485}
1486
Martin v. Löwis18e16552006-02-15 17:27:45 +00001487/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001488 * The arguments here are tricky, best shown by example:
1489 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1490 * ^ ^ ^ ^
1491 * |--------------------- buf ---------------------|
1492 * |------------------- len ------------------|
1493 * |------ name -------|
1494 * |----- namelen -----|
1495 * buf is the full path, but len only counts up to (& exclusive of) the
1496 * extension. name is the module name, also exclusive of extension.
1497 *
1498 * We've already done a successful stat() or fopen() on buf, so know that
1499 * there's some match, possibly case-insensitive.
1500 *
Tim Peters50d8d372001-02-28 05:34:27 +00001501 * case_ok() is to return 1 if there's a case-sensitive match for
1502 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1503 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001504 *
Tim Peters50d8d372001-02-28 05:34:27 +00001505 * case_ok() is used to implement case-sensitive import semantics even
1506 * on platforms with case-insensitive filesystems. It's trivial to implement
1507 * for case-sensitive filesystems. It's pretty much a cross-platform
1508 * nightmare for systems with case-insensitive filesystems.
1509 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001510
Tim Peters50d8d372001-02-28 05:34:27 +00001511/* First we may need a pile of platform-specific header files; the sequence
1512 * of #if's here should match the sequence in the body of case_ok().
1513 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001514#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001515#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001516
Tim Peters50d8d372001-02-28 05:34:27 +00001517#elif defined(DJGPP)
1518#include <dir.h>
1519
Jason Tishler7961aa62005-05-20 00:56:54 +00001520#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001521#include <sys/types.h>
1522#include <dirent.h>
1523
Andrew MacIntyred9400542002-02-26 11:41:34 +00001524#elif defined(PYOS_OS2)
1525#define INCL_DOS
1526#define INCL_DOSERRORS
1527#define INCL_NOPMAPI
1528#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001529#endif
1530
Guido van Rossum0980bd91998-02-13 17:18:36 +00001531static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001533{
Tim Peters50d8d372001-02-28 05:34:27 +00001534/* Pick a platform-specific implementation; the sequence of #if's here should
1535 * match the sequence just above.
1536 */
1537
Jason Tishler7961aa62005-05-20 00:56:54 +00001538/* MS_WINDOWS */
1539#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001540 WIN32_FIND_DATA data;
1541 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001542
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001543 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001544 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001545
Guido van Rossum0980bd91998-02-13 17:18:36 +00001546 h = FindFirstFile(buf, &data);
1547 if (h == INVALID_HANDLE_VALUE) {
1548 PyErr_Format(PyExc_NameError,
1549 "Can't find file for module %.100s\n(filename %.300s)",
1550 name, buf);
1551 return 0;
1552 }
1553 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001554 return strncmp(data.cFileName, name, namelen) == 0;
1555
1556/* DJGPP */
1557#elif defined(DJGPP)
1558 struct ffblk ffblk;
1559 int done;
1560
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001561 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001562 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001563
1564 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1565 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001566 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001567 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001568 name, buf);
1569 return 0;
1570 }
Tim Peters50d8d372001-02-28 05:34:27 +00001571 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001572
Jason Tishler7961aa62005-05-20 00:56:54 +00001573/* new-fangled macintosh (macosx) or Cygwin */
1574#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001575 DIR *dirp;
1576 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001577 char dirname[MAXPATHLEN + 1];
1578 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001579
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001580 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001581 return 1;
1582
Tim Petersd1e87a82001-03-01 18:12:00 +00001583 /* Copy the dir component into dirname; substitute "." if empty */
1584 if (dirlen <= 0) {
1585 dirname[0] = '.';
1586 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001587 }
1588 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001589 assert(dirlen <= MAXPATHLEN);
1590 memcpy(dirname, buf, dirlen);
1591 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001592 }
1593 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001594 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001595 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001596 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001597 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001598 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001599#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001600 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001601#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001602 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001603#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001604 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001605 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001606 (void)closedir(dirp);
1607 return 1; /* Found */
1608 }
1609 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001610 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001611 }
Tim Peters430f5d42001-03-01 01:30:56 +00001612 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001613
Andrew MacIntyred9400542002-02-26 11:41:34 +00001614/* OS/2 */
1615#elif defined(PYOS_OS2)
1616 HDIR hdir = 1;
1617 ULONG srchcnt = 1;
1618 FILEFINDBUF3 ffbuf;
1619 APIRET rc;
1620
Christian Heimes790c8232008-01-07 21:14:23 +00001621 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001622 return 1;
1623
1624 rc = DosFindFirst(buf,
1625 &hdir,
1626 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1627 &ffbuf, sizeof(ffbuf),
1628 &srchcnt,
1629 FIL_STANDARD);
1630 if (rc != NO_ERROR)
1631 return 0;
1632 return strncmp(ffbuf.achName, name, namelen) == 0;
1633
Tim Peters50d8d372001-02-28 05:34:27 +00001634/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1635#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001636 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001637
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001638#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001639}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001640
Guido van Rossum0980bd91998-02-13 17:18:36 +00001641
Guido van Rossum197346f1997-10-31 18:38:52 +00001642#ifdef HAVE_STAT
1643/* Helper to look for __init__.py or __init__.py[co] in potential package */
1644static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001645find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001646{
Tim Peters0f9431f2001-07-05 03:47:53 +00001647 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001648 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001649 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001650 struct stat statbuf;
1651
Tim Peters0f9431f2001-07-05 03:47:53 +00001652/* For calling case_ok(buf, len, namelen, name):
1653 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1654 * ^ ^ ^ ^
1655 * |--------------------- buf ---------------------|
1656 * |------------------- len ------------------|
1657 * |------ name -------|
1658 * |----- namelen -----|
1659 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001660 if (save_len + 13 >= MAXPATHLEN)
1661 return 0;
1662 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001663 pname = buf + i;
1664 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001665 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001666 if (case_ok(buf,
1667 save_len + 9, /* len("/__init__") */
1668 8, /* len("__init__") */
1669 pname)) {
1670 buf[save_len] = '\0';
1671 return 1;
1672 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001673 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001674 i += strlen(pname);
1675 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001676 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001677 if (case_ok(buf,
1678 save_len + 9, /* len("/__init__") */
1679 8, /* len("__init__") */
1680 pname)) {
1681 buf[save_len] = '\0';
1682 return 1;
1683 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001684 }
1685 buf[save_len] = '\0';
1686 return 0;
1687}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001688
Guido van Rossum197346f1997-10-31 18:38:52 +00001689#endif /* HAVE_STAT */
1690
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001691
Tim Petersdbd9ba62000-07-09 03:09:57 +00001692static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001693
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001694/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001695 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001696
Guido van Rossum79f25d91997-04-29 20:08:16 +00001697static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001698load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001699{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001700 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001701 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001702 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001703
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001704 /* First check that there's an open file (if we need one) */
1705 switch (type) {
1706 case PY_SOURCE:
1707 case PY_COMPILED:
1708 if (fp == NULL) {
1709 PyErr_Format(PyExc_ValueError,
1710 "file object required for import (type code %d)",
1711 type);
1712 return NULL;
1713 }
1714 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001715
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001716 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001717
1718 case PY_SOURCE:
1719 m = load_source_module(name, buf, fp);
1720 break;
1721
1722 case PY_COMPILED:
1723 m = load_compiled_module(name, buf, fp);
1724 break;
1725
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001726#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001727 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001728 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001729 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001730#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001731
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001732 case PKG_DIRECTORY:
1733 m = load_package(name, buf);
1734 break;
1735
1736 case C_BUILTIN:
1737 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001738 if (buf != NULL && buf[0] != '\0')
1739 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001740 if (type == C_BUILTIN)
1741 err = init_builtin(name);
1742 else
1743 err = PyImport_ImportFrozenModule(name);
1744 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001745 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001746 if (err == 0) {
1747 PyErr_Format(PyExc_ImportError,
1748 "Purported %s module %.200s not found",
1749 type == C_BUILTIN ?
1750 "builtin" : "frozen",
1751 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001752 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001753 }
1754 modules = PyImport_GetModuleDict();
1755 m = PyDict_GetItemString(modules, name);
1756 if (m == NULL) {
1757 PyErr_Format(
1758 PyExc_ImportError,
1759 "%s module %.200s not properly initialized",
1760 type == C_BUILTIN ?
1761 "builtin" : "frozen",
1762 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001763 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001764 }
1765 Py_INCREF(m);
1766 break;
1767
Just van Rossum52e14d62002-12-30 22:08:05 +00001768 case IMP_HOOK: {
1769 if (loader == NULL) {
1770 PyErr_SetString(PyExc_ImportError,
1771 "import hook without loader");
1772 return NULL;
1773 }
1774 m = PyObject_CallMethod(loader, "load_module", "s", name);
1775 break;
1776 }
1777
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001779 PyErr_Format(PyExc_ImportError,
1780 "Don't know how to import %.200s (type code %d)",
1781 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001782 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001783
1784 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001785
1786 return m;
1787}
1788
1789
1790/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001791 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001792 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001793
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001794static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001795init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001796{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001797 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001798
Greg Ward201baee2001-10-04 14:52:06 +00001799 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001800 return 1;
1801
Guido van Rossum771c6c81997-10-31 18:37:24 +00001802 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001803 if (strcmp(name, p->name) == 0) {
1804 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001805 PyErr_Format(PyExc_ImportError,
1806 "Cannot re-init internal module %.200s",
1807 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001808 return -1;
1809 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001810 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001811 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001812 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001813 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001814 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001815 if (_PyImport_FixupExtension(name, name) == NULL)
1816 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001817 return 1;
1818 }
1819 }
1820 return 0;
1821}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001822
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001823
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001824/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001825
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001826static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001827find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001828{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001829 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001830
Guido van Rossum79f25d91997-04-29 20:08:16 +00001831 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001832 if (p->name == NULL)
1833 return NULL;
1834 if (strcmp(p->name, name) == 0)
1835 break;
1836 }
1837 return p;
1838}
1839
Guido van Rossum79f25d91997-04-29 20:08:16 +00001840static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001841get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001842{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001843 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001844 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001845
1846 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001847 PyErr_Format(PyExc_ImportError,
1848 "No such frozen object named %.200s",
1849 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001850 return NULL;
1851 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001852 if (p->code == NULL) {
1853 PyErr_Format(PyExc_ImportError,
1854 "Excluded frozen object named %.200s",
1855 name);
1856 return NULL;
1857 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001858 size = p->size;
1859 if (size < 0)
1860 size = -size;
1861 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001862}
1863
1864/* Initialize a frozen module.
1865 Return 1 for succes, 0 if the module is not found, and -1 with
1866 an exception set if the initialization failed.
1867 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001868
1869int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001870PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001871{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001872 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001873 PyObject *co;
1874 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001875 int ispackage;
1876 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001877
1878 if (p == NULL)
1879 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001880 if (p->code == NULL) {
1881 PyErr_Format(PyExc_ImportError,
1882 "Excluded frozen object named %.200s",
1883 name);
1884 return -1;
1885 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001886 size = p->size;
1887 ispackage = (size < 0);
1888 if (ispackage)
1889 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001890 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001891 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001892 name, ispackage ? " package" : "");
1893 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001894 if (co == NULL)
1895 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001896 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001897 PyErr_Format(PyExc_TypeError,
1898 "frozen object %.200s is not a code object",
1899 name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001900 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001901 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001902 if (ispackage) {
1903 /* Set __path__ to the package name */
1904 PyObject *d, *s;
1905 int err;
1906 m = PyImport_AddModule(name);
1907 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001908 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001909 d = PyModule_GetDict(m);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001910 s = PyUnicode_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001911 if (s == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001912 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001913 err = PyDict_SetItemString(d, "__path__", s);
1914 Py_DECREF(s);
1915 if (err != 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001916 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001917 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001918 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001919 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001920 goto err_return;
1921 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001922 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001923 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001924err_return:
1925 Py_DECREF(co);
1926 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001927}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001928
1929
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001930/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001931 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001932
Guido van Rossum79f25d91997-04-29 20:08:16 +00001933PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001934PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001935{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001936 PyObject *pname;
1937 PyObject *result;
1938
Martin v. Löwis5b222132007-06-10 09:51:05 +00001939 pname = PyUnicode_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001940 if (pname == NULL)
1941 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001942 result = PyImport_Import(pname);
1943 Py_DECREF(pname);
1944 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001945}
1946
Christian Heimes072c0f12008-01-03 23:01:04 +00001947/* Import a module without blocking
1948 *
1949 * At first it tries to fetch the module from sys.modules. If the module was
1950 * never loaded before it loads it with PyImport_ImportModule() unless another
1951 * thread holds the import lock. In the latter case the function raises an
1952 * ImportError instead of blocking.
1953 *
1954 * Returns the module object with incremented ref count.
1955 */
1956PyObject *
1957PyImport_ImportModuleNoBlock(const char *name)
1958{
1959 PyObject *result;
1960 PyObject *modules;
1961 long me;
1962
1963 /* Try to get the module from sys.modules[name] */
1964 modules = PyImport_GetModuleDict();
1965 if (modules == NULL)
1966 return NULL;
1967
1968 result = PyDict_GetItemString(modules, name);
1969 if (result != NULL) {
1970 Py_INCREF(result);
1971 return result;
1972 }
1973 else {
1974 PyErr_Clear();
1975 }
1976
1977 /* check the import lock
1978 * me might be -1 but I ignore the error here, the lock function
1979 * takes care of the problem */
1980 me = PyThread_get_thread_ident();
1981 if (import_lock_thread == -1 || import_lock_thread == me) {
1982 /* no thread or me is holding the lock */
1983 return PyImport_ImportModule(name);
1984 }
1985 else {
1986 PyErr_Format(PyExc_ImportError,
1987 "Failed to import %.200s because the import lock"
1988 "is held by another thread.",
1989 name);
1990 return NULL;
1991 }
1992}
1993
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001994/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001995static PyObject *get_parent(PyObject *globals, char *buf,
1996 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001997static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001998 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001999static int mark_miss(char *name);
2000static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002001 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002002static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002003
2004/* The Magnum Opus of dotted-name import :-) */
2005
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002006static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002007import_module_level(char *name, PyObject *globals, PyObject *locals,
2008 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002009{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002010 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002011 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002012 PyObject *parent, *head, *next, *tail;
2013
Christian Heimes454f37b2008-01-10 00:10:02 +00002014 if (strchr(name, '/') != NULL
2015#ifdef MS_WINDOWS
2016 || strchr(name, '\\') != NULL
2017#endif
2018 ) {
2019 PyErr_SetString(PyExc_ImportError,
2020 "Import by filename is not supported.");
2021 return NULL;
2022 }
2023
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002024 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002025 if (parent == NULL)
2026 return NULL;
2027
2028 head = load_next(parent, Py_None, &name, buf, &buflen);
2029 if (head == NULL)
2030 return NULL;
2031
2032 tail = head;
2033 Py_INCREF(tail);
2034 while (name) {
2035 next = load_next(tail, tail, &name, buf, &buflen);
2036 Py_DECREF(tail);
2037 if (next == NULL) {
2038 Py_DECREF(head);
2039 return NULL;
2040 }
2041 tail = next;
2042 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002043 if (tail == Py_None) {
2044 /* If tail is Py_None, both get_parent and load_next found
2045 an empty module name: someone called __import__("") or
2046 doctored faulty bytecode */
2047 Py_DECREF(tail);
2048 Py_DECREF(head);
2049 PyErr_SetString(PyExc_ValueError,
2050 "Empty module name");
2051 return NULL;
2052 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002053
2054 if (fromlist != NULL) {
2055 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2056 fromlist = NULL;
2057 }
2058
2059 if (fromlist == NULL) {
2060 Py_DECREF(tail);
2061 return head;
2062 }
2063
2064 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002065 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002066 Py_DECREF(tail);
2067 return NULL;
2068 }
2069
2070 return tail;
2071}
2072
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002073PyObject *
2074PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2075 PyObject *fromlist, int level)
2076{
2077 PyObject *result;
2078 lock_import();
2079 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002080 if (unlock_import() < 0) {
2081 Py_XDECREF(result);
2082 PyErr_SetString(PyExc_RuntimeError,
2083 "not holding the import lock");
2084 return NULL;
2085 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002086 return result;
2087}
2088
Fred Drake87590902004-05-28 20:21:36 +00002089/* Return the package that an import is being performed in. If globals comes
2090 from the module foo.bar.bat (not itself a package), this returns the
2091 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002092 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002093
2094 The *name* of the returned package is returned in buf, with the length of
2095 the name in *p_buflen.
2096
2097 If globals doesn't come from a package or a module in a package, or a
2098 corresponding entry is not found in sys.modules, Py_None is returned.
2099*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002100static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002101get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002102{
2103 static PyObject *namestr = NULL;
2104 static PyObject *pathstr = NULL;
Nick Coghlande10c852007-12-04 12:22:52 +00002105 static PyObject *pkgstr = NULL;
2106 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002107
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002108 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002109 return Py_None;
2110
2111 if (namestr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002112 namestr = PyUnicode_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002113 if (namestr == NULL)
2114 return NULL;
2115 }
2116 if (pathstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002117 pathstr = PyUnicode_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002118 if (pathstr == NULL)
2119 return NULL;
2120 }
Nick Coghlande10c852007-12-04 12:22:52 +00002121 if (pkgstr == NULL) {
2122 pkgstr = PyUnicode_InternFromString("__package__");
2123 if (pkgstr == NULL)
2124 return NULL;
2125 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002126
2127 *buf = '\0';
2128 *p_buflen = 0;
Nick Coghlande10c852007-12-04 12:22:52 +00002129 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002130
Nick Coghlande10c852007-12-04 12:22:52 +00002131 if ((pkgname != NULL) && (pkgname != Py_None)) {
2132 /* __package__ is set, so use it */
2133 Py_ssize_t len;
2134 if (!PyUnicode_Check(pkgname)) {
2135 PyErr_SetString(PyExc_ValueError,
2136 "__package__ set to non-string");
2137 return NULL;
2138 }
2139 len = PyUnicode_GET_SIZE(pkgname);
2140 if (len == 0) {
2141 if (level > 0) {
2142 PyErr_SetString(PyExc_ValueError,
2143 "Attempted relative import in non-package");
2144 return NULL;
2145 }
2146 return Py_None;
2147 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002148 if (len > MAXPATHLEN) {
2149 PyErr_SetString(PyExc_ValueError,
Nick Coghlande10c852007-12-04 12:22:52 +00002150 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002151 return NULL;
2152 }
Nick Coghlande10c852007-12-04 12:22:52 +00002153 strcpy(buf, PyUnicode_AsString(pkgname));
2154 } else {
2155 /* __package__ not set, so figure it out and set it */
2156 modname = PyDict_GetItem(globals, namestr);
2157 if (modname == NULL || !PyUnicode_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002158 return Py_None;
Nick Coghlande10c852007-12-04 12:22:52 +00002159
2160 modpath = PyDict_GetItem(globals, pathstr);
2161 if (modpath != NULL) {
2162 /* __path__ is set, so modname is already the package name */
2163 Py_ssize_t len = PyUnicode_GET_SIZE(modname);
2164 int error;
2165 if (len > MAXPATHLEN) {
2166 PyErr_SetString(PyExc_ValueError,
2167 "Module name too long");
2168 return NULL;
2169 }
2170 strcpy(buf, PyUnicode_AsString(modname));
2171 error = PyDict_SetItem(globals, pkgstr, modname);
2172 if (error) {
2173 PyErr_SetString(PyExc_ValueError,
2174 "Could not set __package__");
2175 return NULL;
2176 }
2177 } else {
2178 /* Normal module, so work out the package name if any */
2179 char *start = PyUnicode_AsString(modname);
2180 char *lastdot = strrchr(start, '.');
2181 size_t len;
2182 int error;
2183 if (lastdot == NULL && level > 0) {
2184 PyErr_SetString(PyExc_ValueError,
2185 "Attempted relative import in non-package");
2186 return NULL;
2187 }
2188 if (lastdot == NULL) {
2189 error = PyDict_SetItem(globals, pkgstr, Py_None);
2190 if (error) {
2191 PyErr_SetString(PyExc_ValueError,
2192 "Could not set __package__");
2193 return NULL;
2194 }
2195 return Py_None;
2196 }
2197 len = lastdot - start;
2198 if (len >= MAXPATHLEN) {
2199 PyErr_SetString(PyExc_ValueError,
2200 "Module name too long");
2201 return NULL;
2202 }
2203 strncpy(buf, start, len);
2204 buf[len] = '\0';
2205 pkgname = PyUnicode_FromString(buf);
2206 if (pkgname == NULL) {
2207 return NULL;
2208 }
2209 error = PyDict_SetItem(globals, pkgstr, pkgname);
2210 Py_DECREF(pkgname);
2211 if (error) {
2212 PyErr_SetString(PyExc_ValueError,
2213 "Could not set __package__");
2214 return NULL;
2215 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002216 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002217 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002218 while (--level > 0) {
2219 char *dot = strrchr(buf, '.');
2220 if (dot == NULL) {
2221 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002222 "Attempted relative import beyond "
2223 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002224 return NULL;
2225 }
2226 *dot = '\0';
2227 }
2228 *p_buflen = strlen(buf);
2229
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002230 modules = PyImport_GetModuleDict();
2231 parent = PyDict_GetItemString(modules, buf);
2232 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002233 PyErr_Format(PyExc_SystemError,
2234 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002235 return parent;
2236 /* We expect, but can't guarantee, if parent != None, that:
2237 - parent.__name__ == buf
2238 - parent.__dict__ is globals
2239 If this is violated... Who cares? */
2240}
2241
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002242/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002244load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002245 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002246{
2247 char *name = *p_name;
2248 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002249 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002250 char *p;
2251 PyObject *result;
2252
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002253 if (strlen(name) == 0) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002254 /* completely empty module name should only happen in
2255 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002256 Py_INCREF(mod);
2257 *p_name = NULL;
2258 return mod;
2259 }
2260
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002261 if (dot == NULL) {
2262 *p_name = NULL;
2263 len = strlen(name);
2264 }
2265 else {
2266 *p_name = dot+1;
2267 len = dot-name;
2268 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002269 if (len == 0) {
2270 PyErr_SetString(PyExc_ValueError,
2271 "Empty module name");
2272 return NULL;
2273 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002274
2275 p = buf + *p_buflen;
2276 if (p != buf)
2277 *p++ = '.';
2278 if (p+len-buf >= MAXPATHLEN) {
2279 PyErr_SetString(PyExc_ValueError,
2280 "Module name too long");
2281 return NULL;
2282 }
2283 strncpy(p, name, len);
2284 p[len] = '\0';
2285 *p_buflen = p+len-buf;
2286
2287 result = import_submodule(mod, p, buf);
2288 if (result == Py_None && altmod != mod) {
2289 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002290 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002291 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002292 if (result != NULL && result != Py_None) {
2293 if (mark_miss(buf) != 0) {
2294 Py_DECREF(result);
2295 return NULL;
2296 }
2297 strncpy(buf, name, len);
2298 buf[len] = '\0';
2299 *p_buflen = len;
2300 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002301 }
2302 if (result == NULL)
2303 return NULL;
2304
2305 if (result == Py_None) {
2306 Py_DECREF(result);
2307 PyErr_Format(PyExc_ImportError,
2308 "No module named %.200s", name);
2309 return NULL;
2310 }
2311
2312 return result;
2313}
2314
2315static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002316mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002317{
2318 PyObject *modules = PyImport_GetModuleDict();
2319 return PyDict_SetItemString(modules, name, Py_None);
2320}
2321
2322static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002323ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002324 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002325{
2326 int i;
2327
2328 if (!PyObject_HasAttrString(mod, "__path__"))
2329 return 1;
2330
2331 for (i = 0; ; i++) {
2332 PyObject *item = PySequence_GetItem(fromlist, i);
2333 int hasit;
2334 if (item == NULL) {
2335 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2336 PyErr_Clear();
2337 return 1;
2338 }
2339 return 0;
2340 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002341 if (!PyUnicode_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002342 PyErr_SetString(PyExc_TypeError,
Neal Norwitz80e7f272007-08-26 06:45:23 +00002343 "Item in ``from list'' not a string");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002344 Py_DECREF(item);
2345 return 0;
2346 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002347 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002348 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002349 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002350 /* See if the package defines __all__ */
2351 if (recursive)
2352 continue; /* Avoid endless recursion */
2353 all = PyObject_GetAttrString(mod, "__all__");
2354 if (all == NULL)
2355 PyErr_Clear();
2356 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002357 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002358 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002359 if (!ret)
2360 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002361 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002362 continue;
2363 }
2364 hasit = PyObject_HasAttr(mod, item);
2365 if (!hasit) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002366 PyObject *item8;
2367 char *subname;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002368 PyObject *submod;
2369 char *p;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002370 if (!Py_FileSystemDefaultEncoding) {
2371 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2372 PyUnicode_GetSize(item),
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002373 NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002374 } else {
Guido van Rossum98297ee2007-11-06 21:34:58 +00002375 item8 = PyUnicode_AsEncodedString(item,
2376 Py_FileSystemDefaultEncoding, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002377 }
2378 if (!item8) {
2379 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2380 return 0;
2381 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002382 subname = PyString_AS_STRING(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002383 if (buflen + strlen(subname) >= MAXPATHLEN) {
2384 PyErr_SetString(PyExc_ValueError,
2385 "Module name too long");
2386 Py_DECREF(item);
2387 return 0;
2388 }
2389 p = buf + buflen;
2390 *p++ = '.';
2391 strcpy(p, subname);
2392 submod = import_submodule(mod, subname, buf);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002393 Py_DECREF(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002394 Py_XDECREF(submod);
2395 if (submod == NULL) {
2396 Py_DECREF(item);
2397 return 0;
2398 }
2399 }
2400 Py_DECREF(item);
2401 }
2402
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002403 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002404}
2405
Neil Schemenauer00b09662003-06-16 21:03:07 +00002406static int
2407add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2408 PyObject *modules)
2409{
2410 if (mod == Py_None)
2411 return 1;
2412 /* Irrespective of the success of this load, make a
2413 reference to it in the parent package module. A copy gets
2414 saved in the modules dictionary under the full name, so get a
2415 reference from there, if need be. (The exception is when the
2416 load failed with a SyntaxError -- then there's no trace in
2417 sys.modules. In that case, of course, do nothing extra.) */
2418 if (submod == NULL) {
2419 submod = PyDict_GetItemString(modules, fullname);
2420 if (submod == NULL)
2421 return 1;
2422 }
2423 if (PyModule_Check(mod)) {
2424 /* We can't use setattr here since it can give a
2425 * spurious warning if the submodule name shadows a
2426 * builtin name */
2427 PyObject *dict = PyModule_GetDict(mod);
2428 if (!dict)
2429 return 0;
2430 if (PyDict_SetItemString(dict, subname, submod) < 0)
2431 return 0;
2432 }
2433 else {
2434 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2435 return 0;
2436 }
2437 return 1;
2438}
2439
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002440static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002441import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002442{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002443 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002444 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002445
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002446 /* Require:
2447 if mod == None: subname == fullname
2448 else: mod.__name__ + "." + subname == fullname
2449 */
2450
Tim Peters50d8d372001-02-28 05:34:27 +00002451 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002452 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002453 }
2454 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002455 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002456 char buf[MAXPATHLEN+1];
2457 struct filedescr *fdp;
2458 FILE *fp = NULL;
2459
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002460 if (mod == Py_None)
2461 path = NULL;
2462 else {
2463 path = PyObject_GetAttrString(mod, "__path__");
2464 if (path == NULL) {
2465 PyErr_Clear();
2466 Py_INCREF(Py_None);
2467 return Py_None;
2468 }
2469 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002470
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002471 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002472 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2473 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002474 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002475 if (fdp == NULL) {
2476 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2477 return NULL;
2478 PyErr_Clear();
2479 Py_INCREF(Py_None);
2480 return Py_None;
2481 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002482 m = load_module(fullname, fp, buf, fdp->type, loader);
2483 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002484 if (fp)
2485 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002486 if (!add_submodule(mod, m, fullname, subname, modules)) {
2487 Py_XDECREF(m);
2488 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002489 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002490 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002491
2492 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002493}
2494
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002495
2496/* Re-import a module of any kind and return its module object, WITH
2497 INCREMENTED REFERENCE COUNT */
2498
Guido van Rossum79f25d91997-04-29 20:08:16 +00002499PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002500PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002501{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002502 PyInterpreterState *interp = PyThreadState_Get()->interp;
2503 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002504 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumd8faa362007-04-27 19:54:29 +00002505 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002506 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002507 char buf[MAXPATHLEN+1];
2508 struct filedescr *fdp;
2509 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002510 PyObject *newm;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002511
2512 if (modules_reloading == NULL) {
2513 Py_FatalError("PyImport_ReloadModule: "
Guido van Rossume7ba4952007-06-06 23:52:48 +00002514 "no modules_reloading dictionary!");
Guido van Rossumd8faa362007-04-27 19:54:29 +00002515 return NULL;
2516 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002517
Guido van Rossum79f25d91997-04-29 20:08:16 +00002518 if (m == NULL || !PyModule_Check(m)) {
2519 PyErr_SetString(PyExc_TypeError,
2520 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002521 return NULL;
2522 }
Neal Norwitz5616c6d2007-08-26 05:32:41 +00002523 name = (char*)PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002524 if (name == NULL)
2525 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002526 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002527 PyErr_Format(PyExc_ImportError,
2528 "reload(): module %.200s not in sys.modules",
2529 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002530 return NULL;
2531 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002532 existing_m = PyDict_GetItemString(modules_reloading, name);
2533 if (existing_m != NULL) {
2534 /* Due to a recursive reload, this module is already
2535 being reloaded. */
2536 Py_INCREF(existing_m);
2537 return existing_m;
2538 }
2539 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2540 return NULL;
2541
Guido van Rossum222ef561997-09-06 19:41:09 +00002542 subname = strrchr(name, '.');
2543 if (subname == NULL)
2544 subname = name;
2545 else {
2546 PyObject *parentname, *parent;
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002547 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002548 if (parentname == NULL) {
2549 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002550 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002551 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002552 parent = PyDict_GetItem(modules, parentname);
2553 if (parent == NULL) {
2554 PyErr_Format(PyExc_ImportError,
2555 "reload(): parent %.200s not in sys.modules",
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002556 PyUnicode_AsString(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002557 Py_DECREF(parentname);
Guido van Rossume7ba4952007-06-06 23:52:48 +00002558 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002559 return NULL;
2560 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002561 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002562 subname++;
2563 path = PyObject_GetAttrString(parent, "__path__");
2564 if (path == NULL)
2565 PyErr_Clear();
2566 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002567 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002568 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002569 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002570
2571 if (fdp == NULL) {
2572 Py_XDECREF(loader);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002573 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002574 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002575 }
2576
2577 newm = load_module(name, fp, buf, fdp->type, loader);
2578 Py_XDECREF(loader);
2579
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002580 if (fp)
2581 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002582 if (newm == NULL) {
2583 /* load_module probably removed name from modules because of
2584 * the error. Put back the original module object. We're
2585 * going to return NULL in this case regardless of whether
2586 * replacing name succeeds, so the return value is ignored.
2587 */
2588 PyDict_SetItemString(modules, name, m);
2589 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002590 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002591 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002592}
2593
2594
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002595/* Higher-level import emulator which emulates the "import" statement
2596 more accurately -- it invokes the __import__() function from the
2597 builtins of the current globals. This means that the import is
2598 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002599 environment, e.g. by "rexec".
2600 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002601 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002602 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002603
2604PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002605PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002606{
2607 static PyObject *silly_list = NULL;
2608 static PyObject *builtins_str = NULL;
2609 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002610 PyObject *globals = NULL;
2611 PyObject *import = NULL;
2612 PyObject *builtins = NULL;
2613 PyObject *r = NULL;
2614
2615 /* Initialize constant string objects */
2616 if (silly_list == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002617 import_str = PyUnicode_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002618 if (import_str == NULL)
2619 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002620 builtins_str = PyUnicode_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002621 if (builtins_str == NULL)
2622 return NULL;
2623 silly_list = Py_BuildValue("[s]", "__doc__");
2624 if (silly_list == NULL)
2625 return NULL;
2626 }
2627
2628 /* Get the builtins from current globals */
2629 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002630 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002631 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002632 builtins = PyObject_GetItem(globals, builtins_str);
2633 if (builtins == NULL)
2634 goto err;
2635 }
2636 else {
2637 /* No globals -- use standard builtins, and fake globals */
2638 PyErr_Clear();
2639
Georg Brandl1a3284e2007-12-02 09:40:06 +00002640 builtins = PyImport_ImportModuleLevel("builtins",
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002641 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002642 if (builtins == NULL)
2643 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002644 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2645 if (globals == NULL)
2646 goto err;
2647 }
2648
2649 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002651 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652 if (import == NULL)
2653 PyErr_SetObject(PyExc_KeyError, import_str);
2654 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002655 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002656 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002657 if (import == NULL)
2658 goto err;
2659
Christian Heimes072c0f12008-01-03 23:01:04 +00002660 /* Call the __import__ function with the proper argument list
2661 * Always use absolute import here. */
2662 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2663 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002664
2665 err:
2666 Py_XDECREF(globals);
2667 Py_XDECREF(builtins);
2668 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002669
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002670 return r;
2671}
2672
2673
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002674/* Module 'imp' provides Python access to the primitives used for
2675 importing modules.
2676*/
2677
Guido van Rossum79f25d91997-04-29 20:08:16 +00002678static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002679imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002680{
2681 char buf[4];
2682
Guido van Rossum96774c12000-05-01 20:19:08 +00002683 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2684 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2685 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2686 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002687
Guido van Rossumad8d3002007-08-03 18:40:49 +00002688 return PyBytes_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002689}
2690
Guido van Rossum79f25d91997-04-29 20:08:16 +00002691static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002692imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002693{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002694 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002695 struct filedescr *fdp;
2696
Guido van Rossum79f25d91997-04-29 20:08:16 +00002697 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002698 if (list == NULL)
2699 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002700 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2701 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002702 fdp->suffix, fdp->mode, fdp->type);
2703 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002704 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002705 return NULL;
2706 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002707 if (PyList_Append(list, item) < 0) {
2708 Py_DECREF(list);
2709 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002710 return NULL;
2711 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002712 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002713 }
2714 return list;
2715}
2716
Guido van Rossum79f25d91997-04-29 20:08:16 +00002717static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002718call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002719{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002720 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002721 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002722 struct filedescr *fdp;
2723 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002724 FILE *fp = NULL;
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002725 int fd = -1;
Brett Cannon3bb42d92007-10-20 03:43:15 +00002726 char *found_encoding = NULL;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002727 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002728
2729 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002730 if (path == Py_None)
2731 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002732 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002733 if (fdp == NULL)
2734 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002735 if (fp != NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002736 fd = fileno(fp);
2737 if (fd != -1)
2738 fd = dup(fd);
2739 fclose(fp);
2740 fp = NULL;
2741 }
2742 if (fd != -1) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002743 if (strchr(fdp->mode, 'b') == NULL) {
Brett Cannon3bb42d92007-10-20 03:43:15 +00002744 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
2745 memory. */
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002746 found_encoding = PyTokenizer_FindEncoding(fd);
2747 lseek(fd, 0, 0); /* Reset position */
Brett Cannon3bb42d92007-10-20 03:43:15 +00002748 encoding = (found_encoding != NULL) ? found_encoding :
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002749 (char*)PyUnicode_GetDefaultEncoding();
2750 }
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002751 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00002752 (char*)encoding, NULL, NULL, 1);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002753 if (fob == NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002754 close(fd);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002755 PyMem_FREE(found_encoding);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002756 return NULL;
2757 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002758 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002759 else {
2760 fob = Py_None;
2761 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002762 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002763 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002764 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002765 Py_DECREF(fob);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002766 PyMem_FREE(found_encoding);
2767
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002768 return ret;
2769}
2770
Guido van Rossum79f25d91997-04-29 20:08:16 +00002771static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002772imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002773{
2774 char *name;
2775 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002776 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002777 return NULL;
2778 return call_find_module(name, path);
2779}
2780
2781static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002782imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002783{
2784 char *name;
2785 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002786 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002787 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002788 return NULL;
2789 ret = init_builtin(name);
2790 if (ret < 0)
2791 return NULL;
2792 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002793 Py_INCREF(Py_None);
2794 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002795 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002796 m = PyImport_AddModule(name);
2797 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002798 return m;
2799}
2800
Guido van Rossum79f25d91997-04-29 20:08:16 +00002801static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002802imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002803{
2804 char *name;
2805 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002806 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002807 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002809 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002810 if (ret < 0)
2811 return NULL;
2812 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002813 Py_INCREF(Py_None);
2814 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002815 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002816 m = PyImport_AddModule(name);
2817 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002818 return m;
2819}
2820
Guido van Rossum79f25d91997-04-29 20:08:16 +00002821static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002822imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002823{
2824 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002825
Guido van Rossum43713e52000-02-29 13:59:29 +00002826 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002827 return NULL;
2828 return get_frozen_object(name);
2829}
2830
Guido van Rossum79f25d91997-04-29 20:08:16 +00002831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002832imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002833{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002834 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002835 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002836 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00002837 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002838}
2839
Guido van Rossum79f25d91997-04-29 20:08:16 +00002840static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002841imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002842{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002843 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002844 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002845 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002846 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002847 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002848 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002849}
2850
2851static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002852get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002853{
2854 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002855 if (mode[0] == 'U')
2856 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002857 if (fob == NULL) {
2858 fp = fopen(pathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002859 }
2860 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002861 int fd = PyObject_AsFileDescriptor(fob);
2862 if (fd == -1)
2863 return NULL;
2864 /* XXX This will leak a FILE struct. Fix this!!!!
2865 (But it doesn't leak a file descrioptor!) */
2866 fp = fdopen(fd, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002867 }
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002868 if (fp == NULL)
2869 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002870 return fp;
2871}
2872
Guido van Rossum79f25d91997-04-29 20:08:16 +00002873static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002874imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002875{
2876 char *name;
2877 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002878 PyObject *fob = NULL;
2879 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002880 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002881 if (!PyArg_ParseTuple(args, "ss|O:load_compiled",
2882 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002883 return NULL;
2884 fp = get_file(pathname, fob, "rb");
2885 if (fp == NULL)
2886 return NULL;
2887 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002888 if (fob == NULL)
2889 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002890 return m;
2891}
2892
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002893#ifdef HAVE_DYNAMIC_LOADING
2894
Guido van Rossum79f25d91997-04-29 20:08:16 +00002895static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002896imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002897{
2898 char *name;
2899 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002900 PyObject *fob = NULL;
2901 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002902 FILE *fp = NULL;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002903 if (!PyArg_ParseTuple(args, "ss|O:load_dynamic",
2904 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002905 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002906 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002907 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002908 if (fp == NULL)
2909 return NULL;
2910 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002911 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002912 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002913}
2914
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002915#endif /* HAVE_DYNAMIC_LOADING */
2916
Guido van Rossum79f25d91997-04-29 20:08:16 +00002917static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002918imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002919{
2920 char *name;
2921 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002922 PyObject *fob = NULL;
2923 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002924 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002925 if (!PyArg_ParseTuple(args, "ss|O:load_source",
2926 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002927 return NULL;
2928 fp = get_file(pathname, fob, "r");
2929 if (fp == NULL)
2930 return NULL;
2931 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002932 if (fob == NULL)
2933 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002934 return m;
2935}
2936
Guido van Rossum79f25d91997-04-29 20:08:16 +00002937static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002938imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002939{
2940 char *name;
2941 PyObject *fob;
2942 char *pathname;
2943 char *suffix; /* Unused */
2944 char *mode;
2945 int type;
2946 FILE *fp;
2947
Guido van Rossum43713e52000-02-29 13:59:29 +00002948 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002949 &name, &fob, &pathname,
2950 &suffix, &mode, &type))
2951 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002952 if (*mode) {
2953 /* Mode must start with 'r' or 'U' and must not contain '+'.
2954 Implicit in this test is the assumption that the mode
2955 may contain other modifiers like 'b' or 't'. */
2956
2957 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002958 PyErr_Format(PyExc_ValueError,
2959 "invalid file open mode %.200s", mode);
2960 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002961 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002962 }
2963 if (fob == Py_None)
2964 fp = NULL;
2965 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002966 fp = get_file(NULL, fob, mode);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002967 if (fp == NULL)
2968 return NULL;
2969 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002970 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002971}
2972
2973static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002974imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002975{
2976 char *name;
2977 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002978 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002979 return NULL;
2980 return load_package(name, pathname);
2981}
2982
2983static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002984imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002985{
2986 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002987 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002988 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002989 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002990}
2991
Christian Heimes13a7a212008-01-07 17:13:09 +00002992static PyObject *
2993imp_reload(PyObject *self, PyObject *v)
2994{
2995 return PyImport_ReloadModule(v);
2996}
2997
2998PyDoc_STRVAR(doc_reload,
2999"reload(module) -> module\n\
3000\n\
3001Reload the module. The module must have been successfully imported before.");
3002
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003003/* Doc strings */
3004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003005PyDoc_STRVAR(doc_imp,
3006"This module provides the components needed to build your own\n\
3007__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003009PyDoc_STRVAR(doc_find_module,
3010"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003011Search for a module. If path is omitted or None, search for a\n\
3012built-in, frozen or special module and continue search in sys.path.\n\
3013The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003014package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003015
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003016PyDoc_STRVAR(doc_load_module,
3017"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003018Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003019The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003021PyDoc_STRVAR(doc_get_magic,
3022"get_magic() -> string\n\
3023Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003025PyDoc_STRVAR(doc_get_suffixes,
3026"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003027Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003028that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003030PyDoc_STRVAR(doc_new_module,
3031"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003032Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003033The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003034
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003035PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003036"lock_held() -> boolean\n\
3037Return True if the import lock is currently held, else False.\n\
3038On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003039
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003040PyDoc_STRVAR(doc_acquire_lock,
3041"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003042Acquires the interpreter's import lock for the current thread.\n\
3043This lock should be used by import hooks to ensure thread-safety\n\
3044when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003045On platforms without threads, this function does nothing.");
3046
3047PyDoc_STRVAR(doc_release_lock,
3048"release_lock() -> None\n\
3049Release the interpreter's import lock.\n\
3050On platforms without threads, this function does nothing.");
3051
Guido van Rossum79f25d91997-04-29 20:08:16 +00003052static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003053 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3054 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3055 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3056 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3057 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3058 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3059 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3060 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Christian Heimes13a7a212008-01-07 17:13:09 +00003061 {"reload", imp_reload, METH_O, doc_reload},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003062 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003063 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3064 {"init_builtin", imp_init_builtin, METH_VARARGS},
3065 {"init_frozen", imp_init_frozen, METH_VARARGS},
3066 {"is_builtin", imp_is_builtin, METH_VARARGS},
3067 {"is_frozen", imp_is_frozen, METH_VARARGS},
3068 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003069#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003070 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003071#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003072 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003073 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003074 {NULL, NULL} /* sentinel */
3075};
3076
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003077static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003078setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003079{
3080 PyObject *v;
3081 int err;
3082
Christian Heimes217cfd12007-12-02 14:31:20 +00003083 v = PyLong_FromLong((long)value);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003084 err = PyDict_SetItemString(d, name, v);
3085 Py_XDECREF(v);
3086 return err;
3087}
3088
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003089typedef struct {
3090 PyObject_HEAD
3091} NullImporter;
3092
3093static int
3094NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3095{
3096 char *path;
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003097 Py_ssize_t pathlen;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003098
3099 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3100 return -1;
3101
3102 if (!PyArg_ParseTuple(args, "s:NullImporter",
3103 &path))
3104 return -1;
3105
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003106 pathlen = strlen(path);
3107 if (pathlen == 0) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003108 PyErr_SetString(PyExc_ImportError, "empty pathname");
3109 return -1;
3110 } else {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003111 struct stat statbuf;
3112 int rv;
3113
3114 rv = stat(path, &statbuf);
Guido van Rossumc1bdbc32007-11-07 17:46:34 +00003115#ifdef MS_WINDOWS
3116 /* MS Windows stat() chokes on paths like C:\path\. Try to
3117 * recover *one* time by stripping off a trailing slash or
3118 * backslash. http://bugs.python.org/issue1293
3119 */
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003120 if (rv != 0 && pathlen <= MAXPATHLEN &&
3121 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3122 char mangled[MAXPATHLEN+1];
3123
3124 strcpy(mangled, path);
3125 mangled[pathlen-1] = '\0';
3126 rv = stat(mangled, &statbuf);
3127 }
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003128#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003129 if (rv == 0) {
3130 /* it exists */
3131 if (S_ISDIR(statbuf.st_mode)) {
3132 /* it's a directory */
3133 PyErr_SetString(PyExc_ImportError,
3134 "existing directory");
3135 return -1;
3136 }
3137 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003138 }
3139 return 0;
3140}
3141
3142static PyObject *
3143NullImporter_find_module(NullImporter *self, PyObject *args)
3144{
3145 Py_RETURN_NONE;
3146}
3147
3148static PyMethodDef NullImporter_methods[] = {
3149 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3150 "Always return None"
3151 },
3152 {NULL} /* Sentinel */
3153};
3154
3155
Christian Heimes9cd17752007-11-18 19:35:23 +00003156PyTypeObject PyNullImporter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003157 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003158 "imp.NullImporter", /*tp_name*/
3159 sizeof(NullImporter), /*tp_basicsize*/
3160 0, /*tp_itemsize*/
3161 0, /*tp_dealloc*/
3162 0, /*tp_print*/
3163 0, /*tp_getattr*/
3164 0, /*tp_setattr*/
3165 0, /*tp_compare*/
3166 0, /*tp_repr*/
3167 0, /*tp_as_number*/
3168 0, /*tp_as_sequence*/
3169 0, /*tp_as_mapping*/
3170 0, /*tp_hash */
3171 0, /*tp_call*/
3172 0, /*tp_str*/
3173 0, /*tp_getattro*/
3174 0, /*tp_setattro*/
3175 0, /*tp_as_buffer*/
3176 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3177 "Null importer object", /* tp_doc */
3178 0, /* tp_traverse */
3179 0, /* tp_clear */
3180 0, /* tp_richcompare */
3181 0, /* tp_weaklistoffset */
3182 0, /* tp_iter */
3183 0, /* tp_iternext */
3184 NullImporter_methods, /* tp_methods */
3185 0, /* tp_members */
3186 0, /* tp_getset */
3187 0, /* tp_base */
3188 0, /* tp_dict */
3189 0, /* tp_descr_get */
3190 0, /* tp_descr_set */
3191 0, /* tp_dictoffset */
3192 (initproc)NullImporter_init, /* tp_init */
3193 0, /* tp_alloc */
3194 PyType_GenericNew /* tp_new */
3195};
3196
3197
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003198PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003199initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003200{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003201 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003202
Christian Heimes9cd17752007-11-18 19:35:23 +00003203 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003204 goto failure;
3205
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003206 m = Py_InitModule4("imp", imp_methods, doc_imp,
3207 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003208 if (m == NULL)
3209 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003210 d = PyModule_GetDict(m);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003211 if (d == NULL)
3212 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003213
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003214 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3215 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3216 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3217 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3218 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3219 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3220 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3221 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003222 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003223 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003224
Christian Heimes9cd17752007-11-18 19:35:23 +00003225 Py_INCREF(&PyNullImporter_Type);
3226 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003227 failure:
3228 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003229}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003230
3231
Guido van Rossumb18618d2000-05-03 23:44:39 +00003232/* API for embedding applications that want to add their own entries
3233 to the table of built-in modules. This should normally be called
3234 *before* Py_Initialize(). When the table resize fails, -1 is
3235 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003236
3237 After a similar function by Just van Rossum. */
3238
3239int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003240PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003241{
3242 static struct _inittab *our_copy = NULL;
3243 struct _inittab *p;
3244 int i, n;
3245
3246 /* Count the number of entries in both tables */
3247 for (n = 0; newtab[n].name != NULL; n++)
3248 ;
3249 if (n == 0)
3250 return 0; /* Nothing to do */
3251 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3252 ;
3253
3254 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003255 p = our_copy;
3256 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003257 if (p == NULL)
3258 return -1;
3259
3260 /* Copy the tables into the new memory */
3261 if (our_copy != PyImport_Inittab)
3262 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3263 PyImport_Inittab = our_copy = p;
3264 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3265
3266 return 0;
3267}
3268
3269/* Shorthand to add a single entry given a name and a function */
3270
3271int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003272PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003273{
3274 struct _inittab newtab[2];
3275
3276 memset(newtab, '\0', sizeof newtab);
3277
3278 newtab[0].name = name;
3279 newtab[0].initfunc = initfunc;
3280
3281 return PyImport_ExtendInittab(newtab);
3282}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003283
3284#ifdef __cplusplus
3285}
3286#endif