blob: 08024b21dbe42acfedaeeac8c428d4cc06dbaaba [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
912
913/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000914 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
915 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916
Guido van Rossum79f25d91997-04-29 20:08:16 +0000917static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000918load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000919{
Christian Heimes40346852008-02-23 17:52:07 +0000920 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921 FILE *fpc;
922 char buf[MAXPATHLEN+1];
923 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000924 PyCodeObject *co;
925 PyObject *m;
Christian Heimes40346852008-02-23 17:52:07 +0000926
927 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000928 PyErr_Format(PyExc_RuntimeError,
Christian Heimes40346852008-02-23 17:52:07 +0000929 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000930 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000931 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000932 }
Fred Drake4c82b232000-06-30 16:18:57 +0000933#if SIZEOF_TIME_T > 4
934 /* Python's .pyc timestamp handling presumes that the timestamp fits
935 in 4 bytes. This will be fine until sometime in the year 2038,
936 when a 4-byte signed time_t will overflow.
937 */
Christian Heimes40346852008-02-23 17:52:07 +0000938 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000939 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000940 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000941 return NULL;
942 }
943#endif
Tim Peters36515e22001-11-18 04:06:29 +0000944 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000945 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000946 if (cpathname != NULL &&
Christian Heimes40346852008-02-23 17:52:07 +0000947 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000948 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949 fclose(fpc);
950 if (co == NULL)
951 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000952 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000953 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000954 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000955 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000956 }
957 else {
958 co = parse_source_module(pathname, fp);
959 if (co == NULL)
960 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000961 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000962 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000963 name, pathname);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000964 if (cpathname) {
965 PyObject *ro = PySys_GetObject("dont_write_bytecode");
966 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes40346852008-02-23 17:52:07 +0000967 write_compiled_module(co, cpathname, &st);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000968 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000969 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000970 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000971 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000972
973 return m;
974}
975
976
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000977/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000978static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
979static struct filedescr *find_module(char *, char *, PyObject *,
980 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000981static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000982
983/* Load a package and return its module object WITH INCREMENTED
984 REFERENCE COUNT */
985
986static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000987load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000988{
Tim Peters1cd70172004-08-02 03:52:12 +0000989 PyObject *m, *d;
990 PyObject *file = NULL;
991 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000992 int err;
993 char buf[MAXPATHLEN+1];
994 FILE *fp = NULL;
995 struct filedescr *fdp;
996
997 m = PyImport_AddModule(name);
998 if (m == NULL)
999 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001000 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001001 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001002 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001003 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001004 file = PyString_FromString(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001005 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001006 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001007 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001008 if (path == NULL)
1009 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001010 err = PyDict_SetItemString(d, "__file__", file);
1011 if (err == 0)
1012 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001013 if (err != 0)
1014 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001015 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001016 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017 if (fdp == NULL) {
1018 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1019 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001020 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001021 }
1022 else
1023 m = NULL;
1024 goto cleanup;
1025 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001026 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027 if (fp != NULL)
1028 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001029 goto cleanup;
1030
1031 error:
1032 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001033 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001034 Py_XDECREF(path);
1035 Py_XDECREF(file);
1036 return m;
1037}
1038
1039
1040/* Helper to test for built-in module */
1041
1042static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001043is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001044{
1045 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001046 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1047 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1048 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001049 return -1;
1050 else
1051 return 1;
1052 }
1053 }
1054 return 0;
1055}
1056
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001057
Just van Rossum52e14d62002-12-30 22:08:05 +00001058/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1059 possibly by fetching it from the path_importer_cache dict. If it
Brett Cannon94b69f62006-09-28 22:10:14 +00001060 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001061 that can handle the path item. Return None if no hook could;
1062 this tells our caller it should fall back to the builtin
1063 import mechanism. Cache the result in path_importer_cache.
1064 Returns a borrowed reference. */
1065
1066static PyObject *
1067get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1068 PyObject *p)
1069{
1070 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001071 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001072
1073 /* These conditions are the caller's responsibility: */
1074 assert(PyList_Check(path_hooks));
1075 assert(PyDict_Check(path_importer_cache));
1076
1077 nhooks = PyList_Size(path_hooks);
1078 if (nhooks < 0)
1079 return NULL; /* Shouldn't happen */
1080
1081 importer = PyDict_GetItem(path_importer_cache, p);
1082 if (importer != NULL)
1083 return importer;
1084
1085 /* set path_importer_cache[p] to None to avoid recursion */
1086 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1087 return NULL;
1088
1089 for (j = 0; j < nhooks; j++) {
1090 PyObject *hook = PyList_GetItem(path_hooks, j);
1091 if (hook == NULL)
1092 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001093 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001094 if (importer != NULL)
1095 break;
1096
1097 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1098 return NULL;
1099 }
1100 PyErr_Clear();
1101 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001102 if (importer == NULL) {
1103 importer = PyObject_CallFunctionObjArgs(
Nick Coghlan327a39b2007-11-18 11:56:28 +00001104 (PyObject *)&PyNullImporter_Type, p, NULL
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001105 );
1106 if (importer == NULL) {
1107 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1108 PyErr_Clear();
1109 return Py_None;
1110 }
1111 }
1112 }
1113 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001114 int err = PyDict_SetItem(path_importer_cache, p, importer);
1115 Py_DECREF(importer);
1116 if (err != 0)
1117 return NULL;
1118 }
1119 return importer;
1120}
1121
Nick Coghlan327a39b2007-11-18 11:56:28 +00001122PyAPI_FUNC(PyObject *)
1123PyImport_GetImporter(PyObject *path) {
1124 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1125
1126 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1127 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1128 importer = get_path_importer(path_importer_cache,
1129 path_hooks, path);
1130 }
1131 }
1132 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1133 return importer;
1134}
1135
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001136/* Search the path (default sys.path) for a module. Return the
1137 corresponding filedescr struct, and (via return arguments) the
1138 pathname and an open file. Return NULL if the module is not found. */
1139
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001140#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001141extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001142 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001143#endif
1144
Martin v. Löwis18e16552006-02-15 17:27:45 +00001145static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001146static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001147static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001148
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001149static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001150find_module(char *fullname, char *subname, PyObject *path, char *buf,
1151 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001153 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001154 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001155 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001156 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001157 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001158 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001159#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001160 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001161#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001162 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1163 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1164 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001165 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001166#if defined(PYOS_OS2)
1167 size_t saved_len;
1168 size_t saved_namelen;
1169 char *saved_buf = NULL;
1170#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001171 if (p_loader != NULL)
1172 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001173
Just van Rossum52e14d62002-12-30 22:08:05 +00001174 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001175 PyErr_SetString(PyExc_OverflowError,
1176 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001177 return NULL;
1178 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001179 strcpy(name, subname);
1180
1181 /* sys.meta_path import hook */
1182 if (p_loader != NULL) {
1183 PyObject *meta_path;
1184
1185 meta_path = PySys_GetObject("meta_path");
1186 if (meta_path == NULL || !PyList_Check(meta_path)) {
1187 PyErr_SetString(PyExc_ImportError,
1188 "sys.meta_path must be a list of "
1189 "import hooks");
1190 return NULL;
1191 }
1192 Py_INCREF(meta_path); /* zap guard */
1193 npath = PyList_Size(meta_path);
1194 for (i = 0; i < npath; i++) {
1195 PyObject *loader;
1196 PyObject *hook = PyList_GetItem(meta_path, i);
1197 loader = PyObject_CallMethod(hook, "find_module",
1198 "sO", fullname,
1199 path != NULL ?
1200 path : Py_None);
1201 if (loader == NULL) {
1202 Py_DECREF(meta_path);
1203 return NULL; /* true error */
1204 }
1205 if (loader != Py_None) {
1206 /* a loader was found */
1207 *p_loader = loader;
1208 Py_DECREF(meta_path);
1209 return &importhookdescr;
1210 }
1211 Py_DECREF(loader);
1212 }
1213 Py_DECREF(meta_path);
1214 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001215
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001216 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001217 /* The only type of submodule allowed inside a "frozen"
1218 package are other frozen modules or packages. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001219 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001220 PyErr_SetString(PyExc_ImportError,
1221 "full frozen module name too long");
1222 return NULL;
1223 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001224 strcpy(buf, PyString_AsString(path));
Guido van Rossum0506a431998-08-11 15:07:39 +00001225 strcat(buf, ".");
1226 strcat(buf, name);
1227 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001228 if (find_frozen(name) != NULL) {
1229 strcpy(buf, name);
1230 return &fd_frozen;
1231 }
1232 PyErr_Format(PyExc_ImportError,
1233 "No frozen submodule named %.200s", name);
1234 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001235 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001236 if (path == NULL) {
1237 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001238 strcpy(buf, name);
1239 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001240 }
Greg Ward201baee2001-10-04 14:52:06 +00001241 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001242 strcpy(buf, name);
1243 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001244 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245
Guido van Rossumac279101996-08-22 23:10:58 +00001246#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001247 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1248 if (fp != NULL) {
1249 *p_fp = fp;
1250 return fdp;
1251 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001252#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001253 path = PySys_GetObject("path");
1254 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001255 if (path == NULL || !PyList_Check(path)) {
1256 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001257 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001258 return NULL;
1259 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001260
1261 path_hooks = PySys_GetObject("path_hooks");
1262 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1263 PyErr_SetString(PyExc_ImportError,
1264 "sys.path_hooks must be a list of "
1265 "import hooks");
1266 return NULL;
1267 }
1268 path_importer_cache = PySys_GetObject("path_importer_cache");
1269 if (path_importer_cache == NULL ||
1270 !PyDict_Check(path_importer_cache)) {
1271 PyErr_SetString(PyExc_ImportError,
1272 "sys.path_importer_cache must be a dict");
1273 return NULL;
1274 }
1275
Guido van Rossum79f25d91997-04-29 20:08:16 +00001276 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277 namelen = strlen(name);
1278 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001279 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001280 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001281 if (!v)
1282 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001283#ifdef Py_USING_UNICODE
1284 if (PyUnicode_Check(v)) {
1285 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1286 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1287 if (copy == NULL)
1288 return NULL;
1289 v = copy;
1290 }
1291 else
1292#endif
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001293 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001294 continue;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001295 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001296 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1297 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001298 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001299 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001300 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001301 if (strlen(buf) != len) {
1302 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001303 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001304 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001305
1306 /* sys.path_hooks import hook */
1307 if (p_loader != NULL) {
1308 PyObject *importer;
1309
1310 importer = get_path_importer(path_importer_cache,
1311 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001312 if (importer == NULL) {
1313 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001314 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001315 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001316 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001317 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001318 PyObject *loader;
1319 loader = PyObject_CallMethod(importer,
1320 "find_module",
1321 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001322 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001323 if (loader == NULL)
1324 return NULL; /* error */
1325 if (loader != Py_None) {
1326 /* a loader was found */
1327 *p_loader = loader;
1328 return &importhookdescr;
1329 }
1330 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001331 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001332 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001333 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001334 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001335
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001336 if (len > 0 && buf[len-1] != SEP
1337#ifdef ALTSEP
1338 && buf[len-1] != ALTSEP
1339#endif
1340 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001341 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001342 strcpy(buf+len, name);
1343 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001344
1345 /* Check for package import (buf holds a directory name,
1346 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001347#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001348 if (stat(buf, &statbuf) == 0 && /* it exists */
1349 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001350 case_ok(buf, len, namelen, name)) { /* case matches */
1351 if (find_init_module(buf)) { /* and has __init__.py */
1352 Py_XDECREF(copy);
1353 return &fd_package;
1354 }
1355 else {
1356 char warnstr[MAXPATHLEN+80];
1357 sprintf(warnstr, "Not importing directory "
1358 "'%.*s': missing __init__.py",
1359 MAXPATHLEN, buf);
1360 if (PyErr_Warn(PyExc_ImportWarning,
1361 warnstr)) {
1362 Py_XDECREF(copy);
1363 return NULL;
1364 }
1365 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001366 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001367#else
1368 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001369#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001370 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001371 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001372 if (find_init_module(buf)) {
1373 Py_XDECREF(copy);
1374 return &fd_package;
1375 }
1376 else {
1377 char warnstr[MAXPATHLEN+80];
1378 sprintf(warnstr, "Not importing directory "
1379 "'%.*s': missing __init__.py",
1380 MAXPATHLEN, buf);
1381 if (PyErr_Warn(PyExc_ImportWarning,
1382 warnstr)) {
1383 Py_XDECREF(copy);
1384 return NULL;
1385 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001386 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001387#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001388#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001389#if defined(PYOS_OS2)
1390 /* take a snapshot of the module spec for restoration
1391 * after the 8 character DLL hackery
1392 */
1393 saved_buf = strdup(buf);
1394 saved_len = len;
1395 saved_namelen = namelen;
1396#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001397 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Georg Brandladd36e52007-08-23 18:08:06 +00001398#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001399 /* OS/2 limits DLLs to 8 character names (w/o
1400 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001401 * so if the name is longer than that and its a
1402 * dynamically loaded module we're going to try,
1403 * truncate the name before trying
1404 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001405 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001406 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001407 const struct filedescr *scan;
1408 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001409 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001410 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001411 break;
1412 else
1413 scan++;
1414 }
1415 if (scan->suffix != NULL) {
1416 /* yes, so truncate the name */
1417 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001418 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001419 buf[len] = '\0';
1420 }
1421 }
1422#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001423 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001424 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001425 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001426 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001427 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001428 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001429 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001430 if (fp != NULL) {
1431 if (case_ok(buf, len, namelen, name))
1432 break;
1433 else { /* continue search */
1434 fclose(fp);
1435 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001436 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001437 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001438#if defined(PYOS_OS2)
1439 /* restore the saved snapshot */
1440 strcpy(buf, saved_buf);
1441 len = saved_len;
1442 namelen = saved_namelen;
1443#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001444 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001445#if defined(PYOS_OS2)
1446 /* don't need/want the module name snapshot anymore */
1447 if (saved_buf)
1448 {
1449 free(saved_buf);
1450 saved_buf = NULL;
1451 }
1452#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001453 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001454 if (fp != NULL)
1455 break;
1456 }
1457 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001458 PyErr_Format(PyExc_ImportError,
1459 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001460 return NULL;
1461 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001462 *p_fp = fp;
1463 return fdp;
1464}
1465
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001466/* Helpers for main.c
1467 * Find the source file corresponding to a named module
1468 */
1469struct filedescr *
1470_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1471 size_t buflen, FILE **p_fp, PyObject **p_loader)
1472{
1473 return find_module((char *) name, (char *) name, path,
1474 buf, buflen, p_fp, p_loader);
1475}
1476
1477PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1478{
1479 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1480}
1481
Martin v. Löwis18e16552006-02-15 17:27:45 +00001482/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001483 * The arguments here are tricky, best shown by example:
1484 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1485 * ^ ^ ^ ^
1486 * |--------------------- buf ---------------------|
1487 * |------------------- len ------------------|
1488 * |------ name -------|
1489 * |----- namelen -----|
1490 * buf is the full path, but len only counts up to (& exclusive of) the
1491 * extension. name is the module name, also exclusive of extension.
1492 *
1493 * We've already done a successful stat() or fopen() on buf, so know that
1494 * there's some match, possibly case-insensitive.
1495 *
Tim Peters50d8d372001-02-28 05:34:27 +00001496 * case_ok() is to return 1 if there's a case-sensitive match for
1497 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1498 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001499 *
Tim Peters50d8d372001-02-28 05:34:27 +00001500 * case_ok() is used to implement case-sensitive import semantics even
1501 * on platforms with case-insensitive filesystems. It's trivial to implement
1502 * for case-sensitive filesystems. It's pretty much a cross-platform
1503 * nightmare for systems with case-insensitive filesystems.
1504 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001505
Tim Peters50d8d372001-02-28 05:34:27 +00001506/* First we may need a pile of platform-specific header files; the sequence
1507 * of #if's here should match the sequence in the body of case_ok().
1508 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001509#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001510#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001511
Tim Peters50d8d372001-02-28 05:34:27 +00001512#elif defined(DJGPP)
1513#include <dir.h>
1514
Jason Tishler7961aa62005-05-20 00:56:54 +00001515#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001516#include <sys/types.h>
1517#include <dirent.h>
1518
Andrew MacIntyred9400542002-02-26 11:41:34 +00001519#elif defined(PYOS_OS2)
1520#define INCL_DOS
1521#define INCL_DOSERRORS
1522#define INCL_NOPMAPI
1523#include <os2.h>
1524
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001525#elif defined(RISCOS)
1526#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001527#endif
1528
Guido van Rossum0980bd91998-02-13 17:18:36 +00001529static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001530case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001531{
Tim Peters50d8d372001-02-28 05:34:27 +00001532/* Pick a platform-specific implementation; the sequence of #if's here should
1533 * match the sequence just above.
1534 */
1535
Jason Tishler7961aa62005-05-20 00:56:54 +00001536/* MS_WINDOWS */
1537#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001538 WIN32_FIND_DATA data;
1539 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001540
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001541 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001542 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001543
Guido van Rossum0980bd91998-02-13 17:18:36 +00001544 h = FindFirstFile(buf, &data);
1545 if (h == INVALID_HANDLE_VALUE) {
1546 PyErr_Format(PyExc_NameError,
1547 "Can't find file for module %.100s\n(filename %.300s)",
1548 name, buf);
1549 return 0;
1550 }
1551 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001552 return strncmp(data.cFileName, name, namelen) == 0;
1553
1554/* DJGPP */
1555#elif defined(DJGPP)
1556 struct ffblk ffblk;
1557 int done;
1558
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001559 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001560 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001561
1562 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1563 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001564 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001565 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001566 name, buf);
1567 return 0;
1568 }
Tim Peters50d8d372001-02-28 05:34:27 +00001569 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001570
Jason Tishler7961aa62005-05-20 00:56:54 +00001571/* new-fangled macintosh (macosx) or Cygwin */
1572#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001573 DIR *dirp;
1574 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001575 char dirname[MAXPATHLEN + 1];
1576 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001577
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001578 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001579 return 1;
1580
Tim Petersd1e87a82001-03-01 18:12:00 +00001581 /* Copy the dir component into dirname; substitute "." if empty */
1582 if (dirlen <= 0) {
1583 dirname[0] = '.';
1584 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001585 }
1586 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001587 assert(dirlen <= MAXPATHLEN);
1588 memcpy(dirname, buf, dirlen);
1589 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001590 }
1591 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001592 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001593 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001594 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001595 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001596 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001597#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001598 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001599#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001600 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001601#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001602 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001603 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001604 (void)closedir(dirp);
1605 return 1; /* Found */
1606 }
1607 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001608 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001609 }
Tim Peters430f5d42001-03-01 01:30:56 +00001610 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001611
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001612/* RISC OS */
1613#elif defined(RISCOS)
1614 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1615 char buf2[MAXPATHLEN+2];
1616 char *nameWithExt = buf+len-namelen;
1617 int canonlen;
1618 os_error *e;
1619
1620 if (Py_GETENV("PYTHONCASEOK") != NULL)
1621 return 1;
1622
1623 /* workaround:
1624 append wildcard, otherwise case of filename wouldn't be touched */
1625 strcpy(buf2, buf);
1626 strcat(buf2, "*");
1627
1628 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1629 canonlen = MAXPATHLEN+1-canonlen;
1630 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1631 return 0;
1632 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1633 return 1; /* match */
1634
1635 return 0;
1636
Andrew MacIntyred9400542002-02-26 11:41:34 +00001637/* OS/2 */
1638#elif defined(PYOS_OS2)
1639 HDIR hdir = 1;
1640 ULONG srchcnt = 1;
1641 FILEFINDBUF3 ffbuf;
1642 APIRET rc;
1643
Georg Brandlaed6c662008-01-07 17:25:53 +00001644 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001645 return 1;
1646
1647 rc = DosFindFirst(buf,
1648 &hdir,
1649 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1650 &ffbuf, sizeof(ffbuf),
1651 &srchcnt,
1652 FIL_STANDARD);
1653 if (rc != NO_ERROR)
1654 return 0;
1655 return strncmp(ffbuf.achName, name, namelen) == 0;
1656
Tim Peters50d8d372001-02-28 05:34:27 +00001657/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1658#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001659 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001660
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001661#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001662}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001663
Guido van Rossum0980bd91998-02-13 17:18:36 +00001664
Guido van Rossum197346f1997-10-31 18:38:52 +00001665#ifdef HAVE_STAT
1666/* Helper to look for __init__.py or __init__.py[co] in potential package */
1667static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001668find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001669{
Tim Peters0f9431f2001-07-05 03:47:53 +00001670 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001671 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001672 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001673 struct stat statbuf;
1674
Tim Peters0f9431f2001-07-05 03:47:53 +00001675/* For calling case_ok(buf, len, namelen, name):
1676 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1677 * ^ ^ ^ ^
1678 * |--------------------- buf ---------------------|
1679 * |------------------- len ------------------|
1680 * |------ name -------|
1681 * |----- namelen -----|
1682 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001683 if (save_len + 13 >= MAXPATHLEN)
1684 return 0;
1685 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001686 pname = buf + i;
1687 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001688 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001689 if (case_ok(buf,
1690 save_len + 9, /* len("/__init__") */
1691 8, /* len("__init__") */
1692 pname)) {
1693 buf[save_len] = '\0';
1694 return 1;
1695 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001696 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001697 i += strlen(pname);
1698 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001699 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001700 if (case_ok(buf,
1701 save_len + 9, /* len("/__init__") */
1702 8, /* len("__init__") */
1703 pname)) {
1704 buf[save_len] = '\0';
1705 return 1;
1706 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001707 }
1708 buf[save_len] = '\0';
1709 return 0;
1710}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001711
1712#else
1713
1714#ifdef RISCOS
1715static int
1716find_init_module(buf)
1717 char *buf;
1718{
1719 int save_len = strlen(buf);
1720 int i = save_len;
1721
1722 if (save_len + 13 >= MAXPATHLEN)
1723 return 0;
1724 buf[i++] = SEP;
1725 strcpy(buf+i, "__init__/py");
1726 if (isfile(buf)) {
1727 buf[save_len] = '\0';
1728 return 1;
1729 }
1730
1731 if (Py_OptimizeFlag)
1732 strcpy(buf+i, "o");
1733 else
1734 strcpy(buf+i, "c");
1735 if (isfile(buf)) {
1736 buf[save_len] = '\0';
1737 return 1;
1738 }
1739 buf[save_len] = '\0';
1740 return 0;
1741}
1742#endif /*RISCOS*/
1743
Guido van Rossum197346f1997-10-31 18:38:52 +00001744#endif /* HAVE_STAT */
1745
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001746
Tim Petersdbd9ba62000-07-09 03:09:57 +00001747static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001748
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001750 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001751
Guido van Rossum79f25d91997-04-29 20:08:16 +00001752static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001753load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001754{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001755 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001756 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001757 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001758
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001759 /* First check that there's an open file (if we need one) */
1760 switch (type) {
1761 case PY_SOURCE:
1762 case PY_COMPILED:
1763 if (fp == NULL) {
1764 PyErr_Format(PyExc_ValueError,
1765 "file object required for import (type code %d)",
1766 type);
1767 return NULL;
1768 }
1769 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001770
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001771 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772
1773 case PY_SOURCE:
1774 m = load_source_module(name, buf, fp);
1775 break;
1776
1777 case PY_COMPILED:
1778 m = load_compiled_module(name, buf, fp);
1779 break;
1780
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001781#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001782 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001783 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001784 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001785#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001786
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001787 case PKG_DIRECTORY:
1788 m = load_package(name, buf);
1789 break;
1790
1791 case C_BUILTIN:
1792 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001793 if (buf != NULL && buf[0] != '\0')
1794 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001795 if (type == C_BUILTIN)
1796 err = init_builtin(name);
1797 else
1798 err = PyImport_ImportFrozenModule(name);
1799 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001800 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001801 if (err == 0) {
1802 PyErr_Format(PyExc_ImportError,
1803 "Purported %s module %.200s not found",
1804 type == C_BUILTIN ?
1805 "builtin" : "frozen",
1806 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001807 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001808 }
1809 modules = PyImport_GetModuleDict();
1810 m = PyDict_GetItemString(modules, name);
1811 if (m == NULL) {
1812 PyErr_Format(
1813 PyExc_ImportError,
1814 "%s module %.200s not properly initialized",
1815 type == C_BUILTIN ?
1816 "builtin" : "frozen",
1817 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001818 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001819 }
1820 Py_INCREF(m);
1821 break;
1822
Just van Rossum52e14d62002-12-30 22:08:05 +00001823 case IMP_HOOK: {
1824 if (loader == NULL) {
1825 PyErr_SetString(PyExc_ImportError,
1826 "import hook without loader");
1827 return NULL;
1828 }
1829 m = PyObject_CallMethod(loader, "load_module", "s", name);
1830 break;
1831 }
1832
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001833 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001834 PyErr_Format(PyExc_ImportError,
1835 "Don't know how to import %.200s (type code %d)",
1836 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001837 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838
1839 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
1841 return m;
1842}
1843
1844
1845/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001846 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001847 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001848
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001849static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001850init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001851{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001852 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001853
Greg Ward201baee2001-10-04 14:52:06 +00001854 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001855 return 1;
1856
Guido van Rossum771c6c81997-10-31 18:37:24 +00001857 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001858 if (strcmp(name, p->name) == 0) {
1859 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001860 PyErr_Format(PyExc_ImportError,
1861 "Cannot re-init internal module %.200s",
1862 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001863 return -1;
1864 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001865 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001866 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001867 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001868 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001869 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001870 if (_PyImport_FixupExtension(name, name) == NULL)
1871 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001872 return 1;
1873 }
1874 }
1875 return 0;
1876}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001877
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001878
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001879/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001880
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001881static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001882find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001883{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001884 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001885
Guido van Rossum79f25d91997-04-29 20:08:16 +00001886 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001887 if (p->name == NULL)
1888 return NULL;
1889 if (strcmp(p->name, name) == 0)
1890 break;
1891 }
1892 return p;
1893}
1894
Guido van Rossum79f25d91997-04-29 20:08:16 +00001895static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001896get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001897{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001898 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001899 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001900
1901 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001902 PyErr_Format(PyExc_ImportError,
1903 "No such frozen object named %.200s",
1904 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001905 return NULL;
1906 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001907 if (p->code == NULL) {
1908 PyErr_Format(PyExc_ImportError,
1909 "Excluded frozen object named %.200s",
1910 name);
1911 return NULL;
1912 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001913 size = p->size;
1914 if (size < 0)
1915 size = -size;
1916 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001917}
1918
1919/* Initialize a frozen module.
1920 Return 1 for succes, 0 if the module is not found, and -1 with
1921 an exception set if the initialization failed.
1922 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001923
1924int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001925PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001926{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001927 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001928 PyObject *co;
1929 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001930 int ispackage;
1931 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001932
1933 if (p == NULL)
1934 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001935 if (p->code == NULL) {
1936 PyErr_Format(PyExc_ImportError,
1937 "Excluded frozen object named %.200s",
1938 name);
1939 return -1;
1940 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001941 size = p->size;
1942 ispackage = (size < 0);
1943 if (ispackage)
1944 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001945 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001946 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001947 name, ispackage ? " package" : "");
1948 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001949 if (co == NULL)
1950 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001951 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001952 PyErr_Format(PyExc_TypeError,
1953 "frozen object %.200s is not a code object",
1954 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001955 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001956 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001957 if (ispackage) {
1958 /* Set __path__ to the package name */
1959 PyObject *d, *s;
1960 int err;
1961 m = PyImport_AddModule(name);
1962 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001963 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001964 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001965 s = PyString_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001966 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001967 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001968 err = PyDict_SetItemString(d, "__path__", s);
1969 Py_DECREF(s);
1970 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001971 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001972 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001973 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001974 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001975 goto err_return;
1976 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001977 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001978 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001979err_return:
1980 Py_DECREF(co);
1981 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001982}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001983
1984
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001985/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001986 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001987
Guido van Rossum79f25d91997-04-29 20:08:16 +00001988PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001989PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001990{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001991 PyObject *pname;
1992 PyObject *result;
1993
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001994 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001995 if (pname == NULL)
1996 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001997 result = PyImport_Import(pname);
1998 Py_DECREF(pname);
1999 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002000}
2001
Christian Heimes000a0742008-01-03 22:16:32 +00002002/* Import a module without blocking
2003 *
2004 * At first it tries to fetch the module from sys.modules. If the module was
2005 * never loaded before it loads it with PyImport_ImportModule() unless another
2006 * thread holds the import lock. In the latter case the function raises an
2007 * ImportError instead of blocking.
2008 *
2009 * Returns the module object with incremented ref count.
2010 */
2011PyObject *
2012PyImport_ImportModuleNoBlock(const char *name)
2013{
2014 PyObject *result;
2015 PyObject *modules;
2016 long me;
2017
2018 /* Try to get the module from sys.modules[name] */
2019 modules = PyImport_GetModuleDict();
2020 if (modules == NULL)
2021 return NULL;
2022
2023 result = PyDict_GetItemString(modules, name);
2024 if (result != NULL) {
2025 Py_INCREF(result);
2026 return result;
2027 }
2028 else {
2029 PyErr_Clear();
2030 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002031#ifdef WITH_THREAD
Christian Heimes000a0742008-01-03 22:16:32 +00002032 /* check the import lock
2033 * me might be -1 but I ignore the error here, the lock function
2034 * takes care of the problem */
2035 me = PyThread_get_thread_ident();
2036 if (import_lock_thread == -1 || import_lock_thread == me) {
2037 /* no thread or me is holding the lock */
2038 return PyImport_ImportModule(name);
2039 }
2040 else {
2041 PyErr_Format(PyExc_ImportError,
2042 "Failed to import %.200s because the import lock"
2043 "is held by another thread.",
2044 name);
2045 return NULL;
2046 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002047#else
2048 return PyImport_ImportModule(name);
2049#endif
Christian Heimes000a0742008-01-03 22:16:32 +00002050}
2051
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002052/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002053static PyObject *get_parent(PyObject *globals, char *buf,
2054 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002055static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002056 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002057static int mark_miss(char *name);
2058static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002059 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002060static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002061
2062/* The Magnum Opus of dotted-name import :-) */
2063
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002064static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002065import_module_level(char *name, PyObject *globals, PyObject *locals,
2066 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002067{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002068 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002069 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002070 PyObject *parent, *head, *next, *tail;
2071
Christian Heimes3403f152008-01-09 19:56:33 +00002072 if (strchr(name, '/') != NULL
2073#ifdef MS_WINDOWS
2074 || strchr(name, '\\') != NULL
2075#endif
2076 ) {
2077 PyErr_SetString(PyExc_ImportError,
2078 "Import by filename is not supported.");
2079 return NULL;
2080 }
2081
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002082 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002083 if (parent == NULL)
2084 return NULL;
2085
2086 head = load_next(parent, Py_None, &name, buf, &buflen);
2087 if (head == NULL)
2088 return NULL;
2089
2090 tail = head;
2091 Py_INCREF(tail);
2092 while (name) {
2093 next = load_next(tail, tail, &name, buf, &buflen);
2094 Py_DECREF(tail);
2095 if (next == NULL) {
2096 Py_DECREF(head);
2097 return NULL;
2098 }
2099 tail = next;
2100 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002101 if (tail == Py_None) {
2102 /* If tail is Py_None, both get_parent and load_next found
2103 an empty module name: someone called __import__("") or
2104 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002105 Py_DECREF(tail);
2106 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002107 PyErr_SetString(PyExc_ValueError,
2108 "Empty module name");
2109 return NULL;
2110 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002111
2112 if (fromlist != NULL) {
2113 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2114 fromlist = NULL;
2115 }
2116
2117 if (fromlist == NULL) {
2118 Py_DECREF(tail);
2119 return head;
2120 }
2121
2122 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002123 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002124 Py_DECREF(tail);
2125 return NULL;
2126 }
2127
2128 return tail;
2129}
2130
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002131PyObject *
2132PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2133 PyObject *fromlist, int level)
2134{
2135 PyObject *result;
2136 lock_import();
2137 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002138 if (unlock_import() < 0) {
2139 Py_XDECREF(result);
2140 PyErr_SetString(PyExc_RuntimeError,
2141 "not holding the import lock");
2142 return NULL;
2143 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002144 return result;
2145}
2146
Fred Drake87590902004-05-28 20:21:36 +00002147/* Return the package that an import is being performed in. If globals comes
2148 from the module foo.bar.bat (not itself a package), this returns the
2149 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002150 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002151
2152 The *name* of the returned package is returned in buf, with the length of
2153 the name in *p_buflen.
2154
2155 If globals doesn't come from a package or a module in a package, or a
2156 corresponding entry is not found in sys.modules, Py_None is returned.
2157*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002158static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002159get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002160{
2161 static PyObject *namestr = NULL;
2162 static PyObject *pathstr = NULL;
Nick Coghlanef01d822007-12-03 12:55:17 +00002163 static PyObject *pkgstr = NULL;
2164 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Nick Coghlanb028f502008-07-13 14:52:36 +00002165 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002166
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002167 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002168 return Py_None;
2169
2170 if (namestr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002171 namestr = PyString_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002172 if (namestr == NULL)
2173 return NULL;
2174 }
2175 if (pathstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002176 pathstr = PyString_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002177 if (pathstr == NULL)
2178 return NULL;
2179 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002180 if (pkgstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002181 pkgstr = PyString_InternFromString("__package__");
Nick Coghlanef01d822007-12-03 12:55:17 +00002182 if (pkgstr == NULL)
2183 return NULL;
2184 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002185
2186 *buf = '\0';
2187 *p_buflen = 0;
Nick Coghlanef01d822007-12-03 12:55:17 +00002188 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002189
Nick Coghlanef01d822007-12-03 12:55:17 +00002190 if ((pkgname != NULL) && (pkgname != Py_None)) {
2191 /* __package__ is set, so use it */
2192 Py_ssize_t len;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002193 if (!PyString_Check(pkgname)) {
Nick Coghlanef01d822007-12-03 12:55:17 +00002194 PyErr_SetString(PyExc_ValueError,
2195 "__package__ set to non-string");
2196 return NULL;
2197 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002198 len = PyString_GET_SIZE(pkgname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002199 if (len == 0) {
2200 if (level > 0) {
2201 PyErr_SetString(PyExc_ValueError,
2202 "Attempted relative import in non-package");
2203 return NULL;
2204 }
2205 return Py_None;
2206 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002207 if (len > MAXPATHLEN) {
2208 PyErr_SetString(PyExc_ValueError,
Nick Coghlanef01d822007-12-03 12:55:17 +00002209 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002210 return NULL;
2211 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002212 strcpy(buf, PyString_AS_STRING(pkgname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002213 } else {
2214 /* __package__ not set, so figure it out and set it */
2215 modname = PyDict_GetItem(globals, namestr);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002216 if (modname == NULL || !PyString_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002217 return Py_None;
Nick Coghlanef01d822007-12-03 12:55:17 +00002218
2219 modpath = PyDict_GetItem(globals, pathstr);
2220 if (modpath != NULL) {
2221 /* __path__ is set, so modname is already the package name */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002222 Py_ssize_t len = PyString_GET_SIZE(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002223 int error;
2224 if (len > MAXPATHLEN) {
2225 PyErr_SetString(PyExc_ValueError,
2226 "Module name too long");
2227 return NULL;
2228 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002229 strcpy(buf, PyString_AS_STRING(modname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002230 error = PyDict_SetItem(globals, pkgstr, modname);
2231 if (error) {
2232 PyErr_SetString(PyExc_ValueError,
2233 "Could not set __package__");
2234 return NULL;
2235 }
2236 } else {
2237 /* Normal module, so work out the package name if any */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002238 char *start = PyString_AS_STRING(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002239 char *lastdot = strrchr(start, '.');
2240 size_t len;
2241 int error;
2242 if (lastdot == NULL && level > 0) {
2243 PyErr_SetString(PyExc_ValueError,
2244 "Attempted relative import in non-package");
2245 return NULL;
2246 }
2247 if (lastdot == NULL) {
2248 error = PyDict_SetItem(globals, pkgstr, Py_None);
2249 if (error) {
2250 PyErr_SetString(PyExc_ValueError,
2251 "Could not set __package__");
2252 return NULL;
2253 }
2254 return Py_None;
2255 }
2256 len = lastdot - start;
2257 if (len >= MAXPATHLEN) {
2258 PyErr_SetString(PyExc_ValueError,
2259 "Module name too long");
2260 return NULL;
2261 }
2262 strncpy(buf, start, len);
2263 buf[len] = '\0';
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002264 pkgname = PyString_FromString(buf);
Nick Coghlanef01d822007-12-03 12:55:17 +00002265 if (pkgname == NULL) {
2266 return NULL;
2267 }
2268 error = PyDict_SetItem(globals, pkgstr, pkgname);
2269 Py_DECREF(pkgname);
2270 if (error) {
2271 PyErr_SetString(PyExc_ValueError,
2272 "Could not set __package__");
2273 return NULL;
2274 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002275 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002276 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002277 while (--level > 0) {
2278 char *dot = strrchr(buf, '.');
2279 if (dot == NULL) {
2280 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002281 "Attempted relative import beyond "
2282 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002283 return NULL;
2284 }
2285 *dot = '\0';
2286 }
2287 *p_buflen = strlen(buf);
2288
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002289 modules = PyImport_GetModuleDict();
2290 parent = PyDict_GetItemString(modules, buf);
Nick Coghlanb028f502008-07-13 14:52:36 +00002291 if (parent == NULL) {
2292 if (orig_level < 1) {
2293 PyObject *err_msg = PyString_FromFormat(
2294 "Parent module '%.200s' not found "
2295 "while handling absolute import", buf);
2296 if (err_msg == NULL) {
2297 return NULL;
2298 }
2299 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2300 PyString_AsString(err_msg), 1)) {
2301 *buf = '\0';
2302 *p_buflen = 0;
2303 parent = Py_None;
2304 }
2305 Py_DECREF(err_msg);
2306 } else {
2307 PyErr_Format(PyExc_SystemError,
2308 "Parent module '%.200s' not loaded, "
2309 "cannot perform relative import", buf);
2310 }
2311 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002312 return parent;
2313 /* We expect, but can't guarantee, if parent != None, that:
2314 - parent.__name__ == buf
2315 - parent.__dict__ is globals
2316 If this is violated... Who cares? */
2317}
2318
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002319/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002320static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002321load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002322 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002323{
2324 char *name = *p_name;
2325 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002326 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002327 char *p;
2328 PyObject *result;
2329
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002330 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002331 /* completely empty module name should only happen in
2332 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002333 Py_INCREF(mod);
2334 *p_name = NULL;
2335 return mod;
2336 }
2337
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002338 if (dot == NULL) {
2339 *p_name = NULL;
2340 len = strlen(name);
2341 }
2342 else {
2343 *p_name = dot+1;
2344 len = dot-name;
2345 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002346 if (len == 0) {
2347 PyErr_SetString(PyExc_ValueError,
2348 "Empty module name");
2349 return NULL;
2350 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002351
2352 p = buf + *p_buflen;
2353 if (p != buf)
2354 *p++ = '.';
2355 if (p+len-buf >= MAXPATHLEN) {
2356 PyErr_SetString(PyExc_ValueError,
2357 "Module name too long");
2358 return NULL;
2359 }
2360 strncpy(p, name, len);
2361 p[len] = '\0';
2362 *p_buflen = p+len-buf;
2363
2364 result = import_submodule(mod, p, buf);
2365 if (result == Py_None && altmod != mod) {
2366 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002367 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002368 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002369 if (result != NULL && result != Py_None) {
2370 if (mark_miss(buf) != 0) {
2371 Py_DECREF(result);
2372 return NULL;
2373 }
2374 strncpy(buf, name, len);
2375 buf[len] = '\0';
2376 *p_buflen = len;
2377 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002378 }
2379 if (result == NULL)
2380 return NULL;
2381
2382 if (result == Py_None) {
2383 Py_DECREF(result);
2384 PyErr_Format(PyExc_ImportError,
2385 "No module named %.200s", name);
2386 return NULL;
2387 }
2388
2389 return result;
2390}
2391
2392static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002393mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002394{
2395 PyObject *modules = PyImport_GetModuleDict();
2396 return PyDict_SetItemString(modules, name, Py_None);
2397}
2398
2399static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002400ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002401 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002402{
2403 int i;
2404
2405 if (!PyObject_HasAttrString(mod, "__path__"))
2406 return 1;
2407
2408 for (i = 0; ; i++) {
2409 PyObject *item = PySequence_GetItem(fromlist, i);
2410 int hasit;
2411 if (item == NULL) {
2412 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2413 PyErr_Clear();
2414 return 1;
2415 }
2416 return 0;
2417 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002418 if (!PyString_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002419 PyErr_SetString(PyExc_TypeError,
2420 "Item in ``from list'' not a string");
2421 Py_DECREF(item);
2422 return 0;
2423 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002424 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002425 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002426 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002427 /* See if the package defines __all__ */
2428 if (recursive)
2429 continue; /* Avoid endless recursion */
2430 all = PyObject_GetAttrString(mod, "__all__");
2431 if (all == NULL)
2432 PyErr_Clear();
2433 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002434 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002435 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002436 if (!ret)
2437 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002438 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002439 continue;
2440 }
2441 hasit = PyObject_HasAttr(mod, item);
2442 if (!hasit) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002443 char *subname = PyString_AS_STRING(item);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002444 PyObject *submod;
2445 char *p;
2446 if (buflen + strlen(subname) >= MAXPATHLEN) {
2447 PyErr_SetString(PyExc_ValueError,
2448 "Module name too long");
2449 Py_DECREF(item);
2450 return 0;
2451 }
2452 p = buf + buflen;
2453 *p++ = '.';
2454 strcpy(p, subname);
2455 submod = import_submodule(mod, subname, buf);
2456 Py_XDECREF(submod);
2457 if (submod == NULL) {
2458 Py_DECREF(item);
2459 return 0;
2460 }
2461 }
2462 Py_DECREF(item);
2463 }
2464
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002465 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002466}
2467
Neil Schemenauer00b09662003-06-16 21:03:07 +00002468static int
2469add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2470 PyObject *modules)
2471{
2472 if (mod == Py_None)
2473 return 1;
2474 /* Irrespective of the success of this load, make a
2475 reference to it in the parent package module. A copy gets
2476 saved in the modules dictionary under the full name, so get a
2477 reference from there, if need be. (The exception is when the
2478 load failed with a SyntaxError -- then there's no trace in
2479 sys.modules. In that case, of course, do nothing extra.) */
2480 if (submod == NULL) {
2481 submod = PyDict_GetItemString(modules, fullname);
2482 if (submod == NULL)
2483 return 1;
2484 }
2485 if (PyModule_Check(mod)) {
2486 /* We can't use setattr here since it can give a
2487 * spurious warning if the submodule name shadows a
2488 * builtin name */
2489 PyObject *dict = PyModule_GetDict(mod);
2490 if (!dict)
2491 return 0;
2492 if (PyDict_SetItemString(dict, subname, submod) < 0)
2493 return 0;
2494 }
2495 else {
2496 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2497 return 0;
2498 }
2499 return 1;
2500}
2501
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002502static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002503import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002504{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002505 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002506 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002507
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002508 /* Require:
2509 if mod == None: subname == fullname
2510 else: mod.__name__ + "." + subname == fullname
2511 */
2512
Tim Peters50d8d372001-02-28 05:34:27 +00002513 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002514 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002515 }
2516 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002517 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002518 char buf[MAXPATHLEN+1];
2519 struct filedescr *fdp;
2520 FILE *fp = NULL;
2521
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002522 if (mod == Py_None)
2523 path = NULL;
2524 else {
2525 path = PyObject_GetAttrString(mod, "__path__");
2526 if (path == NULL) {
2527 PyErr_Clear();
2528 Py_INCREF(Py_None);
2529 return Py_None;
2530 }
2531 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002532
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002533 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002534 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2535 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002536 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002537 if (fdp == NULL) {
2538 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2539 return NULL;
2540 PyErr_Clear();
2541 Py_INCREF(Py_None);
2542 return Py_None;
2543 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002544 m = load_module(fullname, fp, buf, fdp->type, loader);
2545 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002546 if (fp)
2547 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002548 if (!add_submodule(mod, m, fullname, subname, modules)) {
2549 Py_XDECREF(m);
2550 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002551 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002552 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002553
2554 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002555}
2556
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002557
2558/* Re-import a module of any kind and return its module object, WITH
2559 INCREMENTED REFERENCE COUNT */
2560
Guido van Rossum79f25d91997-04-29 20:08:16 +00002561PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002562PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002563{
Collin Winter47c52a82007-03-13 23:02:15 +00002564 PyInterpreterState *interp = PyThreadState_Get()->interp;
2565 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002566 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002567 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002568 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002569 char buf[MAXPATHLEN+1];
2570 struct filedescr *fdp;
2571 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002572 PyObject *newm;
Collin Winter47c52a82007-03-13 23:02:15 +00002573
2574 if (modules_reloading == NULL) {
2575 Py_FatalError("PyImport_ReloadModule: "
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002576 "no modules_reloading dictionary!");
Collin Winter47c52a82007-03-13 23:02:15 +00002577 return NULL;
2578 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002579
Guido van Rossum79f25d91997-04-29 20:08:16 +00002580 if (m == NULL || !PyModule_Check(m)) {
2581 PyErr_SetString(PyExc_TypeError,
2582 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002583 return NULL;
2584 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002585 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002586 if (name == NULL)
2587 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002588 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002589 PyErr_Format(PyExc_ImportError,
2590 "reload(): module %.200s not in sys.modules",
2591 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002592 return NULL;
2593 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002594 existing_m = PyDict_GetItemString(modules_reloading, name);
2595 if (existing_m != NULL) {
2596 /* Due to a recursive reload, this module is already
2597 being reloaded. */
2598 Py_INCREF(existing_m);
2599 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002600 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002601 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2602 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002603
Guido van Rossum222ef561997-09-06 19:41:09 +00002604 subname = strrchr(name, '.');
2605 if (subname == NULL)
2606 subname = name;
2607 else {
2608 PyObject *parentname, *parent;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002609 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002610 if (parentname == NULL) {
2611 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002612 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002613 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002614 parent = PyDict_GetItem(modules, parentname);
2615 if (parent == NULL) {
2616 PyErr_Format(PyExc_ImportError,
2617 "reload(): parent %.200s not in sys.modules",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002618 PyString_AS_STRING(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002619 Py_DECREF(parentname);
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002620 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002621 return NULL;
2622 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002623 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002624 subname++;
2625 path = PyObject_GetAttrString(parent, "__path__");
2626 if (path == NULL)
2627 PyErr_Clear();
2628 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002629 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002630 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002631 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002632
2633 if (fdp == NULL) {
2634 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002635 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002636 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002637 }
2638
2639 newm = load_module(name, fp, buf, fdp->type, loader);
2640 Py_XDECREF(loader);
2641
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002642 if (fp)
2643 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002644 if (newm == NULL) {
2645 /* load_module probably removed name from modules because of
2646 * the error. Put back the original module object. We're
2647 * going to return NULL in this case regardless of whether
2648 * replacing name succeeds, so the return value is ignored.
2649 */
2650 PyDict_SetItemString(modules, name, m);
2651 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002652 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002653 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002654}
2655
2656
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002657/* Higher-level import emulator which emulates the "import" statement
2658 more accurately -- it invokes the __import__() function from the
2659 builtins of the current globals. This means that the import is
2660 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002661 environment, e.g. by "rexec".
2662 A dummy list ["__doc__"] is passed as the 4th argument so that
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002663 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002664 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002665
2666PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002667PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002668{
2669 static PyObject *silly_list = NULL;
2670 static PyObject *builtins_str = NULL;
2671 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002672 PyObject *globals = NULL;
2673 PyObject *import = NULL;
2674 PyObject *builtins = NULL;
2675 PyObject *r = NULL;
2676
2677 /* Initialize constant string objects */
2678 if (silly_list == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002679 import_str = PyString_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002680 if (import_str == NULL)
2681 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002682 builtins_str = PyString_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002683 if (builtins_str == NULL)
2684 return NULL;
2685 silly_list = Py_BuildValue("[s]", "__doc__");
2686 if (silly_list == NULL)
2687 return NULL;
2688 }
2689
2690 /* Get the builtins from current globals */
2691 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002692 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002693 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002694 builtins = PyObject_GetItem(globals, builtins_str);
2695 if (builtins == NULL)
2696 goto err;
2697 }
2698 else {
2699 /* No globals -- use standard builtins, and fake globals */
2700 PyErr_Clear();
2701
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002702 builtins = PyImport_ImportModuleLevel("__builtin__",
2703 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002704 if (builtins == NULL)
2705 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002706 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2707 if (globals == NULL)
2708 goto err;
2709 }
2710
2711 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002713 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 if (import == NULL)
2715 PyErr_SetObject(PyExc_KeyError, import_str);
2716 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002717 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002718 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002719 if (import == NULL)
2720 goto err;
2721
Christian Heimes000a0742008-01-03 22:16:32 +00002722 /* Call the __import__ function with the proper argument list
2723 * Always use absolute import here. */
2724 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2725 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002726
2727 err:
2728 Py_XDECREF(globals);
2729 Py_XDECREF(builtins);
2730 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002731
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002732 return r;
2733}
2734
2735
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002736/* Module 'imp' provides Python access to the primitives used for
2737 importing modules.
2738*/
2739
Guido van Rossum79f25d91997-04-29 20:08:16 +00002740static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002741imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002742{
2743 char buf[4];
2744
Guido van Rossum96774c12000-05-01 20:19:08 +00002745 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2746 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2747 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2748 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002749
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002750 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002751}
2752
Guido van Rossum79f25d91997-04-29 20:08:16 +00002753static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002754imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002755{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002756 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002757 struct filedescr *fdp;
2758
Guido van Rossum79f25d91997-04-29 20:08:16 +00002759 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002760 if (list == NULL)
2761 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002762 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2763 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002764 fdp->suffix, fdp->mode, fdp->type);
2765 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002766 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002767 return NULL;
2768 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002769 if (PyList_Append(list, item) < 0) {
2770 Py_DECREF(list);
2771 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002772 return NULL;
2773 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002774 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002775 }
2776 return list;
2777}
2778
Guido van Rossum79f25d91997-04-29 20:08:16 +00002779static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002780call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002781{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002782 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002783 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002784 struct filedescr *fdp;
2785 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002786 FILE *fp = NULL;
2787
2788 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789 if (path == Py_None)
2790 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002791 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002792 if (fdp == NULL)
2793 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002794 if (fp != NULL) {
2795 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2796 if (fob == NULL) {
2797 fclose(fp);
2798 return NULL;
2799 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002800 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002801 else {
2802 fob = Py_None;
2803 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002804 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002805 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002806 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002807 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808 return ret;
2809}
2810
Guido van Rossum79f25d91997-04-29 20:08:16 +00002811static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002812imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002813{
2814 char *name;
2815 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002816 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002817 return NULL;
2818 return call_find_module(name, path);
2819}
2820
2821static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002822imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002823{
2824 char *name;
2825 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002826 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002827 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002828 return NULL;
2829 ret = init_builtin(name);
2830 if (ret < 0)
2831 return NULL;
2832 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002833 Py_INCREF(Py_None);
2834 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002835 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002836 m = PyImport_AddModule(name);
2837 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002838 return m;
2839}
2840
Guido van Rossum79f25d91997-04-29 20:08:16 +00002841static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002842imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002843{
2844 char *name;
2845 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002846 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002847 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002848 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002849 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002850 if (ret < 0)
2851 return NULL;
2852 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002853 Py_INCREF(Py_None);
2854 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002855 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002856 m = PyImport_AddModule(name);
2857 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002858 return m;
2859}
2860
Guido van Rossum79f25d91997-04-29 20:08:16 +00002861static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002862imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002863{
2864 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002865
Guido van Rossum43713e52000-02-29 13:59:29 +00002866 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002867 return NULL;
2868 return get_frozen_object(name);
2869}
2870
Guido van Rossum79f25d91997-04-29 20:08:16 +00002871static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002872imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002873{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002874 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002875 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002877 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002878}
2879
Guido van Rossum79f25d91997-04-29 20:08:16 +00002880static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002881imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002883 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002884 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002885 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002886 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002887 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002888 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002889}
2890
2891static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002892get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002893{
2894 FILE *fp;
2895 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002896 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002897 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002898 fp = fopen(pathname, mode);
2899 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002900 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002901 }
2902 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002903 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002904 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002905 PyErr_SetString(PyExc_ValueError,
2906 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002907 }
2908 return fp;
2909}
2910
Guido van Rossum79f25d91997-04-29 20:08:16 +00002911static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002912imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002913{
2914 char *name;
2915 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002916 PyObject *fob = NULL;
2917 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002918 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002919 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002920 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002921 return NULL;
2922 fp = get_file(pathname, fob, "rb");
2923 if (fp == NULL)
2924 return NULL;
2925 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002926 if (fob == NULL)
2927 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002928 return m;
2929}
2930
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002931#ifdef HAVE_DYNAMIC_LOADING
2932
Guido van Rossum79f25d91997-04-29 20:08:16 +00002933static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002934imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002935{
2936 char *name;
2937 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002938 PyObject *fob = NULL;
2939 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002940 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002941 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002942 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002943 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002944 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002945 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002946 if (fp == NULL)
2947 return NULL;
2948 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002949 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002950 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002951}
2952
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002953#endif /* HAVE_DYNAMIC_LOADING */
2954
Guido van Rossum79f25d91997-04-29 20:08:16 +00002955static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002956imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002957{
2958 char *name;
2959 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002960 PyObject *fob = NULL;
2961 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002962 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002963 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002964 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002965 return NULL;
2966 fp = get_file(pathname, fob, "r");
2967 if (fp == NULL)
2968 return NULL;
2969 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002970 if (fob == NULL)
2971 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002972 return m;
2973}
2974
Guido van Rossum79f25d91997-04-29 20:08:16 +00002975static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002976imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002977{
2978 char *name;
2979 PyObject *fob;
2980 char *pathname;
2981 char *suffix; /* Unused */
2982 char *mode;
2983 int type;
2984 FILE *fp;
2985
Guido van Rossum43713e52000-02-29 13:59:29 +00002986 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002987 &name, &fob, &pathname,
2988 &suffix, &mode, &type))
2989 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002990 if (*mode) {
2991 /* Mode must start with 'r' or 'U' and must not contain '+'.
2992 Implicit in this test is the assumption that the mode
2993 may contain other modifiers like 'b' or 't'. */
2994
2995 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002996 PyErr_Format(PyExc_ValueError,
2997 "invalid file open mode %.200s", mode);
2998 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002999 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003000 }
3001 if (fob == Py_None)
3002 fp = NULL;
3003 else {
3004 if (!PyFile_Check(fob)) {
3005 PyErr_SetString(PyExc_ValueError,
3006 "load_module arg#2 should be a file or None");
3007 return NULL;
3008 }
3009 fp = get_file(pathname, fob, mode);
3010 if (fp == NULL)
3011 return NULL;
3012 }
Just van Rossum52e14d62002-12-30 22:08:05 +00003013 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003014}
3015
3016static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003017imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003018{
3019 char *name;
3020 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00003021 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003022 return NULL;
3023 return load_package(name, pathname);
3024}
3025
3026static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003027imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003028{
3029 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003030 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003031 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003032 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003033}
3034
Brett Cannon3aa2a492008-08-06 22:28:09 +00003035static PyObject *
3036imp_reload(PyObject *self, PyObject *v)
3037{
3038 return PyImport_ReloadModule(v);
3039}
3040
3041
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003042/* Doc strings */
3043
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003044PyDoc_STRVAR(doc_imp,
3045"This module provides the components needed to build your own\n\
3046__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003047
Brett Cannon3aa2a492008-08-06 22:28:09 +00003048PyDoc_STRVAR(doc_reload,
3049"reload(module) -> module\n\
3050\n\
3051Reload the module. The module must have been successfully imported before.");
3052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003053PyDoc_STRVAR(doc_find_module,
3054"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003055Search for a module. If path is omitted or None, search for a\n\
3056built-in, frozen or special module and continue search in sys.path.\n\
3057The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003058package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003060PyDoc_STRVAR(doc_load_module,
3061"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003062Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003063The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003065PyDoc_STRVAR(doc_get_magic,
3066"get_magic() -> string\n\
3067Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003068
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003069PyDoc_STRVAR(doc_get_suffixes,
3070"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003071Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003072that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003074PyDoc_STRVAR(doc_new_module,
3075"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003076Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003077The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003079PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003080"lock_held() -> boolean\n\
3081Return True if the import lock is currently held, else False.\n\
3082On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003083
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003084PyDoc_STRVAR(doc_acquire_lock,
3085"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003086Acquires the interpreter's import lock for the current thread.\n\
3087This lock should be used by import hooks to ensure thread-safety\n\
3088when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003089On platforms without threads, this function does nothing.");
3090
3091PyDoc_STRVAR(doc_release_lock,
3092"release_lock() -> None\n\
3093Release the interpreter's import lock.\n\
3094On platforms without threads, this function does nothing.");
3095
Guido van Rossum79f25d91997-04-29 20:08:16 +00003096static PyMethodDef imp_methods[] = {
Brett Cannon3aa2a492008-08-06 22:28:09 +00003097 {"reload", imp_reload, METH_O, doc_reload},
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003098 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3099 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3100 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3101 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3102 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3103 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3104 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3105 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003106 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003107 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3108 {"init_builtin", imp_init_builtin, METH_VARARGS},
3109 {"init_frozen", imp_init_frozen, METH_VARARGS},
3110 {"is_builtin", imp_is_builtin, METH_VARARGS},
3111 {"is_frozen", imp_is_frozen, METH_VARARGS},
3112 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003113#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003114 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003115#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003116 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003117 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003118 {NULL, NULL} /* sentinel */
3119};
3120
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003121static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003122setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003123{
3124 PyObject *v;
3125 int err;
3126
3127 v = PyInt_FromLong((long)value);
3128 err = PyDict_SetItemString(d, name, v);
3129 Py_XDECREF(v);
3130 return err;
3131}
3132
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003133typedef struct {
3134 PyObject_HEAD
3135} NullImporter;
3136
3137static int
3138NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3139{
3140 char *path;
Christian Heimescea681b2007-11-07 17:50:54 +00003141 Py_ssize_t pathlen;
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003142
3143 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3144 return -1;
3145
3146 if (!PyArg_ParseTuple(args, "s:NullImporter",
3147 &path))
3148 return -1;
3149
Christian Heimescea681b2007-11-07 17:50:54 +00003150 pathlen = strlen(path);
3151 if (pathlen == 0) {
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003152 PyErr_SetString(PyExc_ImportError, "empty pathname");
3153 return -1;
3154 } else {
3155#ifndef RISCOS
3156 struct stat statbuf;
3157 int rv;
3158
3159 rv = stat(path, &statbuf);
Christian Heimes004c1c12007-11-07 18:30:22 +00003160#ifdef MS_WINDOWS
3161 /* MS Windows stat() chokes on paths like C:\path\. Try to
3162 * recover *one* time by stripping off a trailing slash or
3163 * backslash. http://bugs.python.org/issue1293
3164 */
Christian Heimescea681b2007-11-07 17:50:54 +00003165 if (rv != 0 && pathlen <= MAXPATHLEN &&
3166 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3167 char mangled[MAXPATHLEN+1];
3168
3169 strcpy(mangled, path);
3170 mangled[pathlen-1] = '\0';
3171 rv = stat(mangled, &statbuf);
3172 }
Christian Heimescea681b2007-11-07 17:50:54 +00003173#endif
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003174 if (rv == 0) {
3175 /* it exists */
3176 if (S_ISDIR(statbuf.st_mode)) {
3177 /* it's a directory */
3178 PyErr_SetString(PyExc_ImportError,
3179 "existing directory");
3180 return -1;
3181 }
3182 }
3183#else
3184 if (object_exists(path)) {
3185 /* it exists */
3186 if (isdir(path)) {
3187 /* it's a directory */
3188 PyErr_SetString(PyExc_ImportError,
3189 "existing directory");
3190 return -1;
3191 }
3192 }
3193#endif
3194 }
3195 return 0;
3196}
3197
3198static PyObject *
3199NullImporter_find_module(NullImporter *self, PyObject *args)
3200{
3201 Py_RETURN_NONE;
3202}
3203
3204static PyMethodDef NullImporter_methods[] = {
3205 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3206 "Always return None"
3207 },
3208 {NULL} /* Sentinel */
3209};
3210
3211
Nick Coghlan327a39b2007-11-18 11:56:28 +00003212PyTypeObject PyNullImporter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003213 PyVarObject_HEAD_INIT(NULL, 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003214 "imp.NullImporter", /*tp_name*/
3215 sizeof(NullImporter), /*tp_basicsize*/
3216 0, /*tp_itemsize*/
3217 0, /*tp_dealloc*/
3218 0, /*tp_print*/
3219 0, /*tp_getattr*/
3220 0, /*tp_setattr*/
3221 0, /*tp_compare*/
3222 0, /*tp_repr*/
3223 0, /*tp_as_number*/
3224 0, /*tp_as_sequence*/
3225 0, /*tp_as_mapping*/
3226 0, /*tp_hash */
3227 0, /*tp_call*/
3228 0, /*tp_str*/
3229 0, /*tp_getattro*/
3230 0, /*tp_setattro*/
3231 0, /*tp_as_buffer*/
3232 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3233 "Null importer object", /* tp_doc */
3234 0, /* tp_traverse */
3235 0, /* tp_clear */
3236 0, /* tp_richcompare */
3237 0, /* tp_weaklistoffset */
3238 0, /* tp_iter */
3239 0, /* tp_iternext */
3240 NullImporter_methods, /* tp_methods */
3241 0, /* tp_members */
3242 0, /* tp_getset */
3243 0, /* tp_base */
3244 0, /* tp_dict */
3245 0, /* tp_descr_get */
3246 0, /* tp_descr_set */
3247 0, /* tp_dictoffset */
3248 (initproc)NullImporter_init, /* tp_init */
3249 0, /* tp_alloc */
3250 PyType_GenericNew /* tp_new */
3251};
3252
3253
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003254PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003255initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003256{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003257 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003258
Nick Coghlan327a39b2007-11-18 11:56:28 +00003259 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003260 goto failure;
3261
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003262 m = Py_InitModule4("imp", imp_methods, doc_imp,
3263 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003264 if (m == NULL)
3265 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003266 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003267 if (d == NULL)
3268 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003269
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003270 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3271 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3272 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3273 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3274 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3275 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3276 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3277 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003278 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003279 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003280
Nick Coghlan327a39b2007-11-18 11:56:28 +00003281 Py_INCREF(&PyNullImporter_Type);
3282 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003283 failure:
3284 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003285}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003286
3287
Guido van Rossumb18618d2000-05-03 23:44:39 +00003288/* API for embedding applications that want to add their own entries
3289 to the table of built-in modules. This should normally be called
3290 *before* Py_Initialize(). When the table resize fails, -1 is
3291 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003292
3293 After a similar function by Just van Rossum. */
3294
3295int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003296PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003297{
3298 static struct _inittab *our_copy = NULL;
3299 struct _inittab *p;
3300 int i, n;
3301
3302 /* Count the number of entries in both tables */
3303 for (n = 0; newtab[n].name != NULL; n++)
3304 ;
3305 if (n == 0)
3306 return 0; /* Nothing to do */
3307 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3308 ;
3309
3310 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003311 p = our_copy;
3312 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003313 if (p == NULL)
3314 return -1;
3315
3316 /* Copy the tables into the new memory */
3317 if (our_copy != PyImport_Inittab)
3318 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3319 PyImport_Inittab = our_copy = p;
3320 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3321
3322 return 0;
3323}
3324
3325/* Shorthand to add a single entry given a name and a function */
3326
3327int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003328PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003329{
3330 struct _inittab newtab[2];
3331
3332 memset(newtab, '\0', sizeof newtab);
3333
3334 newtab[0].name = name;
3335 newtab[0].initfunc = initfunc;
3336
3337 return PyImport_ExtendInittab(newtab);
3338}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003339
3340#ifdef __cplusplus
3341}
3342#endif