blob: b00986c697857dda6c11cfbe8bb4a8fb0846aac1 [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"
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +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
Anthony Baxterac6bd462006-04-13 02:06:09 +000021#ifdef __cplusplus
22extern "C" {
23#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimes5e8e6d22008-02-23 23:59:45 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
28#endif
29
Guido van Rossum21d335e1993-10-15 13:01:11 +000030
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000031/* Magic word to reject .pyc files generated by other Python versions.
32 It should change for each incompatible change to the bytecode.
33
34 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000035 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000036 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000038 The magic numbers must be spaced apart atleast 2 values, as the
39 -U interpeter flag will cause MAGIC+1 being used. They have been
40 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000041
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000042 There were a variety of old schemes for setting the magic number.
43 The current working scheme is to increment the previous value by
44 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000045
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000046 Known values:
47 Python 1.5: 20121
48 Python 1.5.1: 20121
49 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000050 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000051 Python 2.0: 50823
52 Python 2.0.1: 50823
53 Python 2.1: 60202
54 Python 2.1.1: 60202
55 Python 2.1.2: 60202
56 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000057 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000058 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000059 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000060 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000061 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000062 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000063 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000064 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000065 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000066 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Neal Norwitz0d62a062006-07-30 06:53:31 +000067 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
68 Python 2.5b3: 62111 (fix wrong code: x += yield)
Neal Norwitz9a70f952006-08-04 05:12:19 +000069 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
70 storing constants that should have been removed)
Neal Norwitzdac090d2006-09-05 03:53:08 +000071 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Raymond Hettingereffde122007-12-18 18:26:18 +000072 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Nick Coghlan7af53be2008-03-07 14:13:28 +000073 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Antoine Pitroud0c35152008-12-17 00:38:28 +000074 Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000075.
Tim Peters36515e22001-11-18 04:06:29 +000076*/
Antoine Pitroud0c35152008-12-17 00:38:28 +000077#define MAGIC (62171 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000078
Guido van Rossum96774c12000-05-01 20:19:08 +000079/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000080 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000081 compiler works which are enabled by command line switches. */
Christian Heimes61e45902008-03-27 10:35:52 +000082static long pyc_magic = MAGIC;
Guido van Rossum96774c12000-05-01 20:19:08 +000083
Guido van Rossum25ce5661997-08-02 03:10:38 +000084/* See _PyImport_FixupExtension() below */
85static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000086
Guido van Rossum771c6c81997-10-31 18:37:24 +000087/* This table is defined in config.c: */
88extern struct _inittab _PyImport_Inittab[];
89
90struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000091
Guido van Rossumed1170e1999-12-20 21:23:41 +000092/* these tables define the module suffixes that Python recognizes */
93struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000094
95#ifdef RISCOS
96static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000097 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000098 {"/pyc", "rb", PY_COMPILED},
99 {0, 0}
100};
101#else
Guido van Rossumed1170e1999-12-20 21:23:41 +0000102static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000103 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000104#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000105 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000106#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000107 {".pyc", "rb", PY_COMPILED},
108 {0, 0}
109};
Guido van Rossum48a680c2001-03-02 06:34:14 +0000110#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000111
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000112
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000113/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114
115void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000116_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000118 const struct filedescr *scan;
119 struct filedescr *filetab;
120 int countD = 0;
121 int countS = 0;
122
123 /* prepare _PyImport_Filetab: copy entries from
124 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
125 */
Georg Brandladd36e52007-08-23 18:08:06 +0000126#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000127 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
128 ++countD;
Georg Brandladd36e52007-08-23 18:08:06 +0000129#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000130 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
131 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000132 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Neal Norwitze1fdb322006-07-21 05:32:28 +0000133 if (filetab == NULL)
Neal Norwitz33722ae2006-07-21 07:59:02 +0000134 Py_FatalError("Can't initialize import file table.");
Georg Brandladd36e52007-08-23 18:08:06 +0000135#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000136 memcpy(filetab, _PyImport_DynLoadFiletab,
137 countD * sizeof(struct filedescr));
Georg Brandladd36e52007-08-23 18:08:06 +0000138#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000139 memcpy(filetab + countD, _PyImport_StandardFiletab,
140 countS * sizeof(struct filedescr));
141 filetab[countD + countS].suffix = NULL;
142
143 _PyImport_Filetab = filetab;
144
Guido van Rossum0824f631997-03-11 18:37:35 +0000145 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
147 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000148#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000149 if (strcmp(filetab->suffix, ".pyc") == 0)
150 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000151#else
152 if (strcmp(filetab->suffix, "/pyc") == 0)
153 filetab->suffix = "/pyo";
154#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000155 }
156 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000157
158 if (Py_UnicodeFlag) {
159 /* Fix the pyc_magic so that byte compiled code created
160 using the all-Unicode method doesn't interfere with
161 code created in normal operation mode. */
162 pyc_magic = MAGIC + 1;
163 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Guido van Rossum25ce5661997-08-02 03:10:38 +0000166void
Just van Rossum52e14d62002-12-30 22:08:05 +0000167_PyImportHooks_Init(void)
168{
169 PyObject *v, *path_hooks = NULL, *zimpimport;
170 int err = 0;
171
172 /* adding sys.path_hooks and sys.path_importer_cache, setting up
173 zipimport */
Nick Coghlan327a39b2007-11-18 11:56:28 +0000174 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000175 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000176
177 if (Py_VerboseFlag)
178 PySys_WriteStderr("# installing zipimport hook\n");
179
180 v = PyList_New(0);
181 if (v == NULL)
182 goto error;
183 err = PySys_SetObject("meta_path", v);
184 Py_DECREF(v);
185 if (err)
186 goto error;
187 v = PyDict_New();
188 if (v == NULL)
189 goto error;
190 err = PySys_SetObject("path_importer_cache", v);
191 Py_DECREF(v);
192 if (err)
193 goto error;
194 path_hooks = PyList_New(0);
195 if (path_hooks == NULL)
196 goto error;
197 err = PySys_SetObject("path_hooks", path_hooks);
198 if (err) {
199 error:
200 PyErr_Print();
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000201 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
202 "path_importer_cache, or NullImporter failed"
203 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000204 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000205
Just van Rossum52e14d62002-12-30 22:08:05 +0000206 zimpimport = PyImport_ImportModule("zipimport");
207 if (zimpimport == NULL) {
208 PyErr_Clear(); /* No zip import module -- okay */
209 if (Py_VerboseFlag)
210 PySys_WriteStderr("# can't import zipimport\n");
211 }
212 else {
213 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
214 "zipimporter");
215 Py_DECREF(zimpimport);
216 if (zipimporter == NULL) {
217 PyErr_Clear(); /* No zipimporter object -- okay */
218 if (Py_VerboseFlag)
219 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000220 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000221 }
222 else {
223 /* sys.path_hooks.append(zipimporter) */
224 err = PyList_Append(path_hooks, zipimporter);
225 Py_DECREF(zipimporter);
226 if (err)
227 goto error;
228 if (Py_VerboseFlag)
229 PySys_WriteStderr(
230 "# installed zipimport hook\n");
231 }
232 }
233 Py_DECREF(path_hooks);
234}
235
236void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000237_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238{
239 Py_XDECREF(extensions);
240 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000241 PyMem_DEL(_PyImport_Filetab);
242 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000243}
244
245
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000246/* Locking primitives to prevent parallel imports of the same module
247 in different threads to return with a partially loaded module.
248 These calls are serialized by the global interpreter lock. */
249
250#ifdef WITH_THREAD
251
Guido van Rossum49b56061998-10-01 20:42:43 +0000252#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000253
Guido van Rossum65d5b571998-12-21 19:32:43 +0000254static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255static long import_lock_thread = -1;
256static int import_lock_level = 0;
257
258static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000259lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000260{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000261 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000262 if (me == -1)
263 return; /* Too bad */
Neal Norwitze1fdb322006-07-21 05:32:28 +0000264 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000265 import_lock = PyThread_allocate_lock();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000266 if (import_lock == NULL)
267 return; /* Nothing much we can do. */
268 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269 if (import_lock_thread == me) {
270 import_lock_level++;
271 return;
272 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000273 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
274 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000275 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000276 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277 PyEval_RestoreThread(tstate);
278 }
279 import_lock_thread = me;
280 import_lock_level = 1;
281}
282
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000284unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000285{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000286 long me = PyThread_get_thread_ident();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000287 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000288 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000289 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000291 import_lock_level--;
292 if (import_lock_level == 0) {
293 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000294 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000295 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000296 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297}
298
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000299/* This function is called from PyOS_AfterFork to ensure that newly
300 created child processes do not share locks with the parent. */
301
302void
303_PyImport_ReInitLock(void)
304{
305#ifdef _AIX
306 if (import_lock != NULL)
307 import_lock = PyThread_allocate_lock();
308#endif
309}
310
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000311#else
312
313#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000314#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000315
316#endif
317
Tim Peters69232342001-08-30 05:16:13 +0000318static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000319imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000320{
Tim Peters69232342001-08-30 05:16:13 +0000321#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000322 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000323#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000324 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000325#endif
326}
327
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000328static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000329imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331#ifdef WITH_THREAD
332 lock_import();
333#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000334 Py_INCREF(Py_None);
335 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000336}
337
338static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000339imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000340{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000341#ifdef WITH_THREAD
342 if (unlock_import() < 0) {
343 PyErr_SetString(PyExc_RuntimeError,
344 "not holding the import lock");
345 return NULL;
346 }
347#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000348 Py_INCREF(Py_None);
349 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000350}
351
Collin Winter276887b2007-03-12 16:11:39 +0000352static void
Neal Norwitz75c7c802007-03-13 05:31:38 +0000353imp_modules_reloading_clear(void)
Collin Winter276887b2007-03-12 16:11:39 +0000354{
355 PyInterpreterState *interp = PyThreadState_Get()->interp;
Neal Norwitz75c7c802007-03-13 05:31:38 +0000356 if (interp->modules_reloading != NULL)
357 PyDict_Clear(interp->modules_reloading);
Collin Winter276887b2007-03-12 16:11:39 +0000358}
359
Guido van Rossum25ce5661997-08-02 03:10:38 +0000360/* Helper for sys */
361
362PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000363PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000365 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366 if (interp->modules == NULL)
367 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
368 return interp->modules;
369}
370
Guido van Rossum3f5da241990-12-20 15:06:42 +0000371
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000372/* List of names to clear in sys */
373static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000374 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375 "exc_type", "exc_value", "exc_traceback",
376 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000377 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes0d924432008-01-30 17:21:22 +0000378 /* misc stuff */
379 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000380 NULL
381};
382
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000383static char* sys_files[] = {
384 "stdin", "__stdin__",
385 "stdout", "__stdout__",
386 "stderr", "__stderr__",
387 NULL
388};
389
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000390
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000391/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000392
Guido van Rossum3f5da241990-12-20 15:06:42 +0000393void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000396 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000397 char *name;
398 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000399 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000400 PyObject *modules = interp->modules;
401
402 if (modules == NULL)
403 return; /* Already done */
404
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405 /* Delete some special variables first. These are common
406 places where user values hide and people complain when their
407 destructors fail. Since the modules containing them are
408 deleted *last* of all, they would come too late in the normal
409 destruction order. Sigh. */
410
411 value = PyDict_GetItemString(modules, "__builtin__");
412 if (value != NULL && PyModule_Check(value)) {
413 dict = PyModule_GetDict(value);
414 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000415 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000416 PyDict_SetItemString(dict, "_", Py_None);
417 }
418 value = PyDict_GetItemString(modules, "sys");
419 if (value != NULL && PyModule_Check(value)) {
420 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000421 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000422 dict = PyModule_GetDict(value);
423 for (p = sys_deletes; *p != NULL; p++) {
424 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000425 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000426 PyDict_SetItemString(dict, *p, Py_None);
427 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000428 for (p = sys_files; *p != NULL; p+=2) {
429 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000430 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000431 v = PyDict_GetItemString(dict, *(p+1));
432 if (v == NULL)
433 v = Py_None;
434 PyDict_SetItemString(dict, *p, v);
435 }
436 }
437
438 /* First, delete __main__ */
439 value = PyDict_GetItemString(modules, "__main__");
440 if (value != NULL && PyModule_Check(value)) {
441 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000442 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000443 _PyModule_Clear(value);
444 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445 }
446
Guido van Rossum758eec01998-01-19 21:58:26 +0000447 /* The special treatment of __builtin__ here is because even
448 when it's not referenced as a module, its dictionary is
449 referenced by almost every module's __builtins__. Since
450 deleting a module clears its dictionary (even if there are
451 references left to it), we need to delete the __builtin__
452 module last. Likewise, we don't delete sys until the very
453 end because it is implicitly referenced (e.g. by print).
454
455 Also note that we 'delete' modules by replacing their entry
456 in the modules dict with None, rather than really deleting
457 them; this avoids a rehash of the modules dictionary and
458 also marks them as "non existent" so they won't be
459 re-imported. */
460
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000461 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000462 one (skipping __builtin__ and sys) and delete them */
463 do {
464 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000465 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000466 while (PyDict_Next(modules, &pos, &key, &value)) {
467 if (value->ob_refcnt != 1)
468 continue;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000469 if (PyString_Check(key) && PyModule_Check(value)) {
470 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000471 if (strcmp(name, "__builtin__") == 0)
472 continue;
473 if (strcmp(name, "sys") == 0)
474 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000475 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000476 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000477 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000478 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000479 PyDict_SetItem(modules, key, Py_None);
480 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481 }
482 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000483 } while (ndone > 0);
484
Guido van Rossum758eec01998-01-19 21:58:26 +0000485 /* Next, delete all modules (still skipping __builtin__ and sys) */
486 pos = 0;
487 while (PyDict_Next(modules, &pos, &key, &value)) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000488 if (PyString_Check(key) && PyModule_Check(value)) {
489 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000490 if (strcmp(name, "__builtin__") == 0)
491 continue;
492 if (strcmp(name, "sys") == 0)
493 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000494 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000495 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000496 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000497 PyDict_SetItem(modules, key, Py_None);
498 }
499 }
500
501 /* Next, delete sys and __builtin__ (in that order) */
502 value = PyDict_GetItemString(modules, "sys");
503 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000504 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000505 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000506 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000507 PyDict_SetItemString(modules, "sys", Py_None);
508 }
509 value = PyDict_GetItemString(modules, "__builtin__");
510 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000511 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000512 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000513 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000514 PyDict_SetItemString(modules, "__builtin__", Py_None);
515 }
516
517 /* Finally, clear and delete the modules directory */
518 PyDict_Clear(modules);
519 interp->modules = NULL;
520 Py_DECREF(modules);
Collin Winter276887b2007-03-12 16:11:39 +0000521 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000522}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000523
524
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000525/* Helper for pythonrun.c -- return magic number */
526
527long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000528PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000529{
Guido van Rossum96774c12000-05-01 20:19:08 +0000530 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000531}
532
533
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534/* Magic for extension modules (built-in as well as dynamically
535 loaded). To prevent initializing an extension module more than
536 once, we keep a static dictionary 'extensions' keyed by module name
537 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000538 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539 dictionary is stored by calling _PyImport_FixupExtension()
540 immediately after the module initialization function succeeds. A
541 copy can be retrieved from there by calling
542 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000543
Guido van Rossum79f25d91997-04-29 20:08:16 +0000544PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000546{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 PyObject *modules, *mod, *dict, *copy;
548 if (extensions == NULL) {
549 extensions = PyDict_New();
550 if (extensions == NULL)
551 return NULL;
552 }
553 modules = PyImport_GetModuleDict();
554 mod = PyDict_GetItemString(modules, name);
555 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000556 PyErr_Format(PyExc_SystemError,
557 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558 return NULL;
559 }
560 dict = PyModule_GetDict(mod);
561 if (dict == NULL)
562 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000563 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 if (copy == NULL)
565 return NULL;
566 PyDict_SetItemString(extensions, filename, copy);
567 Py_DECREF(copy);
568 return copy;
569}
570
571PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000574 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575 if (extensions == NULL)
576 return NULL;
577 dict = PyDict_GetItemString(extensions, filename);
578 if (dict == NULL)
579 return NULL;
580 mod = PyImport_AddModule(name);
581 if (mod == NULL)
582 return NULL;
583 mdict = PyModule_GetDict(mod);
584 if (mdict == NULL)
585 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000586 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000589 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 name, filename);
591 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000592}
593
594
595/* Get the module object corresponding to a module name.
596 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000597 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000598 Because the former action is most common, THIS DOES NOT RETURN A
599 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600
Guido van Rossum79f25d91997-04-29 20:08:16 +0000601PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000602PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000603{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000605 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000606
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000608 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000610 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611 if (m == NULL)
612 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000614 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000615 return NULL;
616 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000617 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000618
619 return m;
620}
621
Tim Peters1cd70172004-08-02 03:52:12 +0000622/* Remove name from sys.modules, if it's there. */
623static void
624_RemoveModule(const char *name)
625{
626 PyObject *modules = PyImport_GetModuleDict();
627 if (PyDict_GetItemString(modules, name) == NULL)
628 return;
629 if (PyDict_DelItemString(modules, name) < 0)
630 Py_FatalError("import: deleting existing key in"
631 "sys.modules failed");
632}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000633
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000634/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000635 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
636 * removed from sys.modules, to avoid leaving damaged module objects
637 * in sys.modules. The caller may wish to restore the original
638 * module object (if any) in this case; PyImport_ReloadModule is an
639 * example.
640 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000641PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000642PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000644 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
645}
646
647PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000648PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000649{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000651 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000652
Guido van Rossum79f25d91997-04-29 20:08:16 +0000653 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000654 if (m == NULL)
655 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000656 /* If the module is being reloaded, we get the old module back
657 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000658 d = PyModule_GetDict(m);
659 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
660 if (PyDict_SetItemString(d, "__builtins__",
661 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000662 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000663 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000664 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000665 v = NULL;
666 if (pathname != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000667 v = PyString_FromString(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000668 if (v == NULL)
669 PyErr_Clear();
670 }
671 if (v == NULL) {
672 v = ((PyCodeObject *)co)->co_filename;
673 Py_INCREF(v);
674 }
675 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000676 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000677 Py_DECREF(v);
678
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000679 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000681 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000683
Guido van Rossum25ce5661997-08-02 03:10:38 +0000684 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000685 PyErr_Format(PyExc_ImportError,
686 "Loaded module %.200s not found in sys.modules",
687 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000688 return NULL;
689 }
690
Guido van Rossum79f25d91997-04-29 20:08:16 +0000691 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000692
693 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000694
695 error:
696 _RemoveModule(name);
697 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698}
699
700
701/* Given a pathname for a Python source file, fill a buffer with the
702 pathname for the corresponding compiled file. Return the pathname
703 for the compiled file, or NULL if there's no space in the buffer.
704 Doesn't set an exception. */
705
706static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000707make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708{
Tim Petersc1731372001-08-04 08:12:36 +0000709 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710 if (len+2 > buflen)
711 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000712
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000713#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000714 /* Treat .pyw as if it were .py. The case of ".pyw" must match
715 that used in _PyImport_StandardFiletab. */
716 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
717 --len; /* pretend 'w' isn't there */
718#endif
719 memcpy(buf, pathname, len);
720 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
721 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722
723 return buf;
724}
725
726
727/* Given a pathname for a Python source file, its time of last
728 modification, and a pathname for a compiled file, check whether the
729 compiled file represents the same version of the source. If so,
730 return a FILE pointer for the compiled file, positioned just after
731 the header; if not, return NULL.
732 Doesn't set an exception. */
733
734static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000735check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000736{
737 FILE *fp;
738 long magic;
739 long pyc_mtime;
740
741 fp = fopen(cpathname, "rb");
742 if (fp == NULL)
743 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000744 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000745 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000747 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000748 fclose(fp);
749 return NULL;
750 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000751 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000752 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000753 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000754 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755 fclose(fp);
756 return NULL;
757 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000758 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000759 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000760 return fp;
761}
762
763
764/* Read a code object from a file and check it for validity */
765
Guido van Rossum79f25d91997-04-29 20:08:16 +0000766static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000767read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000768{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000770
Tim Petersd9b9ac82001-01-28 00:27:39 +0000771 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000772 if (co == NULL)
773 return NULL;
774 if (!PyCode_Check(co)) {
775 PyErr_Format(PyExc_ImportError,
776 "Non-code object in %.200s", cpathname);
777 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000778 return NULL;
779 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000780 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781}
782
783
784/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000785 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786
Guido van Rossum79f25d91997-04-29 20:08:16 +0000787static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000788load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000789{
790 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000791 PyCodeObject *co;
792 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793
Guido van Rossum79f25d91997-04-29 20:08:16 +0000794 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000795 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000796 PyErr_Format(PyExc_ImportError,
797 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000798 return NULL;
799 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000800 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000801 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000802 if (co == NULL)
803 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000804 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000805 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000807 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000808 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000809
810 return m;
811}
812
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813/* Parse a source file and return the corresponding code object */
814
Guido van Rossum79f25d91997-04-29 20:08:16 +0000815static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818 PyCodeObject *co = NULL;
819 mod_ty mod;
Christian Heimes3c608332008-03-26 22:01:37 +0000820 PyCompilerFlags flags;
Neal Norwitz2a399b02006-09-11 04:28:16 +0000821 PyArena *arena = PyArena_New();
822 if (arena == NULL)
823 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000824
Christian Heimes7f23d862008-03-26 22:51:58 +0000825 flags.cf_flags = 0;
826
Christian Heimes3c608332008-03-26 22:01:37 +0000827 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000828 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000829 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000830 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831 }
Neal Norwitz2a399b02006-09-11 04:28:16 +0000832 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833 return co;
834}
835
836
Guido van Rossum55a83382000-09-20 20:31:38 +0000837/* Helper to open a bytecode file for writing in exclusive mode */
838
839static FILE *
Christian Heimes40346852008-02-23 17:52:07 +0000840open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000841{
842#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
843 /* Use O_EXCL to avoid a race condition when another process tries to
844 write the same file. When that happens, our open() call fails,
845 which is just fine (since it's only a cache).
846 XXX If the file exists and is writable but the directory is not
847 writable, the file will never be written. Oh well.
848 */
849 int fd;
850 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000851 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
852#ifdef O_BINARY
853 |O_BINARY /* necessary for Windows */
854#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000855#ifdef __VMS
Christian Heimes40346852008-02-23 17:52:07 +0000856 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000857#else
Christian Heimes40346852008-02-23 17:52:07 +0000858 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000859#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000860 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000861 if (fd < 0)
862 return NULL;
863 return fdopen(fd, "wb");
864#else
865 /* Best we can do -- on Windows this can't happen anyway */
866 return fopen(filename, "wb");
867#endif
868}
869
870
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000871/* Write a compiled module to a file, placing the time of last
872 modification of its source into the header.
873 Errors are ignored, if a write error occurs an attempt is made to
874 remove the file. */
875
876static void
Christian Heimes40346852008-02-23 17:52:07 +0000877write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878{
879 FILE *fp;
Christian Heimes40346852008-02-23 17:52:07 +0000880 time_t mtime = srcstat->st_mtime;
881 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882
Christian Heimes40346852008-02-23 17:52:07 +0000883 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000885 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000886 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887 "# can't create %s\n", cpathname);
888 return;
889 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000890 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000891 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000892 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
893 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000894 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000895 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000896 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897 /* Don't keep partial file */
898 fclose(fp);
899 (void) unlink(cpathname);
900 return;
901 }
902 /* Now write the true mtime */
903 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000905 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000906 fflush(fp);
907 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000908 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000909 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910}
911
Antoine Pitroue96d4ea2009-01-06 18:10:47 +0000912static void
913update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
914{
915 PyObject *constants, *tmp;
916 Py_ssize_t i, n;
917
918 if (!_PyString_Eq(co->co_filename, oldname))
919 return;
920
921 tmp = co->co_filename;
922 co->co_filename = newname;
923 Py_INCREF(co->co_filename);
924 Py_DECREF(tmp);
925
926 constants = co->co_consts;
927 n = PyTuple_GET_SIZE(constants);
928 for (i = 0; i < n; i++) {
929 tmp = PyTuple_GET_ITEM(constants, i);
930 if (PyCode_Check(tmp))
931 update_code_filenames((PyCodeObject *)tmp,
932 oldname, newname);
933 }
934}
935
936static int
937update_compiled_module(PyCodeObject *co, char *pathname)
938{
939 PyObject *oldname, *newname;
940
941 if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
942 return 0;
943
944 newname = PyString_FromString(pathname);
945 if (newname == NULL)
946 return -1;
947
948 oldname = co->co_filename;
949 Py_INCREF(oldname);
950 update_code_filenames(co, oldname, newname);
951 Py_DECREF(oldname);
952 Py_DECREF(newname);
953 return 1;
954}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000955
956/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000957 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
958 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000959
Guido van Rossum79f25d91997-04-29 20:08:16 +0000960static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000961load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000962{
Christian Heimes40346852008-02-23 17:52:07 +0000963 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000964 FILE *fpc;
965 char buf[MAXPATHLEN+1];
966 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000967 PyCodeObject *co;
968 PyObject *m;
Christian Heimes40346852008-02-23 17:52:07 +0000969
970 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000971 PyErr_Format(PyExc_RuntimeError,
Christian Heimes40346852008-02-23 17:52:07 +0000972 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000973 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000974 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000975 }
Fred Drake4c82b232000-06-30 16:18:57 +0000976#if SIZEOF_TIME_T > 4
977 /* Python's .pyc timestamp handling presumes that the timestamp fits
978 in 4 bytes. This will be fine until sometime in the year 2038,
979 when a 4-byte signed time_t will overflow.
980 */
Christian Heimes40346852008-02-23 17:52:07 +0000981 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000982 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000983 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000984 return NULL;
985 }
986#endif
Tim Peters36515e22001-11-18 04:06:29 +0000987 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000988 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000989 if (cpathname != NULL &&
Christian Heimes40346852008-02-23 17:52:07 +0000990 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000991 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000992 fclose(fpc);
993 if (co == NULL)
994 return NULL;
Antoine Pitroue96d4ea2009-01-06 18:10:47 +0000995 if (update_compiled_module(co, pathname) < 0)
996 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000997 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000998 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000999 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +00001000 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001001 }
1002 else {
1003 co = parse_source_module(pathname, fp);
1004 if (co == NULL)
1005 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001006 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001007 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001008 name, pathname);
Georg Brandl2da0fce2008-01-07 17:09:35 +00001009 if (cpathname) {
1010 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1011 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes40346852008-02-23 17:52:07 +00001012 write_compiled_module(co, cpathname, &st);
Georg Brandl2da0fce2008-01-07 17:09:35 +00001013 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +00001015 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001016 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001017
1018 return m;
1019}
1020
1021
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001022/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001023static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1024static struct filedescr *find_module(char *, char *, PyObject *,
1025 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001026static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027
1028/* Load a package and return its module object WITH INCREMENTED
1029 REFERENCE COUNT */
1030
1031static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001032load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001033{
Tim Peters1cd70172004-08-02 03:52:12 +00001034 PyObject *m, *d;
1035 PyObject *file = NULL;
1036 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001037 int err;
1038 char buf[MAXPATHLEN+1];
1039 FILE *fp = NULL;
1040 struct filedescr *fdp;
1041
1042 m = PyImport_AddModule(name);
1043 if (m == NULL)
1044 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001045 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001046 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001047 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001048 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001049 file = PyString_FromString(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001050 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001051 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001052 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001053 if (path == NULL)
1054 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001055 err = PyDict_SetItemString(d, "__file__", file);
1056 if (err == 0)
1057 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001058 if (err != 0)
1059 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001060 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001061 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062 if (fdp == NULL) {
1063 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1064 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001065 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001066 }
1067 else
1068 m = NULL;
1069 goto cleanup;
1070 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001071 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001072 if (fp != NULL)
1073 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001074 goto cleanup;
1075
1076 error:
1077 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001078 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001079 Py_XDECREF(path);
1080 Py_XDECREF(file);
1081 return m;
1082}
1083
1084
1085/* Helper to test for built-in module */
1086
1087static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001088is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001089{
1090 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001091 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1092 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1093 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001094 return -1;
1095 else
1096 return 1;
1097 }
1098 }
1099 return 0;
1100}
1101
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001102
Just van Rossum52e14d62002-12-30 22:08:05 +00001103/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1104 possibly by fetching it from the path_importer_cache dict. If it
Brett Cannon94b69f62006-09-28 22:10:14 +00001105 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001106 that can handle the path item. Return None if no hook could;
1107 this tells our caller it should fall back to the builtin
1108 import mechanism. Cache the result in path_importer_cache.
1109 Returns a borrowed reference. */
1110
1111static PyObject *
1112get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1113 PyObject *p)
1114{
1115 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001116 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001117
1118 /* These conditions are the caller's responsibility: */
1119 assert(PyList_Check(path_hooks));
1120 assert(PyDict_Check(path_importer_cache));
1121
1122 nhooks = PyList_Size(path_hooks);
1123 if (nhooks < 0)
1124 return NULL; /* Shouldn't happen */
1125
1126 importer = PyDict_GetItem(path_importer_cache, p);
1127 if (importer != NULL)
1128 return importer;
1129
1130 /* set path_importer_cache[p] to None to avoid recursion */
1131 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1132 return NULL;
1133
1134 for (j = 0; j < nhooks; j++) {
1135 PyObject *hook = PyList_GetItem(path_hooks, j);
1136 if (hook == NULL)
1137 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001138 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001139 if (importer != NULL)
1140 break;
1141
1142 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1143 return NULL;
1144 }
1145 PyErr_Clear();
1146 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001147 if (importer == NULL) {
1148 importer = PyObject_CallFunctionObjArgs(
Nick Coghlan327a39b2007-11-18 11:56:28 +00001149 (PyObject *)&PyNullImporter_Type, p, NULL
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001150 );
1151 if (importer == NULL) {
1152 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1153 PyErr_Clear();
1154 return Py_None;
1155 }
1156 }
1157 }
1158 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001159 int err = PyDict_SetItem(path_importer_cache, p, importer);
1160 Py_DECREF(importer);
1161 if (err != 0)
1162 return NULL;
1163 }
1164 return importer;
1165}
1166
Nick Coghlan327a39b2007-11-18 11:56:28 +00001167PyAPI_FUNC(PyObject *)
1168PyImport_GetImporter(PyObject *path) {
1169 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1170
1171 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1172 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1173 importer = get_path_importer(path_importer_cache,
1174 path_hooks, path);
1175 }
1176 }
1177 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1178 return importer;
1179}
1180
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181/* Search the path (default sys.path) for a module. Return the
1182 corresponding filedescr struct, and (via return arguments) the
1183 pathname and an open file. Return NULL if the module is not found. */
1184
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001185#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001186extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001188#endif
1189
Martin v. Löwis18e16552006-02-15 17:27:45 +00001190static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001191static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001192static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001193
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001194static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001195find_module(char *fullname, char *subname, PyObject *path, char *buf,
1196 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001197{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001198 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001199 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001200 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001201 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001202 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001203 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001204#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001205 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001206#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001207 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1208 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1209 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001210 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001211#if defined(PYOS_OS2)
1212 size_t saved_len;
1213 size_t saved_namelen;
1214 char *saved_buf = NULL;
1215#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001216 if (p_loader != NULL)
1217 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001218
Just van Rossum52e14d62002-12-30 22:08:05 +00001219 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001220 PyErr_SetString(PyExc_OverflowError,
1221 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001222 return NULL;
1223 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001224 strcpy(name, subname);
1225
1226 /* sys.meta_path import hook */
1227 if (p_loader != NULL) {
1228 PyObject *meta_path;
1229
1230 meta_path = PySys_GetObject("meta_path");
1231 if (meta_path == NULL || !PyList_Check(meta_path)) {
1232 PyErr_SetString(PyExc_ImportError,
1233 "sys.meta_path must be a list of "
1234 "import hooks");
1235 return NULL;
1236 }
1237 Py_INCREF(meta_path); /* zap guard */
1238 npath = PyList_Size(meta_path);
1239 for (i = 0; i < npath; i++) {
1240 PyObject *loader;
1241 PyObject *hook = PyList_GetItem(meta_path, i);
1242 loader = PyObject_CallMethod(hook, "find_module",
1243 "sO", fullname,
1244 path != NULL ?
1245 path : Py_None);
1246 if (loader == NULL) {
1247 Py_DECREF(meta_path);
1248 return NULL; /* true error */
1249 }
1250 if (loader != Py_None) {
1251 /* a loader was found */
1252 *p_loader = loader;
1253 Py_DECREF(meta_path);
1254 return &importhookdescr;
1255 }
1256 Py_DECREF(loader);
1257 }
1258 Py_DECREF(meta_path);
1259 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001260
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001261 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001262 /* The only type of submodule allowed inside a "frozen"
1263 package are other frozen modules or packages. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001264 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001265 PyErr_SetString(PyExc_ImportError,
1266 "full frozen module name too long");
1267 return NULL;
1268 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001269 strcpy(buf, PyString_AsString(path));
Guido van Rossum0506a431998-08-11 15:07:39 +00001270 strcat(buf, ".");
1271 strcat(buf, name);
1272 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001273 if (find_frozen(name) != NULL) {
1274 strcpy(buf, name);
1275 return &fd_frozen;
1276 }
1277 PyErr_Format(PyExc_ImportError,
1278 "No frozen submodule named %.200s", name);
1279 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001280 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001281 if (path == NULL) {
1282 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001283 strcpy(buf, name);
1284 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001285 }
Greg Ward201baee2001-10-04 14:52:06 +00001286 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001287 strcpy(buf, name);
1288 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001289 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001290
Guido van Rossumac279101996-08-22 23:10:58 +00001291#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001292 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1293 if (fp != NULL) {
1294 *p_fp = fp;
1295 return fdp;
1296 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001297#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001298 path = PySys_GetObject("path");
1299 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001300 if (path == NULL || !PyList_Check(path)) {
1301 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001302 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001303 return NULL;
1304 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001305
1306 path_hooks = PySys_GetObject("path_hooks");
1307 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1308 PyErr_SetString(PyExc_ImportError,
1309 "sys.path_hooks must be a list of "
1310 "import hooks");
1311 return NULL;
1312 }
1313 path_importer_cache = PySys_GetObject("path_importer_cache");
1314 if (path_importer_cache == NULL ||
1315 !PyDict_Check(path_importer_cache)) {
1316 PyErr_SetString(PyExc_ImportError,
1317 "sys.path_importer_cache must be a dict");
1318 return NULL;
1319 }
1320
Guido van Rossum79f25d91997-04-29 20:08:16 +00001321 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001322 namelen = strlen(name);
1323 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001324 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001325 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001326 if (!v)
1327 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001328#ifdef Py_USING_UNICODE
1329 if (PyUnicode_Check(v)) {
1330 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1331 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1332 if (copy == NULL)
1333 return NULL;
1334 v = copy;
1335 }
1336 else
1337#endif
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001338 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001339 continue;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001340 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001341 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1342 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001343 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001344 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001345 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001346 if (strlen(buf) != len) {
1347 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001348 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001349 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001350
1351 /* sys.path_hooks import hook */
1352 if (p_loader != NULL) {
1353 PyObject *importer;
1354
1355 importer = get_path_importer(path_importer_cache,
1356 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001357 if (importer == NULL) {
1358 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001359 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001360 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001361 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001362 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001363 PyObject *loader;
1364 loader = PyObject_CallMethod(importer,
1365 "find_module",
1366 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001367 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001368 if (loader == NULL)
1369 return NULL; /* error */
1370 if (loader != Py_None) {
1371 /* a loader was found */
1372 *p_loader = loader;
1373 return &importhookdescr;
1374 }
1375 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001376 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001377 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001378 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001379 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001380
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001381 if (len > 0 && buf[len-1] != SEP
1382#ifdef ALTSEP
1383 && buf[len-1] != ALTSEP
1384#endif
1385 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001386 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001387 strcpy(buf+len, name);
1388 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001389
1390 /* Check for package import (buf holds a directory name,
1391 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001392#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001393 if (stat(buf, &statbuf) == 0 && /* it exists */
1394 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001395 case_ok(buf, len, namelen, name)) { /* case matches */
1396 if (find_init_module(buf)) { /* and has __init__.py */
1397 Py_XDECREF(copy);
1398 return &fd_package;
1399 }
1400 else {
1401 char warnstr[MAXPATHLEN+80];
1402 sprintf(warnstr, "Not importing directory "
1403 "'%.*s': missing __init__.py",
1404 MAXPATHLEN, buf);
1405 if (PyErr_Warn(PyExc_ImportWarning,
1406 warnstr)) {
1407 Py_XDECREF(copy);
1408 return NULL;
1409 }
1410 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001411 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001412#else
1413 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001414#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001415 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001416 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001417 if (find_init_module(buf)) {
1418 Py_XDECREF(copy);
1419 return &fd_package;
1420 }
1421 else {
1422 char warnstr[MAXPATHLEN+80];
1423 sprintf(warnstr, "Not importing directory "
1424 "'%.*s': missing __init__.py",
1425 MAXPATHLEN, buf);
1426 if (PyErr_Warn(PyExc_ImportWarning,
1427 warnstr)) {
1428 Py_XDECREF(copy);
1429 return NULL;
1430 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001431 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001432#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001433#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001434#if defined(PYOS_OS2)
1435 /* take a snapshot of the module spec for restoration
1436 * after the 8 character DLL hackery
1437 */
1438 saved_buf = strdup(buf);
1439 saved_len = len;
1440 saved_namelen = namelen;
1441#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001442 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Georg Brandladd36e52007-08-23 18:08:06 +00001443#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001444 /* OS/2 limits DLLs to 8 character names (w/o
1445 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001446 * so if the name is longer than that and its a
1447 * dynamically loaded module we're going to try,
1448 * truncate the name before trying
1449 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001450 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001451 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001452 const struct filedescr *scan;
1453 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001454 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001455 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001456 break;
1457 else
1458 scan++;
1459 }
1460 if (scan->suffix != NULL) {
1461 /* yes, so truncate the name */
1462 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001463 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001464 buf[len] = '\0';
1465 }
1466 }
1467#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001468 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001469 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001470 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001471 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001472 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001473 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001474 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001475 if (fp != NULL) {
1476 if (case_ok(buf, len, namelen, name))
1477 break;
1478 else { /* continue search */
1479 fclose(fp);
1480 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001481 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001482 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001483#if defined(PYOS_OS2)
1484 /* restore the saved snapshot */
1485 strcpy(buf, saved_buf);
1486 len = saved_len;
1487 namelen = saved_namelen;
1488#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001489 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001490#if defined(PYOS_OS2)
1491 /* don't need/want the module name snapshot anymore */
1492 if (saved_buf)
1493 {
1494 free(saved_buf);
1495 saved_buf = NULL;
1496 }
1497#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001498 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001499 if (fp != NULL)
1500 break;
1501 }
1502 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001503 PyErr_Format(PyExc_ImportError,
1504 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001505 return NULL;
1506 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001507 *p_fp = fp;
1508 return fdp;
1509}
1510
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001511/* Helpers for main.c
1512 * Find the source file corresponding to a named module
1513 */
1514struct filedescr *
1515_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1516 size_t buflen, FILE **p_fp, PyObject **p_loader)
1517{
1518 return find_module((char *) name, (char *) name, path,
1519 buf, buflen, p_fp, p_loader);
1520}
1521
1522PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1523{
1524 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1525}
1526
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001528 * The arguments here are tricky, best shown by example:
1529 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1530 * ^ ^ ^ ^
1531 * |--------------------- buf ---------------------|
1532 * |------------------- len ------------------|
1533 * |------ name -------|
1534 * |----- namelen -----|
1535 * buf is the full path, but len only counts up to (& exclusive of) the
1536 * extension. name is the module name, also exclusive of extension.
1537 *
1538 * We've already done a successful stat() or fopen() on buf, so know that
1539 * there's some match, possibly case-insensitive.
1540 *
Tim Peters50d8d372001-02-28 05:34:27 +00001541 * case_ok() is to return 1 if there's a case-sensitive match for
1542 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1543 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001544 *
Tim Peters50d8d372001-02-28 05:34:27 +00001545 * case_ok() is used to implement case-sensitive import semantics even
1546 * on platforms with case-insensitive filesystems. It's trivial to implement
1547 * for case-sensitive filesystems. It's pretty much a cross-platform
1548 * nightmare for systems with case-insensitive filesystems.
1549 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001550
Tim Peters50d8d372001-02-28 05:34:27 +00001551/* First we may need a pile of platform-specific header files; the sequence
1552 * of #if's here should match the sequence in the body of case_ok().
1553 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001554#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001555#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001556
Tim Peters50d8d372001-02-28 05:34:27 +00001557#elif defined(DJGPP)
1558#include <dir.h>
1559
Jason Tishler7961aa62005-05-20 00:56:54 +00001560#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001561#include <sys/types.h>
1562#include <dirent.h>
1563
Andrew MacIntyred9400542002-02-26 11:41:34 +00001564#elif defined(PYOS_OS2)
1565#define INCL_DOS
1566#define INCL_DOSERRORS
1567#define INCL_NOPMAPI
1568#include <os2.h>
1569
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001570#elif defined(RISCOS)
1571#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001572#endif
1573
Guido van Rossum0980bd91998-02-13 17:18:36 +00001574static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001575case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001576{
Tim Peters50d8d372001-02-28 05:34:27 +00001577/* Pick a platform-specific implementation; the sequence of #if's here should
1578 * match the sequence just above.
1579 */
1580
Jason Tishler7961aa62005-05-20 00:56:54 +00001581/* MS_WINDOWS */
1582#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001583 WIN32_FIND_DATA data;
1584 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001585
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001586 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001587 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001588
Guido van Rossum0980bd91998-02-13 17:18:36 +00001589 h = FindFirstFile(buf, &data);
1590 if (h == INVALID_HANDLE_VALUE) {
1591 PyErr_Format(PyExc_NameError,
1592 "Can't find file for module %.100s\n(filename %.300s)",
1593 name, buf);
1594 return 0;
1595 }
1596 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001597 return strncmp(data.cFileName, name, namelen) == 0;
1598
1599/* DJGPP */
1600#elif defined(DJGPP)
1601 struct ffblk ffblk;
1602 int done;
1603
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001604 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001605 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001606
1607 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1608 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001609 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001610 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001611 name, buf);
1612 return 0;
1613 }
Tim Peters50d8d372001-02-28 05:34:27 +00001614 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001615
Jason Tishler7961aa62005-05-20 00:56:54 +00001616/* new-fangled macintosh (macosx) or Cygwin */
1617#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001618 DIR *dirp;
1619 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001620 char dirname[MAXPATHLEN + 1];
1621 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001622
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001623 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001624 return 1;
1625
Tim Petersd1e87a82001-03-01 18:12:00 +00001626 /* Copy the dir component into dirname; substitute "." if empty */
1627 if (dirlen <= 0) {
1628 dirname[0] = '.';
1629 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001630 }
1631 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001632 assert(dirlen <= MAXPATHLEN);
1633 memcpy(dirname, buf, dirlen);
1634 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001635 }
1636 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001637 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001638 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001639 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001640 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001641 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001642#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001643 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001644#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001645 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001646#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001647 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001648 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001649 (void)closedir(dirp);
1650 return 1; /* Found */
1651 }
1652 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001653 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001654 }
Tim Peters430f5d42001-03-01 01:30:56 +00001655 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001656
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001657/* RISC OS */
1658#elif defined(RISCOS)
1659 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1660 char buf2[MAXPATHLEN+2];
1661 char *nameWithExt = buf+len-namelen;
1662 int canonlen;
1663 os_error *e;
1664
1665 if (Py_GETENV("PYTHONCASEOK") != NULL)
1666 return 1;
1667
1668 /* workaround:
1669 append wildcard, otherwise case of filename wouldn't be touched */
1670 strcpy(buf2, buf);
1671 strcat(buf2, "*");
1672
1673 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1674 canonlen = MAXPATHLEN+1-canonlen;
1675 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1676 return 0;
1677 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1678 return 1; /* match */
1679
1680 return 0;
1681
Andrew MacIntyred9400542002-02-26 11:41:34 +00001682/* OS/2 */
1683#elif defined(PYOS_OS2)
1684 HDIR hdir = 1;
1685 ULONG srchcnt = 1;
1686 FILEFINDBUF3 ffbuf;
1687 APIRET rc;
1688
Georg Brandlaed6c662008-01-07 17:25:53 +00001689 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001690 return 1;
1691
1692 rc = DosFindFirst(buf,
1693 &hdir,
1694 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1695 &ffbuf, sizeof(ffbuf),
1696 &srchcnt,
1697 FIL_STANDARD);
1698 if (rc != NO_ERROR)
1699 return 0;
1700 return strncmp(ffbuf.achName, name, namelen) == 0;
1701
Tim Peters50d8d372001-02-28 05:34:27 +00001702/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1703#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001704 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001705
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001706#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001707}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001708
Guido van Rossum0980bd91998-02-13 17:18:36 +00001709
Guido van Rossum197346f1997-10-31 18:38:52 +00001710#ifdef HAVE_STAT
1711/* Helper to look for __init__.py or __init__.py[co] in potential package */
1712static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001713find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001714{
Tim Peters0f9431f2001-07-05 03:47:53 +00001715 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001716 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001717 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001718 struct stat statbuf;
1719
Tim Peters0f9431f2001-07-05 03:47:53 +00001720/* For calling case_ok(buf, len, namelen, name):
1721 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1722 * ^ ^ ^ ^
1723 * |--------------------- buf ---------------------|
1724 * |------------------- len ------------------|
1725 * |------ name -------|
1726 * |----- namelen -----|
1727 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001728 if (save_len + 13 >= MAXPATHLEN)
1729 return 0;
1730 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001731 pname = buf + i;
1732 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001733 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001734 if (case_ok(buf,
1735 save_len + 9, /* len("/__init__") */
1736 8, /* len("__init__") */
1737 pname)) {
1738 buf[save_len] = '\0';
1739 return 1;
1740 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001741 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001742 i += strlen(pname);
1743 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001744 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001745 if (case_ok(buf,
1746 save_len + 9, /* len("/__init__") */
1747 8, /* len("__init__") */
1748 pname)) {
1749 buf[save_len] = '\0';
1750 return 1;
1751 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001752 }
1753 buf[save_len] = '\0';
1754 return 0;
1755}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001756
1757#else
1758
1759#ifdef RISCOS
1760static int
1761find_init_module(buf)
1762 char *buf;
1763{
1764 int save_len = strlen(buf);
1765 int i = save_len;
1766
1767 if (save_len + 13 >= MAXPATHLEN)
1768 return 0;
1769 buf[i++] = SEP;
1770 strcpy(buf+i, "__init__/py");
1771 if (isfile(buf)) {
1772 buf[save_len] = '\0';
1773 return 1;
1774 }
1775
1776 if (Py_OptimizeFlag)
1777 strcpy(buf+i, "o");
1778 else
1779 strcpy(buf+i, "c");
1780 if (isfile(buf)) {
1781 buf[save_len] = '\0';
1782 return 1;
1783 }
1784 buf[save_len] = '\0';
1785 return 0;
1786}
1787#endif /*RISCOS*/
1788
Guido van Rossum197346f1997-10-31 18:38:52 +00001789#endif /* HAVE_STAT */
1790
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001791
Tim Petersdbd9ba62000-07-09 03:09:57 +00001792static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001793
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001794/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001795 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001796
Guido van Rossum79f25d91997-04-29 20:08:16 +00001797static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001798load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001799{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001800 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001801 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001802 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001803
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001804 /* First check that there's an open file (if we need one) */
1805 switch (type) {
1806 case PY_SOURCE:
1807 case PY_COMPILED:
1808 if (fp == NULL) {
1809 PyErr_Format(PyExc_ValueError,
1810 "file object required for import (type code %d)",
1811 type);
1812 return NULL;
1813 }
1814 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001815
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001816 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817
1818 case PY_SOURCE:
1819 m = load_source_module(name, buf, fp);
1820 break;
1821
1822 case PY_COMPILED:
1823 m = load_compiled_module(name, buf, fp);
1824 break;
1825
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001826#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001827 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001828 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001829 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001830#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001831
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001832 case PKG_DIRECTORY:
1833 m = load_package(name, buf);
1834 break;
1835
1836 case C_BUILTIN:
1837 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001838 if (buf != NULL && buf[0] != '\0')
1839 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001840 if (type == C_BUILTIN)
1841 err = init_builtin(name);
1842 else
1843 err = PyImport_ImportFrozenModule(name);
1844 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001845 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001846 if (err == 0) {
1847 PyErr_Format(PyExc_ImportError,
1848 "Purported %s module %.200s not found",
1849 type == C_BUILTIN ?
1850 "builtin" : "frozen",
1851 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001852 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001853 }
1854 modules = PyImport_GetModuleDict();
1855 m = PyDict_GetItemString(modules, name);
1856 if (m == NULL) {
1857 PyErr_Format(
1858 PyExc_ImportError,
1859 "%s module %.200s not properly initialized",
1860 type == C_BUILTIN ?
1861 "builtin" : "frozen",
1862 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001863 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001864 }
1865 Py_INCREF(m);
1866 break;
1867
Just van Rossum52e14d62002-12-30 22:08:05 +00001868 case IMP_HOOK: {
1869 if (loader == NULL) {
1870 PyErr_SetString(PyExc_ImportError,
1871 "import hook without loader");
1872 return NULL;
1873 }
1874 m = PyObject_CallMethod(loader, "load_module", "s", name);
1875 break;
1876 }
1877
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001878 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001879 PyErr_Format(PyExc_ImportError,
1880 "Don't know how to import %.200s (type code %d)",
1881 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001882 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001883
1884 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001885
1886 return m;
1887}
1888
1889
1890/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001891 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001893
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001894static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001895init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001896{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001897 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001898
Greg Ward201baee2001-10-04 14:52:06 +00001899 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001900 return 1;
1901
Guido van Rossum771c6c81997-10-31 18:37:24 +00001902 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001903 if (strcmp(name, p->name) == 0) {
1904 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001905 PyErr_Format(PyExc_ImportError,
1906 "Cannot re-init internal module %.200s",
1907 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001908 return -1;
1909 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001910 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001911 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001912 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001913 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001914 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001915 if (_PyImport_FixupExtension(name, name) == NULL)
1916 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001917 return 1;
1918 }
1919 }
1920 return 0;
1921}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001922
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001923
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001924/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001925
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001926static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001927find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001928{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001929 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001930
Guido van Rossum79f25d91997-04-29 20:08:16 +00001931 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001932 if (p->name == NULL)
1933 return NULL;
1934 if (strcmp(p->name, name) == 0)
1935 break;
1936 }
1937 return p;
1938}
1939
Guido van Rossum79f25d91997-04-29 20:08:16 +00001940static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001941get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001942{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001943 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001944 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001945
1946 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001947 PyErr_Format(PyExc_ImportError,
1948 "No such frozen object named %.200s",
1949 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001950 return NULL;
1951 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001952 if (p->code == NULL) {
1953 PyErr_Format(PyExc_ImportError,
1954 "Excluded frozen object named %.200s",
1955 name);
1956 return NULL;
1957 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001958 size = p->size;
1959 if (size < 0)
1960 size = -size;
1961 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001962}
1963
1964/* Initialize a frozen module.
1965 Return 1 for succes, 0 if the module is not found, and -1 with
1966 an exception set if the initialization failed.
1967 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001968
1969int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001970PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001971{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001972 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001973 PyObject *co;
1974 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001975 int ispackage;
1976 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001977
1978 if (p == NULL)
1979 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001980 if (p->code == NULL) {
1981 PyErr_Format(PyExc_ImportError,
1982 "Excluded frozen object named %.200s",
1983 name);
1984 return -1;
1985 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001986 size = p->size;
1987 ispackage = (size < 0);
1988 if (ispackage)
1989 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001990 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001991 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001992 name, ispackage ? " package" : "");
1993 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001994 if (co == NULL)
1995 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001996 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001997 PyErr_Format(PyExc_TypeError,
1998 "frozen object %.200s is not a code object",
1999 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002000 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002001 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00002002 if (ispackage) {
2003 /* Set __path__ to the package name */
2004 PyObject *d, *s;
2005 int err;
2006 m = PyImport_AddModule(name);
2007 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002008 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002009 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002010 s = PyString_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00002011 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002012 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002013 err = PyDict_SetItemString(d, "__path__", s);
2014 Py_DECREF(s);
2015 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002016 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002017 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00002018 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002019 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002020 goto err_return;
2021 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002022 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002023 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00002024err_return:
2025 Py_DECREF(co);
2026 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002027}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002028
2029
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002030/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002031 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002032
Guido van Rossum79f25d91997-04-29 20:08:16 +00002033PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002034PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002035{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002036 PyObject *pname;
2037 PyObject *result;
2038
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002039 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00002040 if (pname == NULL)
2041 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002042 result = PyImport_Import(pname);
2043 Py_DECREF(pname);
2044 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002045}
2046
Christian Heimes000a0742008-01-03 22:16:32 +00002047/* Import a module without blocking
2048 *
2049 * At first it tries to fetch the module from sys.modules. If the module was
2050 * never loaded before it loads it with PyImport_ImportModule() unless another
2051 * thread holds the import lock. In the latter case the function raises an
2052 * ImportError instead of blocking.
2053 *
2054 * Returns the module object with incremented ref count.
2055 */
2056PyObject *
2057PyImport_ImportModuleNoBlock(const char *name)
2058{
2059 PyObject *result;
2060 PyObject *modules;
2061 long me;
2062
2063 /* Try to get the module from sys.modules[name] */
2064 modules = PyImport_GetModuleDict();
2065 if (modules == NULL)
2066 return NULL;
2067
2068 result = PyDict_GetItemString(modules, name);
2069 if (result != NULL) {
2070 Py_INCREF(result);
2071 return result;
2072 }
2073 else {
2074 PyErr_Clear();
2075 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002076#ifdef WITH_THREAD
Christian Heimes000a0742008-01-03 22:16:32 +00002077 /* check the import lock
2078 * me might be -1 but I ignore the error here, the lock function
2079 * takes care of the problem */
2080 me = PyThread_get_thread_ident();
2081 if (import_lock_thread == -1 || import_lock_thread == me) {
2082 /* no thread or me is holding the lock */
2083 return PyImport_ImportModule(name);
2084 }
2085 else {
2086 PyErr_Format(PyExc_ImportError,
2087 "Failed to import %.200s because the import lock"
2088 "is held by another thread.",
2089 name);
2090 return NULL;
2091 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002092#else
2093 return PyImport_ImportModule(name);
2094#endif
Christian Heimes000a0742008-01-03 22:16:32 +00002095}
2096
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002097/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002098static PyObject *get_parent(PyObject *globals, char *buf,
2099 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002100static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002101 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002102static int mark_miss(char *name);
2103static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002104 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002105static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002106
2107/* The Magnum Opus of dotted-name import :-) */
2108
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002109static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002110import_module_level(char *name, PyObject *globals, PyObject *locals,
2111 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002112{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002113 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002114 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002115 PyObject *parent, *head, *next, *tail;
2116
Christian Heimes3403f152008-01-09 19:56:33 +00002117 if (strchr(name, '/') != NULL
2118#ifdef MS_WINDOWS
2119 || strchr(name, '\\') != NULL
2120#endif
2121 ) {
2122 PyErr_SetString(PyExc_ImportError,
2123 "Import by filename is not supported.");
2124 return NULL;
2125 }
2126
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002127 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002128 if (parent == NULL)
2129 return NULL;
2130
2131 head = load_next(parent, Py_None, &name, buf, &buflen);
2132 if (head == NULL)
2133 return NULL;
2134
2135 tail = head;
2136 Py_INCREF(tail);
2137 while (name) {
2138 next = load_next(tail, tail, &name, buf, &buflen);
2139 Py_DECREF(tail);
2140 if (next == NULL) {
2141 Py_DECREF(head);
2142 return NULL;
2143 }
2144 tail = next;
2145 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002146 if (tail == Py_None) {
2147 /* If tail is Py_None, both get_parent and load_next found
2148 an empty module name: someone called __import__("") or
2149 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002150 Py_DECREF(tail);
2151 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002152 PyErr_SetString(PyExc_ValueError,
2153 "Empty module name");
2154 return NULL;
2155 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002156
2157 if (fromlist != NULL) {
2158 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2159 fromlist = NULL;
2160 }
2161
2162 if (fromlist == NULL) {
2163 Py_DECREF(tail);
2164 return head;
2165 }
2166
2167 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002168 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002169 Py_DECREF(tail);
2170 return NULL;
2171 }
2172
2173 return tail;
2174}
2175
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002176PyObject *
2177PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2178 PyObject *fromlist, int level)
2179{
2180 PyObject *result;
2181 lock_import();
2182 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002183 if (unlock_import() < 0) {
2184 Py_XDECREF(result);
2185 PyErr_SetString(PyExc_RuntimeError,
2186 "not holding the import lock");
2187 return NULL;
2188 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002189 return result;
2190}
2191
Fred Drake87590902004-05-28 20:21:36 +00002192/* Return the package that an import is being performed in. If globals comes
2193 from the module foo.bar.bat (not itself a package), this returns the
2194 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002195 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002196
2197 The *name* of the returned package is returned in buf, with the length of
2198 the name in *p_buflen.
2199
2200 If globals doesn't come from a package or a module in a package, or a
2201 corresponding entry is not found in sys.modules, Py_None is returned.
2202*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002203static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002204get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002205{
2206 static PyObject *namestr = NULL;
2207 static PyObject *pathstr = NULL;
Nick Coghlanef01d822007-12-03 12:55:17 +00002208 static PyObject *pkgstr = NULL;
2209 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Nick Coghlanb028f502008-07-13 14:52:36 +00002210 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002211
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002212 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002213 return Py_None;
2214
2215 if (namestr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002216 namestr = PyString_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002217 if (namestr == NULL)
2218 return NULL;
2219 }
2220 if (pathstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002221 pathstr = PyString_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002222 if (pathstr == NULL)
2223 return NULL;
2224 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002225 if (pkgstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002226 pkgstr = PyString_InternFromString("__package__");
Nick Coghlanef01d822007-12-03 12:55:17 +00002227 if (pkgstr == NULL)
2228 return NULL;
2229 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002230
2231 *buf = '\0';
2232 *p_buflen = 0;
Nick Coghlanef01d822007-12-03 12:55:17 +00002233 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002234
Nick Coghlanef01d822007-12-03 12:55:17 +00002235 if ((pkgname != NULL) && (pkgname != Py_None)) {
2236 /* __package__ is set, so use it */
2237 Py_ssize_t len;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002238 if (!PyString_Check(pkgname)) {
Nick Coghlanef01d822007-12-03 12:55:17 +00002239 PyErr_SetString(PyExc_ValueError,
2240 "__package__ set to non-string");
2241 return NULL;
2242 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002243 len = PyString_GET_SIZE(pkgname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002244 if (len == 0) {
2245 if (level > 0) {
2246 PyErr_SetString(PyExc_ValueError,
2247 "Attempted relative import in non-package");
2248 return NULL;
2249 }
2250 return Py_None;
2251 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002252 if (len > MAXPATHLEN) {
2253 PyErr_SetString(PyExc_ValueError,
Nick Coghlanef01d822007-12-03 12:55:17 +00002254 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002255 return NULL;
2256 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002257 strcpy(buf, PyString_AS_STRING(pkgname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002258 } else {
2259 /* __package__ not set, so figure it out and set it */
2260 modname = PyDict_GetItem(globals, namestr);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002261 if (modname == NULL || !PyString_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002262 return Py_None;
Nick Coghlanef01d822007-12-03 12:55:17 +00002263
2264 modpath = PyDict_GetItem(globals, pathstr);
2265 if (modpath != NULL) {
2266 /* __path__ is set, so modname is already the package name */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002267 Py_ssize_t len = PyString_GET_SIZE(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002268 int error;
2269 if (len > MAXPATHLEN) {
2270 PyErr_SetString(PyExc_ValueError,
2271 "Module name too long");
2272 return NULL;
2273 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002274 strcpy(buf, PyString_AS_STRING(modname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002275 error = PyDict_SetItem(globals, pkgstr, modname);
2276 if (error) {
2277 PyErr_SetString(PyExc_ValueError,
2278 "Could not set __package__");
2279 return NULL;
2280 }
2281 } else {
2282 /* Normal module, so work out the package name if any */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002283 char *start = PyString_AS_STRING(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002284 char *lastdot = strrchr(start, '.');
2285 size_t len;
2286 int error;
2287 if (lastdot == NULL && level > 0) {
2288 PyErr_SetString(PyExc_ValueError,
2289 "Attempted relative import in non-package");
2290 return NULL;
2291 }
2292 if (lastdot == NULL) {
2293 error = PyDict_SetItem(globals, pkgstr, Py_None);
2294 if (error) {
2295 PyErr_SetString(PyExc_ValueError,
2296 "Could not set __package__");
2297 return NULL;
2298 }
2299 return Py_None;
2300 }
2301 len = lastdot - start;
2302 if (len >= MAXPATHLEN) {
2303 PyErr_SetString(PyExc_ValueError,
2304 "Module name too long");
2305 return NULL;
2306 }
2307 strncpy(buf, start, len);
2308 buf[len] = '\0';
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002309 pkgname = PyString_FromString(buf);
Nick Coghlanef01d822007-12-03 12:55:17 +00002310 if (pkgname == NULL) {
2311 return NULL;
2312 }
2313 error = PyDict_SetItem(globals, pkgstr, pkgname);
2314 Py_DECREF(pkgname);
2315 if (error) {
2316 PyErr_SetString(PyExc_ValueError,
2317 "Could not set __package__");
2318 return NULL;
2319 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002320 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002321 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002322 while (--level > 0) {
2323 char *dot = strrchr(buf, '.');
2324 if (dot == NULL) {
2325 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002326 "Attempted relative import beyond "
2327 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002328 return NULL;
2329 }
2330 *dot = '\0';
2331 }
2332 *p_buflen = strlen(buf);
2333
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002334 modules = PyImport_GetModuleDict();
2335 parent = PyDict_GetItemString(modules, buf);
Nick Coghlanb028f502008-07-13 14:52:36 +00002336 if (parent == NULL) {
2337 if (orig_level < 1) {
2338 PyObject *err_msg = PyString_FromFormat(
2339 "Parent module '%.200s' not found "
2340 "while handling absolute import", buf);
2341 if (err_msg == NULL) {
2342 return NULL;
2343 }
2344 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2345 PyString_AsString(err_msg), 1)) {
2346 *buf = '\0';
2347 *p_buflen = 0;
2348 parent = Py_None;
2349 }
2350 Py_DECREF(err_msg);
2351 } else {
2352 PyErr_Format(PyExc_SystemError,
2353 "Parent module '%.200s' not loaded, "
2354 "cannot perform relative import", buf);
2355 }
2356 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002357 return parent;
2358 /* We expect, but can't guarantee, if parent != None, that:
2359 - parent.__name__ == buf
2360 - parent.__dict__ is globals
2361 If this is violated... Who cares? */
2362}
2363
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002364/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002365static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002366load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002367 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002368{
2369 char *name = *p_name;
2370 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002371 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002372 char *p;
2373 PyObject *result;
2374
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002375 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002376 /* completely empty module name should only happen in
2377 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002378 Py_INCREF(mod);
2379 *p_name = NULL;
2380 return mod;
2381 }
2382
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002383 if (dot == NULL) {
2384 *p_name = NULL;
2385 len = strlen(name);
2386 }
2387 else {
2388 *p_name = dot+1;
2389 len = dot-name;
2390 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002391 if (len == 0) {
2392 PyErr_SetString(PyExc_ValueError,
2393 "Empty module name");
2394 return NULL;
2395 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002396
2397 p = buf + *p_buflen;
2398 if (p != buf)
2399 *p++ = '.';
2400 if (p+len-buf >= MAXPATHLEN) {
2401 PyErr_SetString(PyExc_ValueError,
2402 "Module name too long");
2403 return NULL;
2404 }
2405 strncpy(p, name, len);
2406 p[len] = '\0';
2407 *p_buflen = p+len-buf;
2408
2409 result = import_submodule(mod, p, buf);
2410 if (result == Py_None && altmod != mod) {
2411 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002412 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002413 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002414 if (result != NULL && result != Py_None) {
2415 if (mark_miss(buf) != 0) {
2416 Py_DECREF(result);
2417 return NULL;
2418 }
2419 strncpy(buf, name, len);
2420 buf[len] = '\0';
2421 *p_buflen = len;
2422 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002423 }
2424 if (result == NULL)
2425 return NULL;
2426
2427 if (result == Py_None) {
2428 Py_DECREF(result);
2429 PyErr_Format(PyExc_ImportError,
2430 "No module named %.200s", name);
2431 return NULL;
2432 }
2433
2434 return result;
2435}
2436
2437static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002438mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002439{
2440 PyObject *modules = PyImport_GetModuleDict();
2441 return PyDict_SetItemString(modules, name, Py_None);
2442}
2443
2444static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002445ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002446 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002447{
2448 int i;
2449
2450 if (!PyObject_HasAttrString(mod, "__path__"))
2451 return 1;
2452
2453 for (i = 0; ; i++) {
2454 PyObject *item = PySequence_GetItem(fromlist, i);
2455 int hasit;
2456 if (item == NULL) {
2457 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2458 PyErr_Clear();
2459 return 1;
2460 }
2461 return 0;
2462 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002463 if (!PyString_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002464 PyErr_SetString(PyExc_TypeError,
2465 "Item in ``from list'' not a string");
2466 Py_DECREF(item);
2467 return 0;
2468 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002469 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002470 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002471 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002472 /* See if the package defines __all__ */
2473 if (recursive)
2474 continue; /* Avoid endless recursion */
2475 all = PyObject_GetAttrString(mod, "__all__");
2476 if (all == NULL)
2477 PyErr_Clear();
2478 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002479 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002480 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002481 if (!ret)
2482 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002483 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002484 continue;
2485 }
2486 hasit = PyObject_HasAttr(mod, item);
2487 if (!hasit) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002488 char *subname = PyString_AS_STRING(item);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002489 PyObject *submod;
2490 char *p;
2491 if (buflen + strlen(subname) >= MAXPATHLEN) {
2492 PyErr_SetString(PyExc_ValueError,
2493 "Module name too long");
2494 Py_DECREF(item);
2495 return 0;
2496 }
2497 p = buf + buflen;
2498 *p++ = '.';
2499 strcpy(p, subname);
2500 submod = import_submodule(mod, subname, buf);
2501 Py_XDECREF(submod);
2502 if (submod == NULL) {
2503 Py_DECREF(item);
2504 return 0;
2505 }
2506 }
2507 Py_DECREF(item);
2508 }
2509
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002510 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002511}
2512
Neil Schemenauer00b09662003-06-16 21:03:07 +00002513static int
2514add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2515 PyObject *modules)
2516{
2517 if (mod == Py_None)
2518 return 1;
2519 /* Irrespective of the success of this load, make a
2520 reference to it in the parent package module. A copy gets
2521 saved in the modules dictionary under the full name, so get a
2522 reference from there, if need be. (The exception is when the
2523 load failed with a SyntaxError -- then there's no trace in
2524 sys.modules. In that case, of course, do nothing extra.) */
2525 if (submod == NULL) {
2526 submod = PyDict_GetItemString(modules, fullname);
2527 if (submod == NULL)
2528 return 1;
2529 }
2530 if (PyModule_Check(mod)) {
2531 /* We can't use setattr here since it can give a
2532 * spurious warning if the submodule name shadows a
2533 * builtin name */
2534 PyObject *dict = PyModule_GetDict(mod);
2535 if (!dict)
2536 return 0;
2537 if (PyDict_SetItemString(dict, subname, submod) < 0)
2538 return 0;
2539 }
2540 else {
2541 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2542 return 0;
2543 }
2544 return 1;
2545}
2546
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002547static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002548import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002549{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002550 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002551 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002552
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002553 /* Require:
2554 if mod == None: subname == fullname
2555 else: mod.__name__ + "." + subname == fullname
2556 */
2557
Tim Peters50d8d372001-02-28 05:34:27 +00002558 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002559 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002560 }
2561 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002562 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002563 char buf[MAXPATHLEN+1];
2564 struct filedescr *fdp;
2565 FILE *fp = NULL;
2566
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002567 if (mod == Py_None)
2568 path = NULL;
2569 else {
2570 path = PyObject_GetAttrString(mod, "__path__");
2571 if (path == NULL) {
2572 PyErr_Clear();
2573 Py_INCREF(Py_None);
2574 return Py_None;
2575 }
2576 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002577
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002578 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002579 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2580 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002581 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002582 if (fdp == NULL) {
2583 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2584 return NULL;
2585 PyErr_Clear();
2586 Py_INCREF(Py_None);
2587 return Py_None;
2588 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002589 m = load_module(fullname, fp, buf, fdp->type, loader);
2590 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002591 if (fp)
2592 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002593 if (!add_submodule(mod, m, fullname, subname, modules)) {
2594 Py_XDECREF(m);
2595 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002596 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002597 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002598
2599 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002600}
2601
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602
2603/* Re-import a module of any kind and return its module object, WITH
2604 INCREMENTED REFERENCE COUNT */
2605
Guido van Rossum79f25d91997-04-29 20:08:16 +00002606PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002607PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002608{
Collin Winter47c52a82007-03-13 23:02:15 +00002609 PyInterpreterState *interp = PyThreadState_Get()->interp;
2610 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002611 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002612 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002613 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002614 char buf[MAXPATHLEN+1];
2615 struct filedescr *fdp;
2616 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002617 PyObject *newm;
Collin Winter47c52a82007-03-13 23:02:15 +00002618
2619 if (modules_reloading == NULL) {
2620 Py_FatalError("PyImport_ReloadModule: "
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002621 "no modules_reloading dictionary!");
Collin Winter47c52a82007-03-13 23:02:15 +00002622 return NULL;
2623 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624
Guido van Rossum79f25d91997-04-29 20:08:16 +00002625 if (m == NULL || !PyModule_Check(m)) {
2626 PyErr_SetString(PyExc_TypeError,
2627 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002628 return NULL;
2629 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002630 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002631 if (name == NULL)
2632 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002633 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002634 PyErr_Format(PyExc_ImportError,
2635 "reload(): module %.200s not in sys.modules",
2636 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002637 return NULL;
2638 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002639 existing_m = PyDict_GetItemString(modules_reloading, name);
2640 if (existing_m != NULL) {
2641 /* Due to a recursive reload, this module is already
2642 being reloaded. */
2643 Py_INCREF(existing_m);
2644 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002645 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002646 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2647 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002648
Guido van Rossum222ef561997-09-06 19:41:09 +00002649 subname = strrchr(name, '.');
2650 if (subname == NULL)
2651 subname = name;
2652 else {
2653 PyObject *parentname, *parent;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002654 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002655 if (parentname == NULL) {
2656 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002657 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002658 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002659 parent = PyDict_GetItem(modules, parentname);
2660 if (parent == NULL) {
2661 PyErr_Format(PyExc_ImportError,
2662 "reload(): parent %.200s not in sys.modules",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002663 PyString_AS_STRING(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002664 Py_DECREF(parentname);
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002665 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002666 return NULL;
2667 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002668 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002669 subname++;
2670 path = PyObject_GetAttrString(parent, "__path__");
2671 if (path == NULL)
2672 PyErr_Clear();
2673 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002674 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002675 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002676 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002677
2678 if (fdp == NULL) {
2679 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002680 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002681 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002682 }
2683
2684 newm = load_module(name, fp, buf, fdp->type, loader);
2685 Py_XDECREF(loader);
2686
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002687 if (fp)
2688 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002689 if (newm == NULL) {
2690 /* load_module probably removed name from modules because of
2691 * the error. Put back the original module object. We're
2692 * going to return NULL in this case regardless of whether
2693 * replacing name succeeds, so the return value is ignored.
2694 */
2695 PyDict_SetItemString(modules, name, m);
2696 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002697 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002698 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002699}
2700
2701
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002702/* Higher-level import emulator which emulates the "import" statement
2703 more accurately -- it invokes the __import__() function from the
2704 builtins of the current globals. This means that the import is
2705 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002706 environment, e.g. by "rexec".
2707 A dummy list ["__doc__"] is passed as the 4th argument so that
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002708 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002709 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002710
2711PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002712PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002713{
2714 static PyObject *silly_list = NULL;
2715 static PyObject *builtins_str = NULL;
2716 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002717 PyObject *globals = NULL;
2718 PyObject *import = NULL;
2719 PyObject *builtins = NULL;
2720 PyObject *r = NULL;
2721
2722 /* Initialize constant string objects */
2723 if (silly_list == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002724 import_str = PyString_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002725 if (import_str == NULL)
2726 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002727 builtins_str = PyString_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002728 if (builtins_str == NULL)
2729 return NULL;
2730 silly_list = Py_BuildValue("[s]", "__doc__");
2731 if (silly_list == NULL)
2732 return NULL;
2733 }
2734
2735 /* Get the builtins from current globals */
2736 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002737 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002738 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002739 builtins = PyObject_GetItem(globals, builtins_str);
2740 if (builtins == NULL)
2741 goto err;
2742 }
2743 else {
2744 /* No globals -- use standard builtins, and fake globals */
2745 PyErr_Clear();
2746
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002747 builtins = PyImport_ImportModuleLevel("__builtin__",
2748 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002749 if (builtins == NULL)
2750 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002751 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2752 if (globals == NULL)
2753 goto err;
2754 }
2755
2756 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002758 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759 if (import == NULL)
2760 PyErr_SetObject(PyExc_KeyError, import_str);
2761 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002762 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002763 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002764 if (import == NULL)
2765 goto err;
2766
Christian Heimes000a0742008-01-03 22:16:32 +00002767 /* Call the __import__ function with the proper argument list
2768 * Always use absolute import here. */
2769 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2770 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002771
2772 err:
2773 Py_XDECREF(globals);
2774 Py_XDECREF(builtins);
2775 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002776
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002777 return r;
2778}
2779
2780
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002781/* Module 'imp' provides Python access to the primitives used for
2782 importing modules.
2783*/
2784
Guido van Rossum79f25d91997-04-29 20:08:16 +00002785static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002786imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002787{
2788 char buf[4];
2789
Guido van Rossum96774c12000-05-01 20:19:08 +00002790 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2791 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2792 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2793 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002794
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002795 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002796}
2797
Guido van Rossum79f25d91997-04-29 20:08:16 +00002798static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002799imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002800{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002801 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002802 struct filedescr *fdp;
2803
Guido van Rossum79f25d91997-04-29 20:08:16 +00002804 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002805 if (list == NULL)
2806 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002807 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2808 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002809 fdp->suffix, fdp->mode, fdp->type);
2810 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002811 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002812 return NULL;
2813 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002814 if (PyList_Append(list, item) < 0) {
2815 Py_DECREF(list);
2816 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002817 return NULL;
2818 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002819 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002820 }
2821 return list;
2822}
2823
Guido van Rossum79f25d91997-04-29 20:08:16 +00002824static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002825call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002826{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002827 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002828 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002829 struct filedescr *fdp;
2830 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002831 FILE *fp = NULL;
2832
2833 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002834 if (path == Py_None)
2835 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002836 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002837 if (fdp == NULL)
2838 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002839 if (fp != NULL) {
2840 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2841 if (fob == NULL) {
2842 fclose(fp);
2843 return NULL;
2844 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002845 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002846 else {
2847 fob = Py_None;
2848 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002849 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002850 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002851 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002852 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002853 return ret;
2854}
2855
Guido van Rossum79f25d91997-04-29 20:08:16 +00002856static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002857imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002858{
2859 char *name;
2860 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002861 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002862 return NULL;
2863 return call_find_module(name, path);
2864}
2865
2866static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002867imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002868{
2869 char *name;
2870 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002871 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002872 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002873 return NULL;
2874 ret = init_builtin(name);
2875 if (ret < 0)
2876 return NULL;
2877 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002878 Py_INCREF(Py_None);
2879 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002880 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002881 m = PyImport_AddModule(name);
2882 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002883 return m;
2884}
2885
Guido van Rossum79f25d91997-04-29 20:08:16 +00002886static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002887imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002888{
2889 char *name;
2890 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002891 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002892 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002893 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002894 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002895 if (ret < 0)
2896 return NULL;
2897 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002898 Py_INCREF(Py_None);
2899 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002900 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002901 m = PyImport_AddModule(name);
2902 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002903 return m;
2904}
2905
Guido van Rossum79f25d91997-04-29 20:08:16 +00002906static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002907imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002908{
2909 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002910
Guido van Rossum43713e52000-02-29 13:59:29 +00002911 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002912 return NULL;
2913 return get_frozen_object(name);
2914}
2915
Guido van Rossum79f25d91997-04-29 20:08:16 +00002916static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002917imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002918{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002919 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002920 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002921 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002922 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002923}
2924
Guido van Rossum79f25d91997-04-29 20:08:16 +00002925static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002926imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002927{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002928 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002929 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002930 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002931 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002932 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002933 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002934}
2935
2936static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002937get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002938{
2939 FILE *fp;
2940 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002941 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002942 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002943 fp = fopen(pathname, mode);
2944 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002945 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002946 }
2947 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002948 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002949 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002950 PyErr_SetString(PyExc_ValueError,
2951 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002952 }
2953 return fp;
2954}
2955
Guido van Rossum79f25d91997-04-29 20:08:16 +00002956static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002957imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002958{
2959 char *name;
2960 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002961 PyObject *fob = NULL;
2962 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002963 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002964 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002965 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002966 return NULL;
2967 fp = get_file(pathname, fob, "rb");
2968 if (fp == NULL)
2969 return NULL;
2970 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002971 if (fob == NULL)
2972 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002973 return m;
2974}
2975
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002976#ifdef HAVE_DYNAMIC_LOADING
2977
Guido van Rossum79f25d91997-04-29 20:08:16 +00002978static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002979imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002980{
2981 char *name;
2982 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002983 PyObject *fob = NULL;
2984 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002985 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002986 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002987 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002988 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002989 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002990 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002991 if (fp == NULL)
2992 return NULL;
2993 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002994 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002995 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002996}
2997
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002998#endif /* HAVE_DYNAMIC_LOADING */
2999
Guido van Rossum79f25d91997-04-29 20:08:16 +00003000static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003001imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003002{
3003 char *name;
3004 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003005 PyObject *fob = NULL;
3006 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003007 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00003008 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00003009 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003010 return NULL;
3011 fp = get_file(pathname, fob, "r");
3012 if (fp == NULL)
3013 return NULL;
3014 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003015 if (fob == NULL)
3016 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003017 return m;
3018}
3019
Guido van Rossum79f25d91997-04-29 20:08:16 +00003020static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003021imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003022{
3023 char *name;
3024 PyObject *fob;
3025 char *pathname;
3026 char *suffix; /* Unused */
3027 char *mode;
3028 int type;
3029 FILE *fp;
3030
Guido van Rossum43713e52000-02-29 13:59:29 +00003031 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003032 &name, &fob, &pathname,
3033 &suffix, &mode, &type))
3034 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003035 if (*mode) {
3036 /* Mode must start with 'r' or 'U' and must not contain '+'.
3037 Implicit in this test is the assumption that the mode
3038 may contain other modifiers like 'b' or 't'. */
3039
3040 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00003041 PyErr_Format(PyExc_ValueError,
3042 "invalid file open mode %.200s", mode);
3043 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003044 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003045 }
3046 if (fob == Py_None)
3047 fp = NULL;
3048 else {
3049 if (!PyFile_Check(fob)) {
3050 PyErr_SetString(PyExc_ValueError,
3051 "load_module arg#2 should be a file or None");
3052 return NULL;
3053 }
3054 fp = get_file(pathname, fob, mode);
3055 if (fp == NULL)
3056 return NULL;
3057 }
Just van Rossum52e14d62002-12-30 22:08:05 +00003058 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003059}
3060
3061static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003062imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003063{
3064 char *name;
3065 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00003066 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003067 return NULL;
3068 return load_package(name, pathname);
3069}
3070
3071static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003072imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003073{
3074 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003075 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003076 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003077 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003078}
3079
Brett Cannon3aa2a492008-08-06 22:28:09 +00003080static PyObject *
3081imp_reload(PyObject *self, PyObject *v)
3082{
3083 return PyImport_ReloadModule(v);
3084}
3085
3086
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003087/* Doc strings */
3088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003089PyDoc_STRVAR(doc_imp,
3090"This module provides the components needed to build your own\n\
3091__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003092
Brett Cannon3aa2a492008-08-06 22:28:09 +00003093PyDoc_STRVAR(doc_reload,
3094"reload(module) -> module\n\
3095\n\
3096Reload the module. The module must have been successfully imported before.");
3097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003098PyDoc_STRVAR(doc_find_module,
3099"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003100Search for a module. If path is omitted or None, search for a\n\
3101built-in, frozen or special module and continue search in sys.path.\n\
3102The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003103package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003105PyDoc_STRVAR(doc_load_module,
3106"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003107Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003108The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003110PyDoc_STRVAR(doc_get_magic,
3111"get_magic() -> string\n\
3112Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003114PyDoc_STRVAR(doc_get_suffixes,
3115"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003116Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003117that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003119PyDoc_STRVAR(doc_new_module,
3120"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003121Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003122The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003124PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003125"lock_held() -> boolean\n\
3126Return True if the import lock is currently held, else False.\n\
3127On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003128
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003129PyDoc_STRVAR(doc_acquire_lock,
3130"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003131Acquires the interpreter's import lock for the current thread.\n\
3132This lock should be used by import hooks to ensure thread-safety\n\
3133when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003134On platforms without threads, this function does nothing.");
3135
3136PyDoc_STRVAR(doc_release_lock,
3137"release_lock() -> None\n\
3138Release the interpreter's import lock.\n\
3139On platforms without threads, this function does nothing.");
3140
Guido van Rossum79f25d91997-04-29 20:08:16 +00003141static PyMethodDef imp_methods[] = {
Brett Cannon3aa2a492008-08-06 22:28:09 +00003142 {"reload", imp_reload, METH_O, doc_reload},
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003143 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3144 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3145 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3146 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3147 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3148 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3149 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3150 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003151 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003152 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3153 {"init_builtin", imp_init_builtin, METH_VARARGS},
3154 {"init_frozen", imp_init_frozen, METH_VARARGS},
3155 {"is_builtin", imp_is_builtin, METH_VARARGS},
3156 {"is_frozen", imp_is_frozen, METH_VARARGS},
3157 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003158#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003159 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003160#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003161 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003162 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003163 {NULL, NULL} /* sentinel */
3164};
3165
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003166static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003167setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003168{
3169 PyObject *v;
3170 int err;
3171
3172 v = PyInt_FromLong((long)value);
3173 err = PyDict_SetItemString(d, name, v);
3174 Py_XDECREF(v);
3175 return err;
3176}
3177
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003178typedef struct {
3179 PyObject_HEAD
3180} NullImporter;
3181
3182static int
3183NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3184{
3185 char *path;
Christian Heimescea681b2007-11-07 17:50:54 +00003186 Py_ssize_t pathlen;
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003187
3188 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3189 return -1;
3190
3191 if (!PyArg_ParseTuple(args, "s:NullImporter",
3192 &path))
3193 return -1;
3194
Christian Heimescea681b2007-11-07 17:50:54 +00003195 pathlen = strlen(path);
3196 if (pathlen == 0) {
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003197 PyErr_SetString(PyExc_ImportError, "empty pathname");
3198 return -1;
3199 } else {
3200#ifndef RISCOS
Kristján Valur Jónsson3b2a6b82009-01-09 20:10:59 +00003201#ifndef MS_WINDOWS
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003202 struct stat statbuf;
3203 int rv;
3204
3205 rv = stat(path, &statbuf);
3206 if (rv == 0) {
3207 /* it exists */
3208 if (S_ISDIR(statbuf.st_mode)) {
3209 /* it's a directory */
3210 PyErr_SetString(PyExc_ImportError,
3211 "existing directory");
3212 return -1;
3213 }
3214 }
Kristján Valur Jónsson3b2a6b82009-01-09 20:10:59 +00003215#else /* MS_WINDOWS */
3216 DWORD rv;
3217 /* see issue1293 and issue3677:
3218 * stat() on Windows doesn't recognise paths like
3219 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3220 */
3221 rv = GetFileAttributesA(path);
3222 if (rv != INVALID_FILE_ATTRIBUTES) {
3223 /* it exists */
3224 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3225 /* it's a directory */
3226 PyErr_SetString(PyExc_ImportError,
3227 "existing directory");
3228 return -1;
3229 }
3230 }
3231#endif
3232#else /* RISCOS */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003233 if (object_exists(path)) {
3234 /* it exists */
3235 if (isdir(path)) {
3236 /* it's a directory */
3237 PyErr_SetString(PyExc_ImportError,
3238 "existing directory");
3239 return -1;
3240 }
3241 }
3242#endif
3243 }
3244 return 0;
3245}
3246
3247static PyObject *
3248NullImporter_find_module(NullImporter *self, PyObject *args)
3249{
3250 Py_RETURN_NONE;
3251}
3252
3253static PyMethodDef NullImporter_methods[] = {
3254 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3255 "Always return None"
3256 },
3257 {NULL} /* Sentinel */
3258};
3259
3260
Nick Coghlan327a39b2007-11-18 11:56:28 +00003261PyTypeObject PyNullImporter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003262 PyVarObject_HEAD_INIT(NULL, 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003263 "imp.NullImporter", /*tp_name*/
3264 sizeof(NullImporter), /*tp_basicsize*/
3265 0, /*tp_itemsize*/
3266 0, /*tp_dealloc*/
3267 0, /*tp_print*/
3268 0, /*tp_getattr*/
3269 0, /*tp_setattr*/
3270 0, /*tp_compare*/
3271 0, /*tp_repr*/
3272 0, /*tp_as_number*/
3273 0, /*tp_as_sequence*/
3274 0, /*tp_as_mapping*/
3275 0, /*tp_hash */
3276 0, /*tp_call*/
3277 0, /*tp_str*/
3278 0, /*tp_getattro*/
3279 0, /*tp_setattro*/
3280 0, /*tp_as_buffer*/
3281 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3282 "Null importer object", /* tp_doc */
3283 0, /* tp_traverse */
3284 0, /* tp_clear */
3285 0, /* tp_richcompare */
3286 0, /* tp_weaklistoffset */
3287 0, /* tp_iter */
3288 0, /* tp_iternext */
3289 NullImporter_methods, /* tp_methods */
3290 0, /* tp_members */
3291 0, /* tp_getset */
3292 0, /* tp_base */
3293 0, /* tp_dict */
3294 0, /* tp_descr_get */
3295 0, /* tp_descr_set */
3296 0, /* tp_dictoffset */
3297 (initproc)NullImporter_init, /* tp_init */
3298 0, /* tp_alloc */
3299 PyType_GenericNew /* tp_new */
3300};
3301
3302
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003303PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003304initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003305{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003306 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003307
Nick Coghlan327a39b2007-11-18 11:56:28 +00003308 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003309 goto failure;
3310
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003311 m = Py_InitModule4("imp", imp_methods, doc_imp,
3312 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003313 if (m == NULL)
3314 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003315 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003316 if (d == NULL)
3317 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003318
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003319 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3320 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3321 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3322 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3323 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3324 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3325 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3326 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003327 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003328 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003329
Nick Coghlan327a39b2007-11-18 11:56:28 +00003330 Py_INCREF(&PyNullImporter_Type);
3331 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003332 failure:
3333 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003334}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003335
3336
Guido van Rossumb18618d2000-05-03 23:44:39 +00003337/* API for embedding applications that want to add their own entries
3338 to the table of built-in modules. This should normally be called
3339 *before* Py_Initialize(). When the table resize fails, -1 is
3340 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003341
3342 After a similar function by Just van Rossum. */
3343
3344int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003345PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003346{
3347 static struct _inittab *our_copy = NULL;
3348 struct _inittab *p;
3349 int i, n;
3350
3351 /* Count the number of entries in both tables */
3352 for (n = 0; newtab[n].name != NULL; n++)
3353 ;
3354 if (n == 0)
3355 return 0; /* Nothing to do */
3356 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3357 ;
3358
3359 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003360 p = our_copy;
3361 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003362 if (p == NULL)
3363 return -1;
3364
3365 /* Copy the tables into the new memory */
3366 if (our_copy != PyImport_Inittab)
3367 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3368 PyImport_Inittab = our_copy = p;
3369 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3370
3371 return 0;
3372}
3373
3374/* Shorthand to add a single entry given a name and a function */
3375
3376int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003377PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003378{
3379 struct _inittab newtab[2];
3380
3381 memset(newtab, '\0', sizeof newtab);
3382
3383 newtab[0].name = name;
3384 newtab[0].initfunc = initfunc;
3385
3386 return PyImport_ExtendInittab(newtab);
3387}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003388
3389#ifdef __cplusplus
3390}
3391#endif