blob: 7dab46ea8edb46deb6b88ee67df915fae6d1d2f8 [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)
Guido van Rossum45aecf42006-03-15 04:58:47 +000075 Python 3000: 3000
Brett Cannone2e23ef2006-08-25 05:05:30 +000076 3010 (removed UNARY_CONVERT)
Guido van Rossum86e58e22006-08-28 15:27:34 +000077 3020 (added BUILD_SET)
Guido van Rossum4f72a782006-10-27 23:31:49 +000078 3030 (added keyword-only parameters)
Guido van Rossum3203bdc2006-12-28 21:03:31 +000079 3040 (added signature annotations)
Guido van Rossum452bf512007-02-09 05:32:43 +000080 3050 (print becomes a function)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000081 3060 (PEP 3115 metaclass syntax)
Guido van Rossum00bc0e02007-10-15 02:52:41 +000082 3070 (PEP 3109 raise changes)
83 3080 (PEP 3137 make __file__ and __name__ unicode)
Guido van Rossum98297ee2007-11-06 21:34:58 +000084 3090 (kill str8 interning)
Christian Heimes99170a52007-12-19 02:07:34 +000085 3100 (merge from 2.6a0, see 62151)
Christian Heimes3b06e532008-01-07 20:12:44 +000086 3102 (__file__ points to source file)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000087.
Tim Peters36515e22001-11-18 04:06:29 +000088*/
Christian Heimes3b06e532008-01-07 20:12:44 +000089#define MAGIC (3102 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000090
Guido van Rossum96774c12000-05-01 20:19:08 +000091/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000092 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000093 compiler works which are enabled by command line switches. */
94static long pyc_magic = MAGIC;
95
Guido van Rossum25ce5661997-08-02 03:10:38 +000096/* See _PyImport_FixupExtension() below */
97static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000098
Guido van Rossum771c6c81997-10-31 18:37:24 +000099/* This table is defined in config.c: */
100extern struct _inittab _PyImport_Inittab[];
101
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000102/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000103extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000104
Guido van Rossum771c6c81997-10-31 18:37:24 +0000105struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000106
Guido van Rossumed1170e1999-12-20 21:23:41 +0000107/* these tables define the module suffixes that Python recognizes */
108struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000109
Guido van Rossumed1170e1999-12-20 21:23:41 +0000110static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000111 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000112#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000113 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000114#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000115 {".pyc", "rb", PY_COMPILED},
116 {0, 0}
117};
118
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000120/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121
122void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000123_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000124{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000125 const struct filedescr *scan;
126 struct filedescr *filetab;
127 int countD = 0;
128 int countS = 0;
129
130 /* prepare _PyImport_Filetab: copy entries from
131 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
132 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000133#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
135 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000136#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000137 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
138 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000139 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140 if (filetab == NULL)
141 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000142#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143 memcpy(filetab, _PyImport_DynLoadFiletab,
144 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000145#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146 memcpy(filetab + countD, _PyImport_StandardFiletab,
147 countS * sizeof(struct filedescr));
148 filetab[countD + countS].suffix = NULL;
149
150 _PyImport_Filetab = filetab;
151
Guido van Rossum0824f631997-03-11 18:37:35 +0000152 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
154 for (; filetab->suffix != NULL; filetab++) {
155 if (strcmp(filetab->suffix, ".pyc") == 0)
156 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000157 }
158 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000159
Guido van Rossum572dbf82007-04-27 23:53:51 +0000160 {
Guido van Rossum96774c12000-05-01 20:19:08 +0000161 /* Fix the pyc_magic so that byte compiled code created
162 using the all-Unicode method doesn't interfere with
163 code created in normal operation mode. */
164 pyc_magic = MAGIC + 1;
165 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166}
167
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168void
Just van Rossum52e14d62002-12-30 22:08:05 +0000169_PyImportHooks_Init(void)
170{
171 PyObject *v, *path_hooks = NULL, *zimpimport;
172 int err = 0;
173
174 /* adding sys.path_hooks and sys.path_importer_cache, setting up
175 zipimport */
Christian Heimes9cd17752007-11-18 19:35:23 +0000176 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000178
179 if (Py_VerboseFlag)
180 PySys_WriteStderr("# installing zipimport hook\n");
181
182 v = PyList_New(0);
183 if (v == NULL)
184 goto error;
185 err = PySys_SetObject("meta_path", v);
186 Py_DECREF(v);
187 if (err)
188 goto error;
189 v = PyDict_New();
190 if (v == NULL)
191 goto error;
192 err = PySys_SetObject("path_importer_cache", v);
193 Py_DECREF(v);
194 if (err)
195 goto error;
196 path_hooks = PyList_New(0);
197 if (path_hooks == NULL)
198 goto error;
199 err = PySys_SetObject("path_hooks", path_hooks);
200 if (err) {
201 error:
202 PyErr_Print();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000203 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
204 "path_importer_cache, or NullImporter failed"
205 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000206 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000207
Just van Rossum52e14d62002-12-30 22:08:05 +0000208 zimpimport = PyImport_ImportModule("zipimport");
209 if (zimpimport == NULL) {
210 PyErr_Clear(); /* No zip import module -- okay */
211 if (Py_VerboseFlag)
212 PySys_WriteStderr("# can't import zipimport\n");
213 }
214 else {
215 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
216 "zipimporter");
217 Py_DECREF(zimpimport);
218 if (zipimporter == NULL) {
219 PyErr_Clear(); /* No zipimporter object -- okay */
220 if (Py_VerboseFlag)
221 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000222 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000223 }
224 else {
225 /* sys.path_hooks.append(zipimporter) */
226 err = PyList_Append(path_hooks, zipimporter);
227 Py_DECREF(zipimporter);
228 if (err)
229 goto error;
230 if (Py_VerboseFlag)
231 PySys_WriteStderr(
232 "# installed zipimport hook\n");
233 }
234 }
235 Py_DECREF(path_hooks);
236}
237
238void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240{
241 Py_XDECREF(extensions);
242 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000243 PyMem_DEL(_PyImport_Filetab);
244 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000245}
246
247
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000248/* Locking primitives to prevent parallel imports of the same module
249 in different threads to return with a partially loaded module.
250 These calls are serialized by the global interpreter lock. */
251
252#ifdef WITH_THREAD
253
Guido van Rossum49b56061998-10-01 20:42:43 +0000254#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255
Guido van Rossum65d5b571998-12-21 19:32:43 +0000256static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000257static long import_lock_thread = -1;
258static int import_lock_level = 0;
259
260static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000261lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000262{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000263 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264 if (me == -1)
265 return; /* Too bad */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000266 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000267 import_lock = PyThread_allocate_lock();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000268 if (import_lock == NULL)
269 return; /* Nothing much we can do. */
270 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000271 if (import_lock_thread == me) {
272 import_lock_level++;
273 return;
274 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000275 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
276 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000278 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279 PyEval_RestoreThread(tstate);
280 }
281 import_lock_thread = me;
282 import_lock_level = 1;
283}
284
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000286unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000288 long me = PyThread_get_thread_ident();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000291 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000292 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000293 import_lock_level--;
294 if (import_lock_level == 0) {
295 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000296 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000298 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000299}
300
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000301/* This function is called from PyOS_AfterFork to ensure that newly
302 created child processes do not share locks with the parent. */
303
304void
305_PyImport_ReInitLock(void)
306{
307#ifdef _AIX
308 if (import_lock != NULL)
309 import_lock = PyThread_allocate_lock();
310#endif
311}
312
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000313#else
314
315#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000316#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000317
318#endif
319
Tim Peters69232342001-08-30 05:16:13 +0000320static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000321imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000322{
Tim Peters69232342001-08-30 05:16:13 +0000323#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000324 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000325#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000326 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000327#endif
328}
329
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000331imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333#ifdef WITH_THREAD
334 lock_import();
335#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000336 Py_INCREF(Py_None);
337 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000338}
339
340static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000341imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343#ifdef WITH_THREAD
344 if (unlock_import() < 0) {
345 PyErr_SetString(PyExc_RuntimeError,
346 "not holding the import lock");
347 return NULL;
348 }
349#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000350 Py_INCREF(Py_None);
351 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352}
353
Guido van Rossumd8faa362007-04-27 19:54:29 +0000354static void
355imp_modules_reloading_clear(void)
356{
357 PyInterpreterState *interp = PyThreadState_Get()->interp;
358 if (interp->modules_reloading != NULL)
359 PyDict_Clear(interp->modules_reloading);
360}
361
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362/* Helper for sys */
363
364PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000365PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000367 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368 if (interp->modules == NULL)
369 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
370 return interp->modules;
371}
372
Guido van Rossum3f5da241990-12-20 15:06:42 +0000373
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000374/* List of names to clear in sys */
375static char* sys_deletes[] = {
Collin Winter670e6922007-03-21 02:57:17 +0000376 "path", "argv", "ps1", "ps2",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000378 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000379 /* misc stuff */
380 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000381 NULL
382};
383
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000384static char* sys_files[] = {
385 "stdin", "__stdin__",
386 "stdout", "__stdout__",
387 "stderr", "__stderr__",
388 NULL
389};
390
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000391
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000392/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000393
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000395PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000397 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000398 char *name;
399 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000400 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000401 PyObject *modules = interp->modules;
402
403 if (modules == NULL)
404 return; /* Already done */
405
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000406 /* Delete some special variables first. These are common
407 places where user values hide and people complain when their
408 destructors fail. Since the modules containing them are
409 deleted *last* of all, they would come too late in the normal
410 destruction order. Sigh. */
411
Georg Brandl1a3284e2007-12-02 09:40:06 +0000412 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000413 if (value != NULL && PyModule_Check(value)) {
414 dict = PyModule_GetDict(value);
415 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000416 PySys_WriteStderr("# clear builtins._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000417 PyDict_SetItemString(dict, "_", Py_None);
418 }
419 value = PyDict_GetItemString(modules, "sys");
420 if (value != NULL && PyModule_Check(value)) {
421 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000422 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000423 dict = PyModule_GetDict(value);
424 for (p = sys_deletes; *p != NULL; p++) {
425 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000426 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000427 PyDict_SetItemString(dict, *p, Py_None);
428 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000429 for (p = sys_files; *p != NULL; p+=2) {
430 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000431 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000432 v = PyDict_GetItemString(dict, *(p+1));
433 if (v == NULL)
434 v = Py_None;
435 PyDict_SetItemString(dict, *p, v);
436 }
437 }
438
439 /* First, delete __main__ */
440 value = PyDict_GetItemString(modules, "__main__");
441 if (value != NULL && PyModule_Check(value)) {
442 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000443 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000444 _PyModule_Clear(value);
445 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000446 }
447
Georg Brandl1a3284e2007-12-02 09:40:06 +0000448 /* The special treatment of "builtins" here is because even
Guido van Rossum758eec01998-01-19 21:58:26 +0000449 when it's not referenced as a module, its dictionary is
450 referenced by almost every module's __builtins__. Since
451 deleting a module clears its dictionary (even if there are
Georg Brandl1a3284e2007-12-02 09:40:06 +0000452 references left to it), we need to delete the "builtins"
Guido van Rossum758eec01998-01-19 21:58:26 +0000453 module last. Likewise, we don't delete sys until the very
454 end because it is implicitly referenced (e.g. by print).
455
456 Also note that we 'delete' modules by replacing their entry
457 in the modules dict with None, rather than really deleting
458 them; this avoids a rehash of the modules dictionary and
459 also marks them as "non existent" so they won't be
460 re-imported. */
461
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000462 /* Next, repeatedly delete modules with a reference count of
Georg Brandl1a3284e2007-12-02 09:40:06 +0000463 one (skipping builtins and sys) and delete them */
Guido van Rossum758eec01998-01-19 21:58:26 +0000464 do {
465 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000466 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000467 while (PyDict_Next(modules, &pos, &key, &value)) {
468 if (value->ob_refcnt != 1)
469 continue;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000470 if (PyUnicode_Check(key) && PyModule_Check(value)) {
471 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000472 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000473 continue;
474 if (strcmp(name, "sys") == 0)
475 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000476 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000477 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000478 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000479 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000480 PyDict_SetItem(modules, key, Py_None);
481 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000482 }
483 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000484 } while (ndone > 0);
485
Georg Brandl1a3284e2007-12-02 09:40:06 +0000486 /* Next, delete all modules (still skipping builtins and sys) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000487 pos = 0;
488 while (PyDict_Next(modules, &pos, &key, &value)) {
Neal Norwitz80e7f272007-08-26 06:45:23 +0000489 if (PyUnicode_Check(key) && PyModule_Check(value)) {
490 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000491 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000492 continue;
493 if (strcmp(name, "sys") == 0)
494 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000495 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000496 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000497 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000498 PyDict_SetItem(modules, key, Py_None);
499 }
500 }
501
Georg Brandl1a3284e2007-12-02 09:40:06 +0000502 /* Next, delete sys and builtins (in that order) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000503 value = PyDict_GetItemString(modules, "sys");
504 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000505 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000506 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000507 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000508 PyDict_SetItemString(modules, "sys", Py_None);
509 }
Georg Brandl1a3284e2007-12-02 09:40:06 +0000510 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossum758eec01998-01-19 21:58:26 +0000511 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000512 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000513 PySys_WriteStderr("# cleanup builtins\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000514 _PyModule_Clear(value);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000515 PyDict_SetItemString(modules, "builtins", Py_None);
Guido van Rossum758eec01998-01-19 21:58:26 +0000516 }
517
518 /* Finally, clear and delete the modules directory */
519 PyDict_Clear(modules);
520 interp->modules = NULL;
521 Py_DECREF(modules);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000523}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000524
525
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000526/* Helper for pythonrun.c -- return magic number */
527
528long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000529PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000530{
Guido van Rossum96774c12000-05-01 20:19:08 +0000531 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000532}
533
534
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535/* Magic for extension modules (built-in as well as dynamically
536 loaded). To prevent initializing an extension module more than
537 once, we keep a static dictionary 'extensions' keyed by module name
538 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000539 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000540 dictionary is stored by calling _PyImport_FixupExtension()
541 immediately after the module initialization function succeeds. A
542 copy can be retrieved from there by calling
543 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000544
Guido van Rossum79f25d91997-04-29 20:08:16 +0000545PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000546_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548 PyObject *modules, *mod, *dict, *copy;
549 if (extensions == NULL) {
550 extensions = PyDict_New();
551 if (extensions == NULL)
552 return NULL;
553 }
554 modules = PyImport_GetModuleDict();
555 mod = PyDict_GetItemString(modules, name);
556 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000557 PyErr_Format(PyExc_SystemError,
558 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559 return NULL;
560 }
561 dict = PyModule_GetDict(mod);
562 if (dict == NULL)
563 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000564 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565 if (copy == NULL)
566 return NULL;
567 PyDict_SetItemString(extensions, filename, copy);
568 Py_DECREF(copy);
569 return copy;
570}
571
572PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000573_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000575 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576 if (extensions == NULL)
577 return NULL;
578 dict = PyDict_GetItemString(extensions, filename);
579 if (dict == NULL)
580 return NULL;
581 mod = PyImport_AddModule(name);
582 if (mod == NULL)
583 return NULL;
584 mdict = PyModule_GetDict(mod);
585 if (mdict == NULL)
586 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000587 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000590 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591 name, filename);
592 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593}
594
595
596/* Get the module object corresponding to a module name.
597 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000598 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000599 Because the former action is most common, THIS DOES NOT RETURN A
600 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601
Guido van Rossum79f25d91997-04-29 20:08:16 +0000602PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000603PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000606 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000609 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612 if (m == NULL)
613 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000615 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000616 return NULL;
617 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000618 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619
620 return m;
621}
622
Tim Peters1cd70172004-08-02 03:52:12 +0000623/* Remove name from sys.modules, if it's there. */
624static void
625_RemoveModule(const char *name)
626{
627 PyObject *modules = PyImport_GetModuleDict();
628 if (PyDict_GetItemString(modules, name) == NULL)
629 return;
630 if (PyDict_DelItemString(modules, name) < 0)
631 Py_FatalError("import: deleting existing key in"
632 "sys.modules failed");
633}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000634
Christian Heimes3b06e532008-01-07 20:12:44 +0000635static PyObject * get_sourcefile(const char *file);
636
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000637/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000638 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
639 * removed from sys.modules, to avoid leaving damaged module objects
640 * in sys.modules. The caller may wish to restore the original
641 * module object (if any) in this case; PyImport_ReloadModule is an
642 * example.
643 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000644PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000647 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
648}
649
650PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000651PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000652{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000654 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000655
Guido van Rossum79f25d91997-04-29 20:08:16 +0000656 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000657 if (m == NULL)
658 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000659 /* If the module is being reloaded, we get the old module back
660 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000661 d = PyModule_GetDict(m);
662 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
663 if (PyDict_SetItemString(d, "__builtins__",
664 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000665 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000666 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000667 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000668 v = NULL;
669 if (pathname != NULL) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000670 v = get_sourcefile(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000671 if (v == NULL)
672 PyErr_Clear();
673 }
674 if (v == NULL) {
675 v = ((PyCodeObject *)co)->co_filename;
676 Py_INCREF(v);
677 }
678 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000679 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000680 Py_DECREF(v);
681
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000682 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000683 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000684 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000685 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000686
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000688 PyErr_Format(PyExc_ImportError,
689 "Loaded module %.200s not found in sys.modules",
690 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000691 return NULL;
692 }
693
Guido van Rossum79f25d91997-04-29 20:08:16 +0000694 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
696 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000697
698 error:
699 _RemoveModule(name);
700 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000701}
702
703
704/* Given a pathname for a Python source file, fill a buffer with the
705 pathname for the corresponding compiled file. Return the pathname
706 for the compiled file, or NULL if there's no space in the buffer.
707 Doesn't set an exception. */
708
709static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000710make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711{
Tim Petersc1731372001-08-04 08:12:36 +0000712 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000713 if (len+2 > buflen)
714 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000715
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000716#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000717 /* Treat .pyw as if it were .py. The case of ".pyw" must match
718 that used in _PyImport_StandardFiletab. */
719 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
720 --len; /* pretend 'w' isn't there */
721#endif
722 memcpy(buf, pathname, len);
723 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
724 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000725
726 return buf;
727}
728
729
730/* Given a pathname for a Python source file, its time of last
731 modification, and a pathname for a compiled file, check whether the
732 compiled file represents the same version of the source. If so,
733 return a FILE pointer for the compiled file, positioned just after
734 the header; if not, return NULL.
735 Doesn't set an exception. */
736
737static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739{
740 FILE *fp;
741 long magic;
742 long pyc_mtime;
743
744 fp = fopen(cpathname, "rb");
745 if (fp == NULL)
746 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000747 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000748 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000749 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000750 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751 fclose(fp);
752 return NULL;
753 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000754 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000756 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000757 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000758 fclose(fp);
759 return NULL;
760 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000761 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000762 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763 return fp;
764}
765
766
767/* Read a code object from a file and check it for validity */
768
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000770read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000772 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773
Tim Petersd9b9ac82001-01-28 00:27:39 +0000774 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000775 if (co == NULL)
776 return NULL;
777 if (!PyCode_Check(co)) {
778 PyErr_Format(PyExc_ImportError,
779 "Non-code object in %.200s", cpathname);
780 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781 return NULL;
782 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000783 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000784}
785
786
787/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000788 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000789
Guido van Rossum79f25d91997-04-29 20:08:16 +0000790static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000791load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000792{
793 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000794 PyCodeObject *co;
795 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000796
Guido van Rossum79f25d91997-04-29 20:08:16 +0000797 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000798 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000799 PyErr_Format(PyExc_ImportError,
800 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000801 return NULL;
802 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000803 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000804 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000805 if (co == NULL)
806 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000807 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000808 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000809 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000810 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000811 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812
813 return m;
814}
815
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000816/* Parse a source file and return the corresponding code object */
817
Guido van Rossum79f25d91997-04-29 20:08:16 +0000818static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000821 PyCodeObject *co = NULL;
822 mod_ty mod;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823 PyArena *arena = PyArena_New();
824 if (arena == NULL)
825 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000827 mod = PyParser_ASTFromFile(fp, pathname, NULL,
828 Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000829 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000831 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000833 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834 return co;
835}
836
837
Guido van Rossum55a83382000-09-20 20:31:38 +0000838/* Helper to open a bytecode file for writing in exclusive mode */
839
840static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +0000841open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000842{
843#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
844 /* Use O_EXCL to avoid a race condition when another process tries to
845 write the same file. When that happens, our open() call fails,
846 which is just fine (since it's only a cache).
847 XXX If the file exists and is writable but the directory is not
848 writable, the file will never be written. Oh well.
849 */
850 int fd;
851 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000852 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
853#ifdef O_BINARY
854 |O_BINARY /* necessary for Windows */
855#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000856#ifdef __VMS
Christian Heimes05e8be12008-02-23 18:30:17 +0000857 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000858#else
Christian Heimes05e8be12008-02-23 18:30:17 +0000859 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000860#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000861 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000862 if (fd < 0)
863 return NULL;
864 return fdopen(fd, "wb");
865#else
866 /* Best we can do -- on Windows this can't happen anyway */
867 return fopen(filename, "wb");
868#endif
869}
870
871
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872/* Write a compiled module to a file, placing the time of last
873 modification of its source into the header.
874 Errors are ignored, if a write error occurs an attempt is made to
875 remove the file. */
876
877static void
Christian Heimes05e8be12008-02-23 18:30:17 +0000878write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879{
880 FILE *fp;
Christian Heimes05e8be12008-02-23 18:30:17 +0000881 time_t mtime = srcstat->st_mtime;
882 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Christian Heimes05e8be12008-02-23 18:30:17 +0000884 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000886 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000887 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888 "# can't create %s\n", cpathname);
889 return;
890 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000891 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000892 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000893 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
894 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000895 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000896 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000897 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898 /* Don't keep partial file */
899 fclose(fp);
900 (void) unlink(cpathname);
901 return;
902 }
903 /* Now write the true mtime */
904 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000905 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000906 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000907 fflush(fp);
908 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000909 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000910 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000911}
912
913
914/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000915 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
916 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917
Guido van Rossum79f25d91997-04-29 20:08:16 +0000918static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000919load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920{
Christian Heimes05e8be12008-02-23 18:30:17 +0000921 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000922 FILE *fpc;
923 char buf[MAXPATHLEN+1];
924 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000925 PyCodeObject *co;
926 PyObject *m;
Christian Heimes05e8be12008-02-23 18:30:17 +0000927
928 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000929 PyErr_Format(PyExc_RuntimeError,
Christian Heimes05e8be12008-02-23 18:30:17 +0000930 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000931 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000932 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000933 }
Fred Drake4c82b232000-06-30 16:18:57 +0000934#if SIZEOF_TIME_T > 4
935 /* Python's .pyc timestamp handling presumes that the timestamp fits
936 in 4 bytes. This will be fine until sometime in the year 2038,
937 when a 4-byte signed time_t will overflow.
938 */
Christian Heimes05e8be12008-02-23 18:30:17 +0000939 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000940 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000941 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000942 return NULL;
943 }
944#endif
Tim Peters36515e22001-11-18 04:06:29 +0000945 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000946 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000947 if (cpathname != NULL &&
Christian Heimes05e8be12008-02-23 18:30:17 +0000948 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000949 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000950 fclose(fpc);
951 if (co == NULL)
952 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000953 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000954 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000955 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000956 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000957 }
958 else {
959 co = parse_source_module(pathname, fp);
960 if (co == NULL)
961 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000962 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000963 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000964 name, pathname);
Christian Heimes790c8232008-01-07 21:14:23 +0000965 if (cpathname) {
966 PyObject *ro = PySys_GetObject("dont_write_bytecode");
967 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes05e8be12008-02-23 18:30:17 +0000968 write_compiled_module(co, cpathname, &st);
Christian Heimes790c8232008-01-07 21:14:23 +0000969 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000970 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000971 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000972 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000973
974 return m;
975}
976
Christian Heimes3b06e532008-01-07 20:12:44 +0000977/* Get source file -> unicode or None
978 * Returns the path to the py file if available, else the given path
979 */
980static PyObject *
981get_sourcefile(const char *file)
982{
983 char py[MAXPATHLEN + 1];
984 Py_ssize_t len;
985 PyObject *u;
986 struct stat statbuf;
987
988 if (!file || !*file) {
989 Py_RETURN_NONE;
990 }
991
992 len = strlen(file);
Christian Heimes3540b502008-01-11 07:03:05 +0000993 /* match '*.py?' */
994 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000995 return PyUnicode_DecodeFSDefault(file);
996 }
997
998 strncpy(py, file, len-1);
999 py[len] = '\0';
1000 if (stat(py, &statbuf) == 0 &&
1001 S_ISREG(statbuf.st_mode)) {
1002 u = PyUnicode_DecodeFSDefault(py);
1003 }
1004 else {
1005 u = PyUnicode_DecodeFSDefault(file);
1006 }
1007 return u;
1008}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001009
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001010/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001011static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1012static struct filedescr *find_module(char *, char *, PyObject *,
1013 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001014static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001015
1016/* Load a package and return its module object WITH INCREMENTED
1017 REFERENCE COUNT */
1018
1019static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001020load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001021{
Tim Peters1cd70172004-08-02 03:52:12 +00001022 PyObject *m, *d;
1023 PyObject *file = NULL;
1024 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001025 int err;
1026 char buf[MAXPATHLEN+1];
1027 FILE *fp = NULL;
1028 struct filedescr *fdp;
1029
1030 m = PyImport_AddModule(name);
1031 if (m == NULL)
1032 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001033 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001034 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001035 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001036 d = PyModule_GetDict(m);
Christian Heimes3b06e532008-01-07 20:12:44 +00001037 file = get_sourcefile(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001038 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001039 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001040 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001041 if (path == NULL)
1042 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001043 err = PyDict_SetItemString(d, "__file__", file);
1044 if (err == 0)
1045 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001046 if (err != 0)
1047 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001048 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001049 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001050 if (fdp == NULL) {
1051 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1052 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001053 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001054 }
1055 else
1056 m = NULL;
1057 goto cleanup;
1058 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001059 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001060 if (fp != NULL)
1061 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001062 goto cleanup;
1063
1064 error:
1065 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001066 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067 Py_XDECREF(path);
1068 Py_XDECREF(file);
1069 return m;
1070}
1071
1072
1073/* Helper to test for built-in module */
1074
1075static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001076is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001077{
1078 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001079 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1080 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1081 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001082 return -1;
1083 else
1084 return 1;
1085 }
1086 }
1087 return 0;
1088}
1089
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001090
Just van Rossum52e14d62002-12-30 22:08:05 +00001091/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1092 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001093 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001094 that can handle the path item. Return None if no hook could;
1095 this tells our caller it should fall back to the builtin
1096 import mechanism. Cache the result in path_importer_cache.
1097 Returns a borrowed reference. */
1098
1099static PyObject *
1100get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1101 PyObject *p)
1102{
1103 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001104 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001105
1106 /* These conditions are the caller's responsibility: */
1107 assert(PyList_Check(path_hooks));
1108 assert(PyDict_Check(path_importer_cache));
1109
1110 nhooks = PyList_Size(path_hooks);
1111 if (nhooks < 0)
1112 return NULL; /* Shouldn't happen */
1113
1114 importer = PyDict_GetItem(path_importer_cache, p);
1115 if (importer != NULL)
1116 return importer;
1117
1118 /* set path_importer_cache[p] to None to avoid recursion */
1119 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1120 return NULL;
1121
1122 for (j = 0; j < nhooks; j++) {
1123 PyObject *hook = PyList_GetItem(path_hooks, j);
1124 if (hook == NULL)
1125 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001127 if (importer != NULL)
1128 break;
1129
1130 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1131 return NULL;
1132 }
1133 PyErr_Clear();
1134 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001135 if (importer == NULL) {
1136 importer = PyObject_CallFunctionObjArgs(
Christian Heimes9cd17752007-11-18 19:35:23 +00001137 (PyObject *)&PyNullImporter_Type, p, NULL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138 );
1139 if (importer == NULL) {
1140 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1141 PyErr_Clear();
1142 return Py_None;
1143 }
1144 }
1145 }
1146 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001147 int err = PyDict_SetItem(path_importer_cache, p, importer);
1148 Py_DECREF(importer);
1149 if (err != 0)
1150 return NULL;
1151 }
1152 return importer;
1153}
1154
Christian Heimes9cd17752007-11-18 19:35:23 +00001155PyAPI_FUNC(PyObject *)
1156PyImport_GetImporter(PyObject *path) {
1157 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1158
1159 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1160 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1161 importer = get_path_importer(path_importer_cache,
1162 path_hooks, path);
1163 }
1164 }
1165 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1166 return importer;
1167}
1168
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169/* Search the path (default sys.path) for a module. Return the
1170 corresponding filedescr struct, and (via return arguments) the
1171 pathname and an open file. Return NULL if the module is not found. */
1172
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001173#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001174extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001176#endif
1177
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001179static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001180static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001181
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001182static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001183find_module(char *fullname, char *subname, PyObject *path, char *buf,
1184 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001185{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001186 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001187 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001188 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001189 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001190 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001191 PyObject *path_hooks, *path_importer_cache;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001192 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001193 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1194 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1195 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001196 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001197#if defined(PYOS_OS2)
1198 size_t saved_len;
1199 size_t saved_namelen;
1200 char *saved_buf = NULL;
1201#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001202 if (p_loader != NULL)
1203 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001204
Just van Rossum52e14d62002-12-30 22:08:05 +00001205 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001206 PyErr_SetString(PyExc_OverflowError,
1207 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001208 return NULL;
1209 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001210 strcpy(name, subname);
1211
1212 /* sys.meta_path import hook */
1213 if (p_loader != NULL) {
1214 PyObject *meta_path;
1215
1216 meta_path = PySys_GetObject("meta_path");
1217 if (meta_path == NULL || !PyList_Check(meta_path)) {
1218 PyErr_SetString(PyExc_ImportError,
1219 "sys.meta_path must be a list of "
1220 "import hooks");
1221 return NULL;
1222 }
1223 Py_INCREF(meta_path); /* zap guard */
1224 npath = PyList_Size(meta_path);
1225 for (i = 0; i < npath; i++) {
1226 PyObject *loader;
1227 PyObject *hook = PyList_GetItem(meta_path, i);
1228 loader = PyObject_CallMethod(hook, "find_module",
1229 "sO", fullname,
1230 path != NULL ?
1231 path : Py_None);
1232 if (loader == NULL) {
1233 Py_DECREF(meta_path);
1234 return NULL; /* true error */
1235 }
1236 if (loader != Py_None) {
1237 /* a loader was found */
1238 *p_loader = loader;
1239 Py_DECREF(meta_path);
1240 return &importhookdescr;
1241 }
1242 Py_DECREF(loader);
1243 }
1244 Py_DECREF(meta_path);
1245 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001246
Guido van Rossum13d77992007-07-23 03:16:50 +00001247 if (path != NULL && PyUnicode_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001248 /* The only type of submodule allowed inside a "frozen"
1249 package are other frozen modules or packages. */
Guido van Rossum13d77992007-07-23 03:16:50 +00001250 char *p = PyUnicode_AsString(path);
1251 if (strlen(p) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001252 PyErr_SetString(PyExc_ImportError,
1253 "full frozen module name too long");
1254 return NULL;
1255 }
Guido van Rossum13d77992007-07-23 03:16:50 +00001256 strcpy(buf, p);
Guido van Rossum0506a431998-08-11 15:07:39 +00001257 strcat(buf, ".");
1258 strcat(buf, name);
1259 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001260 if (find_frozen(name) != NULL) {
1261 strcpy(buf, name);
1262 return &fd_frozen;
1263 }
1264 PyErr_Format(PyExc_ImportError,
1265 "No frozen submodule named %.200s", name);
1266 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001267 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001268 if (path == NULL) {
1269 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001270 strcpy(buf, name);
1271 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001272 }
Greg Ward201baee2001-10-04 14:52:06 +00001273 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001274 strcpy(buf, name);
1275 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001276 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277
Guido van Rossumac279101996-08-22 23:10:58 +00001278#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001279 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1280 if (fp != NULL) {
1281 *p_fp = fp;
1282 return fdp;
1283 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001284#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001285 path = PySys_GetObject("path");
1286 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001287 if (path == NULL || !PyList_Check(path)) {
1288 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001289 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001290 return NULL;
1291 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001292
1293 path_hooks = PySys_GetObject("path_hooks");
1294 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1295 PyErr_SetString(PyExc_ImportError,
1296 "sys.path_hooks must be a list of "
1297 "import hooks");
1298 return NULL;
1299 }
1300 path_importer_cache = PySys_GetObject("path_importer_cache");
1301 if (path_importer_cache == NULL ||
1302 !PyDict_Check(path_importer_cache)) {
1303 PyErr_SetString(PyExc_ImportError,
1304 "sys.path_importer_cache must be a dict");
1305 return NULL;
1306 }
1307
Guido van Rossum79f25d91997-04-29 20:08:16 +00001308 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001309 namelen = strlen(name);
1310 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001311 PyObject *v = PyList_GetItem(path, i);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001312 PyObject *origv = v;
Guido van Rossum6262cc72007-05-09 23:29:27 +00001313 const char *base;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001314 Py_ssize_t size;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001315 if (!v)
1316 return NULL;
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001317 if (PyUnicode_Check(v)) {
1318 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1319 if (v == NULL)
1320 return NULL;
1321 }
1322 if (!PyString_Check(v))
1323 continue;
1324 base = PyString_AS_STRING(v);
1325 size = PyString_GET_SIZE(v);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001326 len = size;
Walter Dörwald3430d702002-06-17 10:43:59 +00001327 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001328 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001329 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001330 strcpy(buf, base);
Walter Dörwald3430d702002-06-17 10:43:59 +00001331 if (strlen(buf) != len) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001332 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001333 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001334
1335 /* sys.path_hooks import hook */
1336 if (p_loader != NULL) {
1337 PyObject *importer;
1338
1339 importer = get_path_importer(path_importer_cache,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001340 path_hooks, origv);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001341 if (importer == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001342 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344 /* Note: importer is a borrowed reference */
1345 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001346 PyObject *loader;
1347 loader = PyObject_CallMethod(importer,
1348 "find_module",
1349 "s", fullname);
1350 if (loader == NULL)
1351 return NULL; /* error */
1352 if (loader != Py_None) {
1353 /* a loader was found */
1354 *p_loader = loader;
1355 return &importhookdescr;
1356 }
1357 Py_DECREF(loader);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001358 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001359 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001360 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001361 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001362
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001363 if (len > 0 && buf[len-1] != SEP
1364#ifdef ALTSEP
1365 && buf[len-1] != ALTSEP
1366#endif
1367 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001368 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001369 strcpy(buf+len, name);
1370 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001371
1372 /* Check for package import (buf holds a directory name,
1373 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001374#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001375 if (stat(buf, &statbuf) == 0 && /* it exists */
1376 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001377 case_ok(buf, len, namelen, name)) { /* case matches */
1378 if (find_init_module(buf)) { /* and has __init__.py */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001379 return &fd_package;
1380 }
1381 else {
1382 char warnstr[MAXPATHLEN+80];
1383 sprintf(warnstr, "Not importing directory "
1384 "'%.*s': missing __init__.py",
1385 MAXPATHLEN, buf);
Skip Montanaro46fc3372007-08-12 11:44:53 +00001386 if (PyErr_WarnEx(PyExc_ImportWarning,
1387 warnstr, 1)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388 return NULL;
1389 }
1390 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001391 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001392#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001393#if defined(PYOS_OS2)
1394 /* take a snapshot of the module spec for restoration
1395 * after the 8 character DLL hackery
1396 */
1397 saved_buf = strdup(buf);
1398 saved_len = len;
1399 saved_namelen = namelen;
1400#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001401 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001402#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001403 /* OS/2 limits DLLs to 8 character names (w/o
1404 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001405 * so if the name is longer than that and its a
1406 * dynamically loaded module we're going to try,
1407 * truncate the name before trying
1408 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001409 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001410 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001411 const struct filedescr *scan;
1412 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001413 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001414 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001415 break;
1416 else
1417 scan++;
1418 }
1419 if (scan->suffix != NULL) {
1420 /* yes, so truncate the name */
1421 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001422 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001423 buf[len] = '\0';
1424 }
1425 }
1426#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001427 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001428 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001429 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001430 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001431 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001432 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001433 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001434 if (fp != NULL) {
1435 if (case_ok(buf, len, namelen, name))
1436 break;
1437 else { /* continue search */
1438 fclose(fp);
1439 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001440 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001441 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001442#if defined(PYOS_OS2)
1443 /* restore the saved snapshot */
1444 strcpy(buf, saved_buf);
1445 len = saved_len;
1446 namelen = saved_namelen;
1447#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001448 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001449#if defined(PYOS_OS2)
1450 /* don't need/want the module name snapshot anymore */
1451 if (saved_buf)
1452 {
1453 free(saved_buf);
1454 saved_buf = NULL;
1455 }
1456#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001457 if (fp != NULL)
1458 break;
1459 }
1460 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001461 PyErr_Format(PyExc_ImportError,
1462 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001463 return NULL;
1464 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001465 *p_fp = fp;
1466 return fdp;
1467}
1468
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001469/* Helpers for main.c
1470 * Find the source file corresponding to a named module
1471 */
1472struct filedescr *
1473_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1474 size_t buflen, FILE **p_fp, PyObject **p_loader)
1475{
1476 return find_module((char *) name, (char *) name, path,
1477 buf, buflen, p_fp, p_loader);
1478}
1479
1480PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1481{
1482 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1483}
1484
Martin v. Löwis18e16552006-02-15 17:27:45 +00001485/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001486 * The arguments here are tricky, best shown by example:
1487 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1488 * ^ ^ ^ ^
1489 * |--------------------- buf ---------------------|
1490 * |------------------- len ------------------|
1491 * |------ name -------|
1492 * |----- namelen -----|
1493 * buf is the full path, but len only counts up to (& exclusive of) the
1494 * extension. name is the module name, also exclusive of extension.
1495 *
1496 * We've already done a successful stat() or fopen() on buf, so know that
1497 * there's some match, possibly case-insensitive.
1498 *
Tim Peters50d8d372001-02-28 05:34:27 +00001499 * case_ok() is to return 1 if there's a case-sensitive match for
1500 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1501 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001502 *
Tim Peters50d8d372001-02-28 05:34:27 +00001503 * case_ok() is used to implement case-sensitive import semantics even
1504 * on platforms with case-insensitive filesystems. It's trivial to implement
1505 * for case-sensitive filesystems. It's pretty much a cross-platform
1506 * nightmare for systems with case-insensitive filesystems.
1507 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001508
Tim Peters50d8d372001-02-28 05:34:27 +00001509/* First we may need a pile of platform-specific header files; the sequence
1510 * of #if's here should match the sequence in the body of case_ok().
1511 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001512#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001513#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001514
Tim Peters50d8d372001-02-28 05:34:27 +00001515#elif defined(DJGPP)
1516#include <dir.h>
1517
Jason Tishler7961aa62005-05-20 00:56:54 +00001518#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001519#include <sys/types.h>
1520#include <dirent.h>
1521
Andrew MacIntyred9400542002-02-26 11:41:34 +00001522#elif defined(PYOS_OS2)
1523#define INCL_DOS
1524#define INCL_DOSERRORS
1525#define INCL_NOPMAPI
1526#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001527#endif
1528
Guido van Rossum0980bd91998-02-13 17:18:36 +00001529static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001530case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001531{
Tim Peters50d8d372001-02-28 05:34:27 +00001532/* Pick a platform-specific implementation; the sequence of #if's here should
1533 * match the sequence just above.
1534 */
1535
Jason Tishler7961aa62005-05-20 00:56:54 +00001536/* MS_WINDOWS */
1537#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001538 WIN32_FIND_DATA data;
1539 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001540
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001541 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001542 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001543
Guido van Rossum0980bd91998-02-13 17:18:36 +00001544 h = FindFirstFile(buf, &data);
1545 if (h == INVALID_HANDLE_VALUE) {
1546 PyErr_Format(PyExc_NameError,
1547 "Can't find file for module %.100s\n(filename %.300s)",
1548 name, buf);
1549 return 0;
1550 }
1551 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001552 return strncmp(data.cFileName, name, namelen) == 0;
1553
1554/* DJGPP */
1555#elif defined(DJGPP)
1556 struct ffblk ffblk;
1557 int done;
1558
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001559 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001560 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001561
1562 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1563 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001564 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001565 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001566 name, buf);
1567 return 0;
1568 }
Tim Peters50d8d372001-02-28 05:34:27 +00001569 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001570
Jason Tishler7961aa62005-05-20 00:56:54 +00001571/* new-fangled macintosh (macosx) or Cygwin */
1572#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001573 DIR *dirp;
1574 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001575 char dirname[MAXPATHLEN + 1];
1576 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001577
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001578 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001579 return 1;
1580
Tim Petersd1e87a82001-03-01 18:12:00 +00001581 /* Copy the dir component into dirname; substitute "." if empty */
1582 if (dirlen <= 0) {
1583 dirname[0] = '.';
1584 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001585 }
1586 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001587 assert(dirlen <= MAXPATHLEN);
1588 memcpy(dirname, buf, dirlen);
1589 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001590 }
1591 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001592 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001593 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001594 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001595 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001596 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001597#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001598 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001599#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001600 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001601#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001602 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001603 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001604 (void)closedir(dirp);
1605 return 1; /* Found */
1606 }
1607 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001608 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001609 }
Tim Peters430f5d42001-03-01 01:30:56 +00001610 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001611
Andrew MacIntyred9400542002-02-26 11:41:34 +00001612/* OS/2 */
1613#elif defined(PYOS_OS2)
1614 HDIR hdir = 1;
1615 ULONG srchcnt = 1;
1616 FILEFINDBUF3 ffbuf;
1617 APIRET rc;
1618
Christian Heimes790c8232008-01-07 21:14:23 +00001619 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001620 return 1;
1621
1622 rc = DosFindFirst(buf,
1623 &hdir,
1624 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1625 &ffbuf, sizeof(ffbuf),
1626 &srchcnt,
1627 FIL_STANDARD);
1628 if (rc != NO_ERROR)
1629 return 0;
1630 return strncmp(ffbuf.achName, name, namelen) == 0;
1631
Tim Peters50d8d372001-02-28 05:34:27 +00001632/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1633#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001634 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001635
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001636#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001637}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001638
Guido van Rossum0980bd91998-02-13 17:18:36 +00001639
Guido van Rossum197346f1997-10-31 18:38:52 +00001640#ifdef HAVE_STAT
1641/* Helper to look for __init__.py or __init__.py[co] in potential package */
1642static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001643find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001644{
Tim Peters0f9431f2001-07-05 03:47:53 +00001645 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001646 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001647 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001648 struct stat statbuf;
1649
Tim Peters0f9431f2001-07-05 03:47:53 +00001650/* For calling case_ok(buf, len, namelen, name):
1651 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1652 * ^ ^ ^ ^
1653 * |--------------------- buf ---------------------|
1654 * |------------------- len ------------------|
1655 * |------ name -------|
1656 * |----- namelen -----|
1657 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001658 if (save_len + 13 >= MAXPATHLEN)
1659 return 0;
1660 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001661 pname = buf + i;
1662 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001663 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001664 if (case_ok(buf,
1665 save_len + 9, /* len("/__init__") */
1666 8, /* len("__init__") */
1667 pname)) {
1668 buf[save_len] = '\0';
1669 return 1;
1670 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001671 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001672 i += strlen(pname);
1673 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001674 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001675 if (case_ok(buf,
1676 save_len + 9, /* len("/__init__") */
1677 8, /* len("__init__") */
1678 pname)) {
1679 buf[save_len] = '\0';
1680 return 1;
1681 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001682 }
1683 buf[save_len] = '\0';
1684 return 0;
1685}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001686
Guido van Rossum197346f1997-10-31 18:38:52 +00001687#endif /* HAVE_STAT */
1688
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001689
Tim Petersdbd9ba62000-07-09 03:09:57 +00001690static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001691
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001692/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001693 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001694
Guido van Rossum79f25d91997-04-29 20:08:16 +00001695static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001696load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001697{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001698 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001699 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001700 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001701
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001702 /* First check that there's an open file (if we need one) */
1703 switch (type) {
1704 case PY_SOURCE:
1705 case PY_COMPILED:
1706 if (fp == NULL) {
1707 PyErr_Format(PyExc_ValueError,
1708 "file object required for import (type code %d)",
1709 type);
1710 return NULL;
1711 }
1712 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001713
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001714 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001715
1716 case PY_SOURCE:
1717 m = load_source_module(name, buf, fp);
1718 break;
1719
1720 case PY_COMPILED:
1721 m = load_compiled_module(name, buf, fp);
1722 break;
1723
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001724#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001725 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001726 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001727 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001728#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001729
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001730 case PKG_DIRECTORY:
1731 m = load_package(name, buf);
1732 break;
1733
1734 case C_BUILTIN:
1735 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001736 if (buf != NULL && buf[0] != '\0')
1737 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001738 if (type == C_BUILTIN)
1739 err = init_builtin(name);
1740 else
1741 err = PyImport_ImportFrozenModule(name);
1742 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001743 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001744 if (err == 0) {
1745 PyErr_Format(PyExc_ImportError,
1746 "Purported %s module %.200s not found",
1747 type == C_BUILTIN ?
1748 "builtin" : "frozen",
1749 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001750 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001751 }
1752 modules = PyImport_GetModuleDict();
1753 m = PyDict_GetItemString(modules, name);
1754 if (m == NULL) {
1755 PyErr_Format(
1756 PyExc_ImportError,
1757 "%s module %.200s not properly initialized",
1758 type == C_BUILTIN ?
1759 "builtin" : "frozen",
1760 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001761 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001762 }
1763 Py_INCREF(m);
1764 break;
1765
Just van Rossum52e14d62002-12-30 22:08:05 +00001766 case IMP_HOOK: {
1767 if (loader == NULL) {
1768 PyErr_SetString(PyExc_ImportError,
1769 "import hook without loader");
1770 return NULL;
1771 }
1772 m = PyObject_CallMethod(loader, "load_module", "s", name);
1773 break;
1774 }
1775
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001777 PyErr_Format(PyExc_ImportError,
1778 "Don't know how to import %.200s (type code %d)",
1779 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001780 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001781
1782 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001783
1784 return m;
1785}
1786
1787
1788/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001789 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001790 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001791
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001792static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001793init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001794{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001795 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001796
Greg Ward201baee2001-10-04 14:52:06 +00001797 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001798 return 1;
1799
Guido van Rossum771c6c81997-10-31 18:37:24 +00001800 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001801 if (strcmp(name, p->name) == 0) {
1802 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001803 PyErr_Format(PyExc_ImportError,
1804 "Cannot re-init internal module %.200s",
1805 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001806 return -1;
1807 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001808 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001809 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001810 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001811 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001812 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001813 if (_PyImport_FixupExtension(name, name) == NULL)
1814 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001815 return 1;
1816 }
1817 }
1818 return 0;
1819}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001820
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001821
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001822/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001823
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001824static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001825find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001826{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001827 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001828
Guido van Rossum79f25d91997-04-29 20:08:16 +00001829 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001830 if (p->name == NULL)
1831 return NULL;
1832 if (strcmp(p->name, name) == 0)
1833 break;
1834 }
1835 return p;
1836}
1837
Guido van Rossum79f25d91997-04-29 20:08:16 +00001838static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001839get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001840{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001841 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001842 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001843
1844 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001845 PyErr_Format(PyExc_ImportError,
1846 "No such frozen object named %.200s",
1847 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001848 return NULL;
1849 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001850 if (p->code == NULL) {
1851 PyErr_Format(PyExc_ImportError,
1852 "Excluded frozen object named %.200s",
1853 name);
1854 return NULL;
1855 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001856 size = p->size;
1857 if (size < 0)
1858 size = -size;
1859 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001860}
1861
1862/* Initialize a frozen module.
1863 Return 1 for succes, 0 if the module is not found, and -1 with
1864 an exception set if the initialization failed.
1865 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001866
1867int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001868PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001869{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001870 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001871 PyObject *co;
1872 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001873 int ispackage;
1874 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001875
1876 if (p == NULL)
1877 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001878 if (p->code == NULL) {
1879 PyErr_Format(PyExc_ImportError,
1880 "Excluded frozen object named %.200s",
1881 name);
1882 return -1;
1883 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001884 size = p->size;
1885 ispackage = (size < 0);
1886 if (ispackage)
1887 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001888 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001889 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001890 name, ispackage ? " package" : "");
1891 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001892 if (co == NULL)
1893 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001894 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001895 PyErr_Format(PyExc_TypeError,
1896 "frozen object %.200s is not a code object",
1897 name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001898 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001899 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001900 if (ispackage) {
1901 /* Set __path__ to the package name */
1902 PyObject *d, *s;
1903 int err;
1904 m = PyImport_AddModule(name);
1905 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001906 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001907 d = PyModule_GetDict(m);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001908 s = PyUnicode_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001909 if (s == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001910 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001911 err = PyDict_SetItemString(d, "__path__", s);
1912 Py_DECREF(s);
1913 if (err != 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001914 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001915 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001916 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001917 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001918 goto err_return;
1919 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001920 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001921 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001922err_return:
1923 Py_DECREF(co);
1924 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001925}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001926
1927
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001928/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001929 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001930
Guido van Rossum79f25d91997-04-29 20:08:16 +00001931PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001932PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001933{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001934 PyObject *pname;
1935 PyObject *result;
1936
Martin v. Löwis5b222132007-06-10 09:51:05 +00001937 pname = PyUnicode_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001938 if (pname == NULL)
1939 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001940 result = PyImport_Import(pname);
1941 Py_DECREF(pname);
1942 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001943}
1944
Christian Heimes072c0f12008-01-03 23:01:04 +00001945/* Import a module without blocking
1946 *
1947 * At first it tries to fetch the module from sys.modules. If the module was
1948 * never loaded before it loads it with PyImport_ImportModule() unless another
1949 * thread holds the import lock. In the latter case the function raises an
1950 * ImportError instead of blocking.
1951 *
1952 * Returns the module object with incremented ref count.
1953 */
1954PyObject *
1955PyImport_ImportModuleNoBlock(const char *name)
1956{
1957 PyObject *result;
1958 PyObject *modules;
1959 long me;
1960
1961 /* Try to get the module from sys.modules[name] */
1962 modules = PyImport_GetModuleDict();
1963 if (modules == NULL)
1964 return NULL;
1965
1966 result = PyDict_GetItemString(modules, name);
1967 if (result != NULL) {
1968 Py_INCREF(result);
1969 return result;
1970 }
1971 else {
1972 PyErr_Clear();
1973 }
1974
1975 /* check the import lock
1976 * me might be -1 but I ignore the error here, the lock function
1977 * takes care of the problem */
1978 me = PyThread_get_thread_ident();
1979 if (import_lock_thread == -1 || import_lock_thread == me) {
1980 /* no thread or me is holding the lock */
1981 return PyImport_ImportModule(name);
1982 }
1983 else {
1984 PyErr_Format(PyExc_ImportError,
1985 "Failed to import %.200s because the import lock"
1986 "is held by another thread.",
1987 name);
1988 return NULL;
1989 }
1990}
1991
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001992/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001993static PyObject *get_parent(PyObject *globals, char *buf,
1994 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001995static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001996 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001997static int mark_miss(char *name);
1998static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001999 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002000static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002001
2002/* The Magnum Opus of dotted-name import :-) */
2003
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002004static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002005import_module_level(char *name, PyObject *globals, PyObject *locals,
2006 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002007{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002008 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002009 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002010 PyObject *parent, *head, *next, *tail;
2011
Christian Heimes454f37b2008-01-10 00:10:02 +00002012 if (strchr(name, '/') != NULL
2013#ifdef MS_WINDOWS
2014 || strchr(name, '\\') != NULL
2015#endif
2016 ) {
2017 PyErr_SetString(PyExc_ImportError,
2018 "Import by filename is not supported.");
2019 return NULL;
2020 }
2021
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002022 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002023 if (parent == NULL)
2024 return NULL;
2025
2026 head = load_next(parent, Py_None, &name, buf, &buflen);
2027 if (head == NULL)
2028 return NULL;
2029
2030 tail = head;
2031 Py_INCREF(tail);
2032 while (name) {
2033 next = load_next(tail, tail, &name, buf, &buflen);
2034 Py_DECREF(tail);
2035 if (next == NULL) {
2036 Py_DECREF(head);
2037 return NULL;
2038 }
2039 tail = next;
2040 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002041 if (tail == Py_None) {
2042 /* If tail is Py_None, both get_parent and load_next found
2043 an empty module name: someone called __import__("") or
2044 doctored faulty bytecode */
2045 Py_DECREF(tail);
2046 Py_DECREF(head);
2047 PyErr_SetString(PyExc_ValueError,
2048 "Empty module name");
2049 return NULL;
2050 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002051
2052 if (fromlist != NULL) {
2053 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2054 fromlist = NULL;
2055 }
2056
2057 if (fromlist == NULL) {
2058 Py_DECREF(tail);
2059 return head;
2060 }
2061
2062 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002063 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002064 Py_DECREF(tail);
2065 return NULL;
2066 }
2067
2068 return tail;
2069}
2070
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002071PyObject *
2072PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2073 PyObject *fromlist, int level)
2074{
2075 PyObject *result;
2076 lock_import();
2077 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002078 if (unlock_import() < 0) {
2079 Py_XDECREF(result);
2080 PyErr_SetString(PyExc_RuntimeError,
2081 "not holding the import lock");
2082 return NULL;
2083 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002084 return result;
2085}
2086
Fred Drake87590902004-05-28 20:21:36 +00002087/* Return the package that an import is being performed in. If globals comes
2088 from the module foo.bar.bat (not itself a package), this returns the
2089 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002090 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002091
2092 The *name* of the returned package is returned in buf, with the length of
2093 the name in *p_buflen.
2094
2095 If globals doesn't come from a package or a module in a package, or a
2096 corresponding entry is not found in sys.modules, Py_None is returned.
2097*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002098static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002099get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002100{
2101 static PyObject *namestr = NULL;
2102 static PyObject *pathstr = NULL;
Nick Coghlande10c852007-12-04 12:22:52 +00002103 static PyObject *pkgstr = NULL;
2104 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002105
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002106 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002107 return Py_None;
2108
2109 if (namestr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002110 namestr = PyUnicode_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002111 if (namestr == NULL)
2112 return NULL;
2113 }
2114 if (pathstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002115 pathstr = PyUnicode_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002116 if (pathstr == NULL)
2117 return NULL;
2118 }
Nick Coghlande10c852007-12-04 12:22:52 +00002119 if (pkgstr == NULL) {
2120 pkgstr = PyUnicode_InternFromString("__package__");
2121 if (pkgstr == NULL)
2122 return NULL;
2123 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002124
2125 *buf = '\0';
2126 *p_buflen = 0;
Nick Coghlande10c852007-12-04 12:22:52 +00002127 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002128
Nick Coghlande10c852007-12-04 12:22:52 +00002129 if ((pkgname != NULL) && (pkgname != Py_None)) {
2130 /* __package__ is set, so use it */
2131 Py_ssize_t len;
2132 if (!PyUnicode_Check(pkgname)) {
2133 PyErr_SetString(PyExc_ValueError,
2134 "__package__ set to non-string");
2135 return NULL;
2136 }
2137 len = PyUnicode_GET_SIZE(pkgname);
2138 if (len == 0) {
2139 if (level > 0) {
2140 PyErr_SetString(PyExc_ValueError,
2141 "Attempted relative import in non-package");
2142 return NULL;
2143 }
2144 return Py_None;
2145 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002146 if (len > MAXPATHLEN) {
2147 PyErr_SetString(PyExc_ValueError,
Nick Coghlande10c852007-12-04 12:22:52 +00002148 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002149 return NULL;
2150 }
Nick Coghlande10c852007-12-04 12:22:52 +00002151 strcpy(buf, PyUnicode_AsString(pkgname));
2152 } else {
2153 /* __package__ not set, so figure it out and set it */
2154 modname = PyDict_GetItem(globals, namestr);
2155 if (modname == NULL || !PyUnicode_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002156 return Py_None;
Nick Coghlande10c852007-12-04 12:22:52 +00002157
2158 modpath = PyDict_GetItem(globals, pathstr);
2159 if (modpath != NULL) {
2160 /* __path__ is set, so modname is already the package name */
2161 Py_ssize_t len = PyUnicode_GET_SIZE(modname);
2162 int error;
2163 if (len > MAXPATHLEN) {
2164 PyErr_SetString(PyExc_ValueError,
2165 "Module name too long");
2166 return NULL;
2167 }
2168 strcpy(buf, PyUnicode_AsString(modname));
2169 error = PyDict_SetItem(globals, pkgstr, modname);
2170 if (error) {
2171 PyErr_SetString(PyExc_ValueError,
2172 "Could not set __package__");
2173 return NULL;
2174 }
2175 } else {
2176 /* Normal module, so work out the package name if any */
2177 char *start = PyUnicode_AsString(modname);
2178 char *lastdot = strrchr(start, '.');
2179 size_t len;
2180 int error;
2181 if (lastdot == NULL && level > 0) {
2182 PyErr_SetString(PyExc_ValueError,
2183 "Attempted relative import in non-package");
2184 return NULL;
2185 }
2186 if (lastdot == NULL) {
2187 error = PyDict_SetItem(globals, pkgstr, Py_None);
2188 if (error) {
2189 PyErr_SetString(PyExc_ValueError,
2190 "Could not set __package__");
2191 return NULL;
2192 }
2193 return Py_None;
2194 }
2195 len = lastdot - start;
2196 if (len >= MAXPATHLEN) {
2197 PyErr_SetString(PyExc_ValueError,
2198 "Module name too long");
2199 return NULL;
2200 }
2201 strncpy(buf, start, len);
2202 buf[len] = '\0';
2203 pkgname = PyUnicode_FromString(buf);
2204 if (pkgname == NULL) {
2205 return NULL;
2206 }
2207 error = PyDict_SetItem(globals, pkgstr, pkgname);
2208 Py_DECREF(pkgname);
2209 if (error) {
2210 PyErr_SetString(PyExc_ValueError,
2211 "Could not set __package__");
2212 return NULL;
2213 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002214 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002215 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002216 while (--level > 0) {
2217 char *dot = strrchr(buf, '.');
2218 if (dot == NULL) {
2219 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002220 "Attempted relative import beyond "
2221 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002222 return NULL;
2223 }
2224 *dot = '\0';
2225 }
2226 *p_buflen = strlen(buf);
2227
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002228 modules = PyImport_GetModuleDict();
2229 parent = PyDict_GetItemString(modules, buf);
2230 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002231 PyErr_Format(PyExc_SystemError,
2232 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002233 return parent;
2234 /* We expect, but can't guarantee, if parent != None, that:
2235 - parent.__name__ == buf
2236 - parent.__dict__ is globals
2237 If this is violated... Who cares? */
2238}
2239
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002240/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002241static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002242load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002244{
2245 char *name = *p_name;
2246 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002247 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002248 char *p;
2249 PyObject *result;
2250
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002251 if (strlen(name) == 0) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002252 /* completely empty module name should only happen in
2253 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002254 Py_INCREF(mod);
2255 *p_name = NULL;
2256 return mod;
2257 }
2258
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002259 if (dot == NULL) {
2260 *p_name = NULL;
2261 len = strlen(name);
2262 }
2263 else {
2264 *p_name = dot+1;
2265 len = dot-name;
2266 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002267 if (len == 0) {
2268 PyErr_SetString(PyExc_ValueError,
2269 "Empty module name");
2270 return NULL;
2271 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002272
2273 p = buf + *p_buflen;
2274 if (p != buf)
2275 *p++ = '.';
2276 if (p+len-buf >= MAXPATHLEN) {
2277 PyErr_SetString(PyExc_ValueError,
2278 "Module name too long");
2279 return NULL;
2280 }
2281 strncpy(p, name, len);
2282 p[len] = '\0';
2283 *p_buflen = p+len-buf;
2284
2285 result = import_submodule(mod, p, buf);
2286 if (result == Py_None && altmod != mod) {
2287 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002288 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002289 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002290 if (result != NULL && result != Py_None) {
2291 if (mark_miss(buf) != 0) {
2292 Py_DECREF(result);
2293 return NULL;
2294 }
2295 strncpy(buf, name, len);
2296 buf[len] = '\0';
2297 *p_buflen = len;
2298 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002299 }
2300 if (result == NULL)
2301 return NULL;
2302
2303 if (result == Py_None) {
2304 Py_DECREF(result);
2305 PyErr_Format(PyExc_ImportError,
2306 "No module named %.200s", name);
2307 return NULL;
2308 }
2309
2310 return result;
2311}
2312
2313static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002314mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002315{
2316 PyObject *modules = PyImport_GetModuleDict();
2317 return PyDict_SetItemString(modules, name, Py_None);
2318}
2319
2320static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002321ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002322 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002323{
2324 int i;
2325
2326 if (!PyObject_HasAttrString(mod, "__path__"))
2327 return 1;
2328
2329 for (i = 0; ; i++) {
2330 PyObject *item = PySequence_GetItem(fromlist, i);
2331 int hasit;
2332 if (item == NULL) {
2333 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2334 PyErr_Clear();
2335 return 1;
2336 }
2337 return 0;
2338 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002339 if (!PyUnicode_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002340 PyErr_SetString(PyExc_TypeError,
Neal Norwitz80e7f272007-08-26 06:45:23 +00002341 "Item in ``from list'' not a string");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002342 Py_DECREF(item);
2343 return 0;
2344 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002345 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002346 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002347 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002348 /* See if the package defines __all__ */
2349 if (recursive)
2350 continue; /* Avoid endless recursion */
2351 all = PyObject_GetAttrString(mod, "__all__");
2352 if (all == NULL)
2353 PyErr_Clear();
2354 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002355 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002356 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002357 if (!ret)
2358 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002359 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002360 continue;
2361 }
2362 hasit = PyObject_HasAttr(mod, item);
2363 if (!hasit) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002364 PyObject *item8;
2365 char *subname;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002366 PyObject *submod;
2367 char *p;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002368 if (!Py_FileSystemDefaultEncoding) {
2369 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2370 PyUnicode_GetSize(item),
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002371 NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002372 } else {
Guido van Rossum98297ee2007-11-06 21:34:58 +00002373 item8 = PyUnicode_AsEncodedString(item,
2374 Py_FileSystemDefaultEncoding, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002375 }
2376 if (!item8) {
2377 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2378 return 0;
2379 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002380 subname = PyString_AS_STRING(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002381 if (buflen + strlen(subname) >= MAXPATHLEN) {
2382 PyErr_SetString(PyExc_ValueError,
2383 "Module name too long");
2384 Py_DECREF(item);
2385 return 0;
2386 }
2387 p = buf + buflen;
2388 *p++ = '.';
2389 strcpy(p, subname);
2390 submod = import_submodule(mod, subname, buf);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002391 Py_DECREF(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002392 Py_XDECREF(submod);
2393 if (submod == NULL) {
2394 Py_DECREF(item);
2395 return 0;
2396 }
2397 }
2398 Py_DECREF(item);
2399 }
2400
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002401 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002402}
2403
Neil Schemenauer00b09662003-06-16 21:03:07 +00002404static int
2405add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2406 PyObject *modules)
2407{
2408 if (mod == Py_None)
2409 return 1;
2410 /* Irrespective of the success of this load, make a
2411 reference to it in the parent package module. A copy gets
2412 saved in the modules dictionary under the full name, so get a
2413 reference from there, if need be. (The exception is when the
2414 load failed with a SyntaxError -- then there's no trace in
2415 sys.modules. In that case, of course, do nothing extra.) */
2416 if (submod == NULL) {
2417 submod = PyDict_GetItemString(modules, fullname);
2418 if (submod == NULL)
2419 return 1;
2420 }
2421 if (PyModule_Check(mod)) {
2422 /* We can't use setattr here since it can give a
2423 * spurious warning if the submodule name shadows a
2424 * builtin name */
2425 PyObject *dict = PyModule_GetDict(mod);
2426 if (!dict)
2427 return 0;
2428 if (PyDict_SetItemString(dict, subname, submod) < 0)
2429 return 0;
2430 }
2431 else {
2432 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2433 return 0;
2434 }
2435 return 1;
2436}
2437
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002438static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002439import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002440{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002441 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002442 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002443
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002444 /* Require:
2445 if mod == None: subname == fullname
2446 else: mod.__name__ + "." + subname == fullname
2447 */
2448
Tim Peters50d8d372001-02-28 05:34:27 +00002449 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002450 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002451 }
2452 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002453 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002454 char buf[MAXPATHLEN+1];
2455 struct filedescr *fdp;
2456 FILE *fp = NULL;
2457
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002458 if (mod == Py_None)
2459 path = NULL;
2460 else {
2461 path = PyObject_GetAttrString(mod, "__path__");
2462 if (path == NULL) {
2463 PyErr_Clear();
2464 Py_INCREF(Py_None);
2465 return Py_None;
2466 }
2467 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002468
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002469 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002470 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2471 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002472 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473 if (fdp == NULL) {
2474 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2475 return NULL;
2476 PyErr_Clear();
2477 Py_INCREF(Py_None);
2478 return Py_None;
2479 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002480 m = load_module(fullname, fp, buf, fdp->type, loader);
2481 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002482 if (fp)
2483 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002484 if (!add_submodule(mod, m, fullname, subname, modules)) {
2485 Py_XDECREF(m);
2486 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002487 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002488 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002489
2490 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002491}
2492
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002493
2494/* Re-import a module of any kind and return its module object, WITH
2495 INCREMENTED REFERENCE COUNT */
2496
Guido van Rossum79f25d91997-04-29 20:08:16 +00002497PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002498PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002499{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002500 PyInterpreterState *interp = PyThreadState_Get()->interp;
2501 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002502 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumd8faa362007-04-27 19:54:29 +00002503 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002504 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002505 char buf[MAXPATHLEN+1];
2506 struct filedescr *fdp;
2507 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002508 PyObject *newm;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002509
2510 if (modules_reloading == NULL) {
2511 Py_FatalError("PyImport_ReloadModule: "
Guido van Rossume7ba4952007-06-06 23:52:48 +00002512 "no modules_reloading dictionary!");
Guido van Rossumd8faa362007-04-27 19:54:29 +00002513 return NULL;
2514 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002515
Guido van Rossum79f25d91997-04-29 20:08:16 +00002516 if (m == NULL || !PyModule_Check(m)) {
2517 PyErr_SetString(PyExc_TypeError,
2518 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002519 return NULL;
2520 }
Neal Norwitz5616c6d2007-08-26 05:32:41 +00002521 name = (char*)PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002522 if (name == NULL)
2523 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002524 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002525 PyErr_Format(PyExc_ImportError,
2526 "reload(): module %.200s not in sys.modules",
2527 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002528 return NULL;
2529 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002530 existing_m = PyDict_GetItemString(modules_reloading, name);
2531 if (existing_m != NULL) {
2532 /* Due to a recursive reload, this module is already
2533 being reloaded. */
2534 Py_INCREF(existing_m);
2535 return existing_m;
2536 }
2537 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2538 return NULL;
2539
Guido van Rossum222ef561997-09-06 19:41:09 +00002540 subname = strrchr(name, '.');
2541 if (subname == NULL)
2542 subname = name;
2543 else {
2544 PyObject *parentname, *parent;
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002545 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002546 if (parentname == NULL) {
2547 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002548 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002549 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002550 parent = PyDict_GetItem(modules, parentname);
2551 if (parent == NULL) {
2552 PyErr_Format(PyExc_ImportError,
2553 "reload(): parent %.200s not in sys.modules",
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002554 PyUnicode_AsString(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002555 Py_DECREF(parentname);
Guido van Rossume7ba4952007-06-06 23:52:48 +00002556 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002557 return NULL;
2558 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002559 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002560 subname++;
2561 path = PyObject_GetAttrString(parent, "__path__");
2562 if (path == NULL)
2563 PyErr_Clear();
2564 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002565 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002566 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002567 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002568
2569 if (fdp == NULL) {
2570 Py_XDECREF(loader);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002571 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002572 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002573 }
2574
2575 newm = load_module(name, fp, buf, fdp->type, loader);
2576 Py_XDECREF(loader);
2577
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002578 if (fp)
2579 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002580 if (newm == NULL) {
2581 /* load_module probably removed name from modules because of
2582 * the error. Put back the original module object. We're
2583 * going to return NULL in this case regardless of whether
2584 * replacing name succeeds, so the return value is ignored.
2585 */
2586 PyDict_SetItemString(modules, name, m);
2587 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002588 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002589 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002590}
2591
2592
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002593/* Higher-level import emulator which emulates the "import" statement
2594 more accurately -- it invokes the __import__() function from the
2595 builtins of the current globals. This means that the import is
2596 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002597 environment, e.g. by "rexec".
2598 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002599 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002600 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002601
2602PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002603PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002604{
2605 static PyObject *silly_list = NULL;
2606 static PyObject *builtins_str = NULL;
2607 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002608 PyObject *globals = NULL;
2609 PyObject *import = NULL;
2610 PyObject *builtins = NULL;
2611 PyObject *r = NULL;
2612
2613 /* Initialize constant string objects */
2614 if (silly_list == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002615 import_str = PyUnicode_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002616 if (import_str == NULL)
2617 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002618 builtins_str = PyUnicode_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002619 if (builtins_str == NULL)
2620 return NULL;
2621 silly_list = Py_BuildValue("[s]", "__doc__");
2622 if (silly_list == NULL)
2623 return NULL;
2624 }
2625
2626 /* Get the builtins from current globals */
2627 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002628 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002629 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002630 builtins = PyObject_GetItem(globals, builtins_str);
2631 if (builtins == NULL)
2632 goto err;
2633 }
2634 else {
2635 /* No globals -- use standard builtins, and fake globals */
2636 PyErr_Clear();
2637
Georg Brandl1a3284e2007-12-02 09:40:06 +00002638 builtins = PyImport_ImportModuleLevel("builtins",
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002639 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002640 if (builtins == NULL)
2641 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002642 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2643 if (globals == NULL)
2644 goto err;
2645 }
2646
2647 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002649 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 if (import == NULL)
2651 PyErr_SetObject(PyExc_KeyError, import_str);
2652 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002653 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002654 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002655 if (import == NULL)
2656 goto err;
2657
Christian Heimes072c0f12008-01-03 23:01:04 +00002658 /* Call the __import__ function with the proper argument list
2659 * Always use absolute import here. */
2660 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2661 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002662
2663 err:
2664 Py_XDECREF(globals);
2665 Py_XDECREF(builtins);
2666 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002667
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002668 return r;
2669}
2670
2671
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002672/* Module 'imp' provides Python access to the primitives used for
2673 importing modules.
2674*/
2675
Guido van Rossum79f25d91997-04-29 20:08:16 +00002676static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002677imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002678{
2679 char buf[4];
2680
Guido van Rossum96774c12000-05-01 20:19:08 +00002681 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2682 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2683 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2684 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002685
Guido van Rossumad8d3002007-08-03 18:40:49 +00002686 return PyBytes_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002687}
2688
Guido van Rossum79f25d91997-04-29 20:08:16 +00002689static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002690imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002691{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002692 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002693 struct filedescr *fdp;
2694
Guido van Rossum79f25d91997-04-29 20:08:16 +00002695 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002696 if (list == NULL)
2697 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002698 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2699 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002700 fdp->suffix, fdp->mode, fdp->type);
2701 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002702 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002703 return NULL;
2704 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002705 if (PyList_Append(list, item) < 0) {
2706 Py_DECREF(list);
2707 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002708 return NULL;
2709 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002710 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711 }
2712 return list;
2713}
2714
Guido van Rossum79f25d91997-04-29 20:08:16 +00002715static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002716call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002717{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002718 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002719 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002720 struct filedescr *fdp;
2721 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002722 FILE *fp = NULL;
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002723 int fd = -1;
Brett Cannon3bb42d92007-10-20 03:43:15 +00002724 char *found_encoding = NULL;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002725 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002726
2727 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002728 if (path == Py_None)
2729 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002730 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002731 if (fdp == NULL)
2732 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002733 if (fp != NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002734 fd = fileno(fp);
2735 if (fd != -1)
2736 fd = dup(fd);
2737 fclose(fp);
2738 fp = NULL;
2739 }
2740 if (fd != -1) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002741 if (strchr(fdp->mode, 'b') == NULL) {
Brett Cannon3bb42d92007-10-20 03:43:15 +00002742 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
2743 memory. */
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002744 found_encoding = PyTokenizer_FindEncoding(fd);
2745 lseek(fd, 0, 0); /* Reset position */
Brett Cannon3bb42d92007-10-20 03:43:15 +00002746 encoding = (found_encoding != NULL) ? found_encoding :
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002747 (char*)PyUnicode_GetDefaultEncoding();
2748 }
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002749 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00002750 (char*)encoding, NULL, NULL, 1);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002751 if (fob == NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002752 close(fd);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002753 PyMem_FREE(found_encoding);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002754 return NULL;
2755 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002756 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002757 else {
2758 fob = Py_None;
2759 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002760 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002761 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002762 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002763 Py_DECREF(fob);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002764 PyMem_FREE(found_encoding);
2765
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002766 return ret;
2767}
2768
Guido van Rossum79f25d91997-04-29 20:08:16 +00002769static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002770imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002771{
2772 char *name;
2773 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002774 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002775 return NULL;
2776 return call_find_module(name, path);
2777}
2778
2779static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002780imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002781{
2782 char *name;
2783 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002784 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002785 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002786 return NULL;
2787 ret = init_builtin(name);
2788 if (ret < 0)
2789 return NULL;
2790 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002791 Py_INCREF(Py_None);
2792 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002793 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002794 m = PyImport_AddModule(name);
2795 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002796 return m;
2797}
2798
Guido van Rossum79f25d91997-04-29 20:08:16 +00002799static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002800imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002801{
2802 char *name;
2803 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002804 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002805 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002806 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002807 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808 if (ret < 0)
2809 return NULL;
2810 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002811 Py_INCREF(Py_None);
2812 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002813 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002814 m = PyImport_AddModule(name);
2815 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002816 return m;
2817}
2818
Guido van Rossum79f25d91997-04-29 20:08:16 +00002819static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002820imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002821{
2822 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002823
Guido van Rossum43713e52000-02-29 13:59:29 +00002824 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002825 return NULL;
2826 return get_frozen_object(name);
2827}
2828
Guido van Rossum79f25d91997-04-29 20:08:16 +00002829static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002830imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002831{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002832 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002833 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002834 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00002835 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002836}
2837
Guido van Rossum79f25d91997-04-29 20:08:16 +00002838static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002839imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002840{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002841 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002842 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002843 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002844 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002845 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002846 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002847}
2848
2849static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002850get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002851{
2852 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002853 if (mode[0] == 'U')
2854 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002855 if (fob == NULL) {
2856 fp = fopen(pathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002857 }
2858 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002859 int fd = PyObject_AsFileDescriptor(fob);
2860 if (fd == -1)
2861 return NULL;
2862 /* XXX This will leak a FILE struct. Fix this!!!!
2863 (But it doesn't leak a file descrioptor!) */
2864 fp = fdopen(fd, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002865 }
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002866 if (fp == NULL)
2867 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002868 return fp;
2869}
2870
Guido van Rossum79f25d91997-04-29 20:08:16 +00002871static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002872imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002873{
2874 char *name;
2875 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002876 PyObject *fob = NULL;
2877 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002878 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002879 if (!PyArg_ParseTuple(args, "ss|O:load_compiled",
2880 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002881 return NULL;
2882 fp = get_file(pathname, fob, "rb");
2883 if (fp == NULL)
2884 return NULL;
2885 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002886 if (fob == NULL)
2887 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002888 return m;
2889}
2890
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002891#ifdef HAVE_DYNAMIC_LOADING
2892
Guido van Rossum79f25d91997-04-29 20:08:16 +00002893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002894imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002895{
2896 char *name;
2897 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002898 PyObject *fob = NULL;
2899 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002900 FILE *fp = NULL;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002901 if (!PyArg_ParseTuple(args, "ss|O:load_dynamic",
2902 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002903 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002904 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002905 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002906 if (fp == NULL)
2907 return NULL;
2908 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002909 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002910 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002911}
2912
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002913#endif /* HAVE_DYNAMIC_LOADING */
2914
Guido van Rossum79f25d91997-04-29 20:08:16 +00002915static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002916imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002917{
2918 char *name;
2919 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002920 PyObject *fob = NULL;
2921 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002922 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002923 if (!PyArg_ParseTuple(args, "ss|O:load_source",
2924 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002925 return NULL;
2926 fp = get_file(pathname, fob, "r");
2927 if (fp == NULL)
2928 return NULL;
2929 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002930 if (fob == NULL)
2931 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002932 return m;
2933}
2934
Guido van Rossum79f25d91997-04-29 20:08:16 +00002935static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002936imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002937{
2938 char *name;
2939 PyObject *fob;
2940 char *pathname;
2941 char *suffix; /* Unused */
2942 char *mode;
2943 int type;
2944 FILE *fp;
2945
Guido van Rossum43713e52000-02-29 13:59:29 +00002946 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002947 &name, &fob, &pathname,
2948 &suffix, &mode, &type))
2949 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002950 if (*mode) {
2951 /* Mode must start with 'r' or 'U' and must not contain '+'.
2952 Implicit in this test is the assumption that the mode
2953 may contain other modifiers like 'b' or 't'. */
2954
2955 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002956 PyErr_Format(PyExc_ValueError,
2957 "invalid file open mode %.200s", mode);
2958 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002959 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002960 }
2961 if (fob == Py_None)
2962 fp = NULL;
2963 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002964 fp = get_file(NULL, fob, mode);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002965 if (fp == NULL)
2966 return NULL;
2967 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002968 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002969}
2970
2971static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002972imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002973{
2974 char *name;
2975 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002976 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002977 return NULL;
2978 return load_package(name, pathname);
2979}
2980
2981static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002982imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002983{
2984 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002985 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002986 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002987 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002988}
2989
Christian Heimes13a7a212008-01-07 17:13:09 +00002990static PyObject *
2991imp_reload(PyObject *self, PyObject *v)
2992{
2993 return PyImport_ReloadModule(v);
2994}
2995
2996PyDoc_STRVAR(doc_reload,
2997"reload(module) -> module\n\
2998\n\
2999Reload the module. The module must have been successfully imported before.");
3000
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003001/* Doc strings */
3002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003003PyDoc_STRVAR(doc_imp,
3004"This module provides the components needed to build your own\n\
3005__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003007PyDoc_STRVAR(doc_find_module,
3008"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003009Search for a module. If path is omitted or None, search for a\n\
3010built-in, frozen or special module and continue search in sys.path.\n\
3011The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003012package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003014PyDoc_STRVAR(doc_load_module,
3015"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003016Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003017The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003019PyDoc_STRVAR(doc_get_magic,
3020"get_magic() -> string\n\
3021Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003023PyDoc_STRVAR(doc_get_suffixes,
3024"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003025Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003026that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003028PyDoc_STRVAR(doc_new_module,
3029"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003030Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003031The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003032
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003033PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003034"lock_held() -> boolean\n\
3035Return True if the import lock is currently held, else False.\n\
3036On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003037
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003038PyDoc_STRVAR(doc_acquire_lock,
3039"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003040Acquires the interpreter's import lock for the current thread.\n\
3041This lock should be used by import hooks to ensure thread-safety\n\
3042when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003043On platforms without threads, this function does nothing.");
3044
3045PyDoc_STRVAR(doc_release_lock,
3046"release_lock() -> None\n\
3047Release the interpreter's import lock.\n\
3048On platforms without threads, this function does nothing.");
3049
Guido van Rossum79f25d91997-04-29 20:08:16 +00003050static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003051 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3052 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3053 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3054 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3055 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3056 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3057 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3058 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Christian Heimes13a7a212008-01-07 17:13:09 +00003059 {"reload", imp_reload, METH_O, doc_reload},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003060 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003061 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3062 {"init_builtin", imp_init_builtin, METH_VARARGS},
3063 {"init_frozen", imp_init_frozen, METH_VARARGS},
3064 {"is_builtin", imp_is_builtin, METH_VARARGS},
3065 {"is_frozen", imp_is_frozen, METH_VARARGS},
3066 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003067#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003068 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003069#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003070 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003071 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003072 {NULL, NULL} /* sentinel */
3073};
3074
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003075static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003076setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003077{
3078 PyObject *v;
3079 int err;
3080
Christian Heimes217cfd12007-12-02 14:31:20 +00003081 v = PyLong_FromLong((long)value);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003082 err = PyDict_SetItemString(d, name, v);
3083 Py_XDECREF(v);
3084 return err;
3085}
3086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003087typedef struct {
3088 PyObject_HEAD
3089} NullImporter;
3090
3091static int
3092NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3093{
3094 char *path;
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003095 Py_ssize_t pathlen;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003096
3097 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3098 return -1;
3099
3100 if (!PyArg_ParseTuple(args, "s:NullImporter",
3101 &path))
3102 return -1;
3103
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003104 pathlen = strlen(path);
3105 if (pathlen == 0) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003106 PyErr_SetString(PyExc_ImportError, "empty pathname");
3107 return -1;
3108 } else {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003109 struct stat statbuf;
3110 int rv;
3111
3112 rv = stat(path, &statbuf);
Guido van Rossumc1bdbc32007-11-07 17:46:34 +00003113#ifdef MS_WINDOWS
3114 /* MS Windows stat() chokes on paths like C:\path\. Try to
3115 * recover *one* time by stripping off a trailing slash or
3116 * backslash. http://bugs.python.org/issue1293
3117 */
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003118 if (rv != 0 && pathlen <= MAXPATHLEN &&
3119 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3120 char mangled[MAXPATHLEN+1];
3121
3122 strcpy(mangled, path);
3123 mangled[pathlen-1] = '\0';
3124 rv = stat(mangled, &statbuf);
3125 }
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003126#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003127 if (rv == 0) {
3128 /* it exists */
3129 if (S_ISDIR(statbuf.st_mode)) {
3130 /* it's a directory */
3131 PyErr_SetString(PyExc_ImportError,
3132 "existing directory");
3133 return -1;
3134 }
3135 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003136 }
3137 return 0;
3138}
3139
3140static PyObject *
3141NullImporter_find_module(NullImporter *self, PyObject *args)
3142{
3143 Py_RETURN_NONE;
3144}
3145
3146static PyMethodDef NullImporter_methods[] = {
3147 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3148 "Always return None"
3149 },
3150 {NULL} /* Sentinel */
3151};
3152
3153
Christian Heimes9cd17752007-11-18 19:35:23 +00003154PyTypeObject PyNullImporter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003155 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003156 "imp.NullImporter", /*tp_name*/
3157 sizeof(NullImporter), /*tp_basicsize*/
3158 0, /*tp_itemsize*/
3159 0, /*tp_dealloc*/
3160 0, /*tp_print*/
3161 0, /*tp_getattr*/
3162 0, /*tp_setattr*/
3163 0, /*tp_compare*/
3164 0, /*tp_repr*/
3165 0, /*tp_as_number*/
3166 0, /*tp_as_sequence*/
3167 0, /*tp_as_mapping*/
3168 0, /*tp_hash */
3169 0, /*tp_call*/
3170 0, /*tp_str*/
3171 0, /*tp_getattro*/
3172 0, /*tp_setattro*/
3173 0, /*tp_as_buffer*/
3174 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3175 "Null importer object", /* tp_doc */
3176 0, /* tp_traverse */
3177 0, /* tp_clear */
3178 0, /* tp_richcompare */
3179 0, /* tp_weaklistoffset */
3180 0, /* tp_iter */
3181 0, /* tp_iternext */
3182 NullImporter_methods, /* tp_methods */
3183 0, /* tp_members */
3184 0, /* tp_getset */
3185 0, /* tp_base */
3186 0, /* tp_dict */
3187 0, /* tp_descr_get */
3188 0, /* tp_descr_set */
3189 0, /* tp_dictoffset */
3190 (initproc)NullImporter_init, /* tp_init */
3191 0, /* tp_alloc */
3192 PyType_GenericNew /* tp_new */
3193};
3194
3195
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003196PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003197initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003198{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003199 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003200
Christian Heimes9cd17752007-11-18 19:35:23 +00003201 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003202 goto failure;
3203
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003204 m = Py_InitModule4("imp", imp_methods, doc_imp,
3205 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003206 if (m == NULL)
3207 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003208 d = PyModule_GetDict(m);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003209 if (d == NULL)
3210 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003211
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003212 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3213 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3214 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3215 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3216 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3217 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3218 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3219 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003220 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003221 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003222
Christian Heimes9cd17752007-11-18 19:35:23 +00003223 Py_INCREF(&PyNullImporter_Type);
3224 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003225 failure:
3226 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003227}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003228
3229
Guido van Rossumb18618d2000-05-03 23:44:39 +00003230/* API for embedding applications that want to add their own entries
3231 to the table of built-in modules. This should normally be called
3232 *before* Py_Initialize(). When the table resize fails, -1 is
3233 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003234
3235 After a similar function by Just van Rossum. */
3236
3237int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003238PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003239{
3240 static struct _inittab *our_copy = NULL;
3241 struct _inittab *p;
3242 int i, n;
3243
3244 /* Count the number of entries in both tables */
3245 for (n = 0; newtab[n].name != NULL; n++)
3246 ;
3247 if (n == 0)
3248 return 0; /* Nothing to do */
3249 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3250 ;
3251
3252 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003253 p = our_copy;
3254 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003255 if (p == NULL)
3256 return -1;
3257
3258 /* Copy the tables into the new memory */
3259 if (our_copy != PyImport_Inittab)
3260 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3261 PyImport_Inittab = our_copy = p;
3262 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3263
3264 return 0;
3265}
3266
3267/* Shorthand to add a single entry given a name and a function */
3268
3269int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003270PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003271{
3272 struct _inittab newtab[2];
3273
3274 memset(newtab, '\0', sizeof newtab);
3275
3276 newtab[0].name = name;
3277 newtab[0].initfunc = initfunc;
3278
3279 return PyImport_ExtendInittab(newtab);
3280}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003281
3282#ifdef __cplusplus
3283}
3284#endif