blob: 40fc0186e8dc8975715e2a901d77c4ea9bcb5c62 [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
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000030extern time_t PyOS_GetLastModificationTime(char *, FILE *);
31 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000040 The magic numbers must be spaced apart atleast 2 values, as the
41 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000048 Known values:
49 Python 1.5: 20121
50 Python 1.5.1: 20121
51 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000052 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Python 2.0: 50823
54 Python 2.0.1: 50823
55 Python 2.1: 60202
56 Python 2.1.1: 60202
57 Python 2.1.2: 60202
58 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000059 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000060 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000061 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000062 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000063 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000064 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000065 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000066 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000067 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000068 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Neal Norwitz0d62a062006-07-30 06:53:31 +000069 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
70 Python 2.5b3: 62111 (fix wrong code: x += yield)
Neal Norwitz9a70f952006-08-04 05:12:19 +000071 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
72 storing constants that should have been removed)
Neal Norwitzdac090d2006-09-05 03:53:08 +000073 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Raymond Hettingereffde122007-12-18 18:26:18 +000074 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Nick Coghlan7af53be2008-03-07 14:13:28 +000075 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Antoine Pitroud0c35152008-12-17 00:38:28 +000076 Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000077.
Tim Peters36515e22001-11-18 04:06:29 +000078*/
Antoine Pitroud0c35152008-12-17 00:38:28 +000079#define MAGIC (62171 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000080
Guido van Rossum96774c12000-05-01 20:19:08 +000081/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000082 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000083 compiler works which are enabled by command line switches. */
Christian Heimes61e45902008-03-27 10:35:52 +000084static long pyc_magic = MAGIC;
Guido van Rossum96774c12000-05-01 20:19:08 +000085
Guido van Rossum25ce5661997-08-02 03:10:38 +000086/* See _PyImport_FixupExtension() below */
87static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000088
Guido van Rossum771c6c81997-10-31 18:37:24 +000089/* This table is defined in config.c: */
90extern struct _inittab _PyImport_Inittab[];
91
92struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000093
Guido van Rossumed1170e1999-12-20 21:23:41 +000094/* these tables define the module suffixes that Python recognizes */
95struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000096
97#ifdef RISCOS
98static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000099 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +0000100 {"/pyc", "rb", PY_COMPILED},
101 {0, 0}
102};
103#else
Guido van Rossumed1170e1999-12-20 21:23:41 +0000104static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000105 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000106#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000107 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000108#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000109 {".pyc", "rb", PY_COMPILED},
110 {0, 0}
111};
Guido van Rossum48a680c2001-03-02 06:34:14 +0000112#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000113
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000114
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000115/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116
117void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000118_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000120 const struct filedescr *scan;
121 struct filedescr *filetab;
122 int countD = 0;
123 int countS = 0;
124
125 /* prepare _PyImport_Filetab: copy entries from
126 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
127 */
Georg Brandladd36e52007-08-23 18:08:06 +0000128#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000129 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
130 ++countD;
Georg Brandladd36e52007-08-23 18:08:06 +0000131#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000132 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
133 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000134 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Neal Norwitze1fdb322006-07-21 05:32:28 +0000135 if (filetab == NULL)
Neal Norwitz33722ae2006-07-21 07:59:02 +0000136 Py_FatalError("Can't initialize import file table.");
Georg Brandladd36e52007-08-23 18:08:06 +0000137#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138 memcpy(filetab, _PyImport_DynLoadFiletab,
139 countD * sizeof(struct filedescr));
Georg Brandladd36e52007-08-23 18:08:06 +0000140#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141 memcpy(filetab + countD, _PyImport_StandardFiletab,
142 countS * sizeof(struct filedescr));
143 filetab[countD + countS].suffix = NULL;
144
145 _PyImport_Filetab = filetab;
146
Guido van Rossum0824f631997-03-11 18:37:35 +0000147 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000148 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
149 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000150#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000151 if (strcmp(filetab->suffix, ".pyc") == 0)
152 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000153#else
154 if (strcmp(filetab->suffix, "/pyc") == 0)
155 filetab->suffix = "/pyo";
156#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000157 }
158 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000159
160 if (Py_UnicodeFlag) {
161 /* Fix the pyc_magic so that byte compiled code created
162 using the all-Unicode method doesn't interfere with
163 code created in normal operation mode. */
164 pyc_magic = MAGIC + 1;
165 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166}
167
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168void
Just van Rossum52e14d62002-12-30 22:08:05 +0000169_PyImportHooks_Init(void)
170{
171 PyObject *v, *path_hooks = NULL, *zimpimport;
172 int err = 0;
173
174 /* adding sys.path_hooks and sys.path_importer_cache, setting up
175 zipimport */
Nick Coghlan327a39b2007-11-18 11:56:28 +0000176 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000177 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000178
179 if (Py_VerboseFlag)
180 PySys_WriteStderr("# installing zipimport hook\n");
181
182 v = PyList_New(0);
183 if (v == NULL)
184 goto error;
185 err = PySys_SetObject("meta_path", v);
186 Py_DECREF(v);
187 if (err)
188 goto error;
189 v = PyDict_New();
190 if (v == NULL)
191 goto error;
192 err = PySys_SetObject("path_importer_cache", v);
193 Py_DECREF(v);
194 if (err)
195 goto error;
196 path_hooks = PyList_New(0);
197 if (path_hooks == NULL)
198 goto error;
199 err = PySys_SetObject("path_hooks", path_hooks);
200 if (err) {
201 error:
202 PyErr_Print();
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000203 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
204 "path_importer_cache, or NullImporter failed"
205 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000206 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000207
Just van Rossum52e14d62002-12-30 22:08:05 +0000208 zimpimport = PyImport_ImportModule("zipimport");
209 if (zimpimport == NULL) {
210 PyErr_Clear(); /* No zip import module -- okay */
211 if (Py_VerboseFlag)
212 PySys_WriteStderr("# can't import zipimport\n");
213 }
214 else {
215 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
216 "zipimporter");
217 Py_DECREF(zimpimport);
218 if (zipimporter == NULL) {
219 PyErr_Clear(); /* No zipimporter object -- okay */
220 if (Py_VerboseFlag)
221 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000222 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000223 }
224 else {
225 /* sys.path_hooks.append(zipimporter) */
226 err = PyList_Append(path_hooks, zipimporter);
227 Py_DECREF(zipimporter);
228 if (err)
229 goto error;
230 if (Py_VerboseFlag)
231 PySys_WriteStderr(
232 "# installed zipimport hook\n");
233 }
234 }
235 Py_DECREF(path_hooks);
236}
237
238void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240{
241 Py_XDECREF(extensions);
242 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000243 PyMem_DEL(_PyImport_Filetab);
244 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000245}
246
247
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000248/* Locking primitives to prevent parallel imports of the same module
249 in different threads to return with a partially loaded module.
250 These calls are serialized by the global interpreter lock. */
251
252#ifdef WITH_THREAD
253
Guido van Rossum49b56061998-10-01 20:42:43 +0000254#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255
Guido van Rossum65d5b571998-12-21 19:32:43 +0000256static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000257static long import_lock_thread = -1;
258static int import_lock_level = 0;
259
260static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000261lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000262{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000263 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264 if (me == -1)
265 return; /* Too bad */
Neal Norwitze1fdb322006-07-21 05:32:28 +0000266 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000267 import_lock = PyThread_allocate_lock();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000268 if (import_lock == NULL)
269 return; /* Nothing much we can do. */
270 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000271 if (import_lock_thread == me) {
272 import_lock_level++;
273 return;
274 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000275 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
276 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000278 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279 PyEval_RestoreThread(tstate);
280 }
281 import_lock_thread = me;
282 import_lock_level = 1;
283}
284
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000286unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000288 long me = PyThread_get_thread_ident();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000289 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000291 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000292 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000293 import_lock_level--;
294 if (import_lock_level == 0) {
295 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000296 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000298 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000299}
300
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000301/* This function is called from PyOS_AfterFork to ensure that newly
302 created child processes do not share locks with the parent. */
303
304void
305_PyImport_ReInitLock(void)
306{
307#ifdef _AIX
308 if (import_lock != NULL)
309 import_lock = PyThread_allocate_lock();
310#endif
311}
312
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000313#else
314
315#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000316#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000317
318#endif
319
Tim Peters69232342001-08-30 05:16:13 +0000320static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000321imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000322{
Tim Peters69232342001-08-30 05:16:13 +0000323#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000324 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000325#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000326 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000327#endif
328}
329
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000331imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333#ifdef WITH_THREAD
334 lock_import();
335#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000336 Py_INCREF(Py_None);
337 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000338}
339
340static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000341imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343#ifdef WITH_THREAD
344 if (unlock_import() < 0) {
345 PyErr_SetString(PyExc_RuntimeError,
346 "not holding the import lock");
347 return NULL;
348 }
349#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000350 Py_INCREF(Py_None);
351 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352}
353
Collin Winter276887b2007-03-12 16:11:39 +0000354static void
Neal Norwitz75c7c802007-03-13 05:31:38 +0000355imp_modules_reloading_clear(void)
Collin Winter276887b2007-03-12 16:11:39 +0000356{
357 PyInterpreterState *interp = PyThreadState_Get()->interp;
Neal Norwitz75c7c802007-03-13 05:31:38 +0000358 if (interp->modules_reloading != NULL)
359 PyDict_Clear(interp->modules_reloading);
Collin Winter276887b2007-03-12 16:11:39 +0000360}
361
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362/* Helper for sys */
363
364PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000365PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000367 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368 if (interp->modules == NULL)
369 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
370 return interp->modules;
371}
372
Guido van Rossum3f5da241990-12-20 15:06:42 +0000373
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000374/* List of names to clear in sys */
375static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000376 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377 "exc_type", "exc_value", "exc_traceback",
378 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000379 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes0d924432008-01-30 17:21:22 +0000380 /* misc stuff */
381 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000382 NULL
383};
384
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000385static char* sys_files[] = {
386 "stdin", "__stdin__",
387 "stdout", "__stdout__",
388 "stderr", "__stderr__",
389 NULL
390};
391
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000393/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000399 char *name;
400 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000401 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000402 PyObject *modules = interp->modules;
403
404 if (modules == NULL)
405 return; /* Already done */
406
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000407 /* Delete some special variables first. These are common
408 places where user values hide and people complain when their
409 destructors fail. Since the modules containing them are
410 deleted *last* of all, they would come too late in the normal
411 destruction order. Sigh. */
412
413 value = PyDict_GetItemString(modules, "__builtin__");
414 if (value != NULL && PyModule_Check(value)) {
415 dict = PyModule_GetDict(value);
416 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000417 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000418 PyDict_SetItemString(dict, "_", Py_None);
419 }
420 value = PyDict_GetItemString(modules, "sys");
421 if (value != NULL && PyModule_Check(value)) {
422 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000423 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000424 dict = PyModule_GetDict(value);
425 for (p = sys_deletes; *p != NULL; p++) {
426 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000427 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000428 PyDict_SetItemString(dict, *p, Py_None);
429 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430 for (p = sys_files; *p != NULL; p+=2) {
431 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000432 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000433 v = PyDict_GetItemString(dict, *(p+1));
434 if (v == NULL)
435 v = Py_None;
436 PyDict_SetItemString(dict, *p, v);
437 }
438 }
439
440 /* First, delete __main__ */
441 value = PyDict_GetItemString(modules, "__main__");
442 if (value != NULL && PyModule_Check(value)) {
443 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000444 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000445 _PyModule_Clear(value);
446 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000447 }
448
Guido van Rossum758eec01998-01-19 21:58:26 +0000449 /* The special treatment of __builtin__ here is because even
450 when it's not referenced as a module, its dictionary is
451 referenced by almost every module's __builtins__. Since
452 deleting a module clears its dictionary (even if there are
453 references left to it), we need to delete the __builtin__
454 module last. Likewise, we don't delete sys until the very
455 end because it is implicitly referenced (e.g. by print).
456
457 Also note that we 'delete' modules by replacing their entry
458 in the modules dict with None, rather than really deleting
459 them; this avoids a rehash of the modules dictionary and
460 also marks them as "non existent" so they won't be
461 re-imported. */
462
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000463 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000464 one (skipping __builtin__ and sys) and delete them */
465 do {
466 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000467 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000468 while (PyDict_Next(modules, &pos, &key, &value)) {
469 if (value->ob_refcnt != 1)
470 continue;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000471 if (PyString_Check(key) && PyModule_Check(value)) {
472 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000473 if (strcmp(name, "__builtin__") == 0)
474 continue;
475 if (strcmp(name, "sys") == 0)
476 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000477 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000478 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000479 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000480 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000481 PyDict_SetItem(modules, key, Py_None);
482 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000483 }
484 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000485 } while (ndone > 0);
486
Guido van Rossum758eec01998-01-19 21:58:26 +0000487 /* Next, delete all modules (still skipping __builtin__ and sys) */
488 pos = 0;
489 while (PyDict_Next(modules, &pos, &key, &value)) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000490 if (PyString_Check(key) && PyModule_Check(value)) {
491 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000492 if (strcmp(name, "__builtin__") == 0)
493 continue;
494 if (strcmp(name, "sys") == 0)
495 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000496 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000497 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000498 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000499 PyDict_SetItem(modules, key, Py_None);
500 }
501 }
502
503 /* Next, delete sys and __builtin__ (in that order) */
504 value = PyDict_GetItemString(modules, "sys");
505 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000506 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000507 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000508 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000509 PyDict_SetItemString(modules, "sys", Py_None);
510 }
511 value = PyDict_GetItemString(modules, "__builtin__");
512 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000513 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000514 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000515 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000516 PyDict_SetItemString(modules, "__builtin__", Py_None);
517 }
518
519 /* Finally, clear and delete the modules directory */
520 PyDict_Clear(modules);
521 interp->modules = NULL;
522 Py_DECREF(modules);
Collin Winter276887b2007-03-12 16:11:39 +0000523 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000524}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000525
526
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527/* Helper for pythonrun.c -- return magic number */
528
529long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000531{
Guido van Rossum96774c12000-05-01 20:19:08 +0000532 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000533}
534
535
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536/* Magic for extension modules (built-in as well as dynamically
537 loaded). To prevent initializing an extension module more than
538 once, we keep a static dictionary 'extensions' keyed by module name
539 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000540 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541 dictionary is stored by calling _PyImport_FixupExtension()
542 immediately after the module initialization function succeeds. A
543 copy can be retrieved from there by calling
544 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545
Guido van Rossum79f25d91997-04-29 20:08:16 +0000546PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549 PyObject *modules, *mod, *dict, *copy;
550 if (extensions == NULL) {
551 extensions = PyDict_New();
552 if (extensions == NULL)
553 return NULL;
554 }
555 modules = PyImport_GetModuleDict();
556 mod = PyDict_GetItemString(modules, name);
557 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000558 PyErr_Format(PyExc_SystemError,
559 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560 return NULL;
561 }
562 dict = PyModule_GetDict(mod);
563 if (dict == NULL)
564 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000565 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566 if (copy == NULL)
567 return NULL;
568 PyDict_SetItemString(extensions, filename, copy);
569 Py_DECREF(copy);
570 return copy;
571}
572
573PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000576 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 if (extensions == NULL)
578 return NULL;
579 dict = PyDict_GetItemString(extensions, filename);
580 if (dict == NULL)
581 return NULL;
582 mod = PyImport_AddModule(name);
583 if (mod == NULL)
584 return NULL;
585 mdict = PyModule_GetDict(mod);
586 if (mdict == NULL)
587 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000588 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000591 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592 name, filename);
593 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594}
595
596
597/* Get the module object corresponding to a module name.
598 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000599 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000600 Because the former action is most common, THIS DOES NOT RETURN A
601 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602
Guido van Rossum79f25d91997-04-29 20:08:16 +0000603PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000604PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000607 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000608
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000610 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000612 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000613 if (m == NULL)
614 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000617 return NULL;
618 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000619 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620
621 return m;
622}
623
Tim Peters1cd70172004-08-02 03:52:12 +0000624/* Remove name from sys.modules, if it's there. */
625static void
626_RemoveModule(const char *name)
627{
628 PyObject *modules = PyImport_GetModuleDict();
629 if (PyDict_GetItemString(modules, name) == NULL)
630 return;
631 if (PyDict_DelItemString(modules, name) < 0)
632 Py_FatalError("import: deleting existing key in"
633 "sys.modules failed");
634}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000636/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000637 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
638 * removed from sys.modules, to avoid leaving damaged module objects
639 * in sys.modules. The caller may wish to restore the original
640 * module object (if any) in this case; PyImport_ReloadModule is an
641 * example.
642 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000643PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000646 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
647}
648
649PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000651{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000653 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000654
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656 if (m == NULL)
657 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000658 /* If the module is being reloaded, we get the old module back
659 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000660 d = PyModule_GetDict(m);
661 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
662 if (PyDict_SetItemString(d, "__builtins__",
663 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000664 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000665 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000666 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000667 v = NULL;
668 if (pathname != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000669 v = PyString_FromString(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000670 if (v == NULL)
671 PyErr_Clear();
672 }
673 if (v == NULL) {
674 v = ((PyCodeObject *)co)->co_filename;
675 Py_INCREF(v);
676 }
677 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000678 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000679 Py_DECREF(v);
680
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000681 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000683 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000684 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000685
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000687 PyErr_Format(PyExc_ImportError,
688 "Loaded module %.200s not found in sys.modules",
689 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000690 return NULL;
691 }
692
Guido van Rossum79f25d91997-04-29 20:08:16 +0000693 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000694
695 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000696
697 error:
698 _RemoveModule(name);
699 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700}
701
702
703/* Given a pathname for a Python source file, fill a buffer with the
704 pathname for the corresponding compiled file. Return the pathname
705 for the compiled file, or NULL if there's no space in the buffer.
706 Doesn't set an exception. */
707
708static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000709make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710{
Tim Petersc1731372001-08-04 08:12:36 +0000711 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712 if (len+2 > buflen)
713 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000714
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000715#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000716 /* Treat .pyw as if it were .py. The case of ".pyw" must match
717 that used in _PyImport_StandardFiletab. */
718 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
719 --len; /* pretend 'w' isn't there */
720#endif
721 memcpy(buf, pathname, len);
722 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
723 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724
725 return buf;
726}
727
728
729/* Given a pathname for a Python source file, its time of last
730 modification, and a pathname for a compiled file, check whether the
731 compiled file represents the same version of the source. If so,
732 return a FILE pointer for the compiled file, positioned just after
733 the header; if not, return NULL.
734 Doesn't set an exception. */
735
736static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000737check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738{
739 FILE *fp;
740 long magic;
741 long pyc_mtime;
742
743 fp = fopen(cpathname, "rb");
744 if (fp == NULL)
745 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000747 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000748 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000749 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750 fclose(fp);
751 return NULL;
752 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000753 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000754 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000756 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757 fclose(fp);
758 return NULL;
759 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000760 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000761 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000762 return fp;
763}
764
765
766/* Read a code object from a file and check it for validity */
767
Guido van Rossum79f25d91997-04-29 20:08:16 +0000768static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000769read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000770{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000771 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000772
Tim Petersd9b9ac82001-01-28 00:27:39 +0000773 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000774 if (co == NULL)
775 return NULL;
776 if (!PyCode_Check(co)) {
777 PyErr_Format(PyExc_ImportError,
778 "Non-code object in %.200s", cpathname);
779 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000780 return NULL;
781 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000782 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783}
784
785
786/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000787 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
Guido van Rossum79f25d91997-04-29 20:08:16 +0000789static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000790load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791{
792 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000793 PyCodeObject *co;
794 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000795
Guido van Rossum79f25d91997-04-29 20:08:16 +0000796 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000797 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000798 PyErr_Format(PyExc_ImportError,
799 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000800 return NULL;
801 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000802 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000803 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000804 if (co == NULL)
805 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000806 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000807 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000808 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000809 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000810 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000811
812 return m;
813}
814
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815/* Parse a source file and return the corresponding code object */
816
Guido van Rossum79f25d91997-04-29 20:08:16 +0000817static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820 PyCodeObject *co = NULL;
821 mod_ty mod;
Christian Heimes3c608332008-03-26 22:01:37 +0000822 PyCompilerFlags flags;
Neal Norwitz2a399b02006-09-11 04:28:16 +0000823 PyArena *arena = PyArena_New();
824 if (arena == NULL)
825 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826
Christian Heimes7f23d862008-03-26 22:51:58 +0000827 flags.cf_flags = 0;
828
Christian Heimes3c608332008-03-26 22:01:37 +0000829 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000830 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000832 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833 }
Neal Norwitz2a399b02006-09-11 04:28:16 +0000834 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835 return co;
836}
837
838
Guido van Rossum55a83382000-09-20 20:31:38 +0000839/* Helper to open a bytecode file for writing in exclusive mode */
840
841static FILE *
Christian Heimes40346852008-02-23 17:52:07 +0000842open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000843{
844#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
845 /* Use O_EXCL to avoid a race condition when another process tries to
846 write the same file. When that happens, our open() call fails,
847 which is just fine (since it's only a cache).
848 XXX If the file exists and is writable but the directory is not
849 writable, the file will never be written. Oh well.
850 */
851 int fd;
852 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000853 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
854#ifdef O_BINARY
855 |O_BINARY /* necessary for Windows */
856#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000857#ifdef __VMS
Christian Heimes40346852008-02-23 17:52:07 +0000858 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000859#else
Christian Heimes40346852008-02-23 17:52:07 +0000860 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000861#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000862 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000863 if (fd < 0)
864 return NULL;
865 return fdopen(fd, "wb");
866#else
867 /* Best we can do -- on Windows this can't happen anyway */
868 return fopen(filename, "wb");
869#endif
870}
871
872
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000873/* Write a compiled module to a file, placing the time of last
874 modification of its source into the header.
875 Errors are ignored, if a write error occurs an attempt is made to
876 remove the file. */
877
878static void
Christian Heimes40346852008-02-23 17:52:07 +0000879write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880{
881 FILE *fp;
Christian Heimes40346852008-02-23 17:52:07 +0000882 time_t mtime = srcstat->st_mtime;
883 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Christian Heimes40346852008-02-23 17:52:07 +0000885 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000888 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000889 "# can't create %s\n", cpathname);
890 return;
891 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000892 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000893 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000894 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
895 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000896 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000897 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000898 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000899 /* Don't keep partial file */
900 fclose(fp);
901 (void) unlink(cpathname);
902 return;
903 }
904 /* Now write the true mtime */
905 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000907 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908 fflush(fp);
909 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000910 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000911 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912}
913
914
915/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000916 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
917 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000918
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921{
Christian Heimes40346852008-02-23 17:52:07 +0000922 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000923 FILE *fpc;
924 char buf[MAXPATHLEN+1];
925 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926 PyCodeObject *co;
927 PyObject *m;
Christian Heimes40346852008-02-23 17:52:07 +0000928
929 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000930 PyErr_Format(PyExc_RuntimeError,
Christian Heimes40346852008-02-23 17:52:07 +0000931 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000932 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000933 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000934 }
Fred Drake4c82b232000-06-30 16:18:57 +0000935#if SIZEOF_TIME_T > 4
936 /* Python's .pyc timestamp handling presumes that the timestamp fits
937 in 4 bytes. This will be fine until sometime in the year 2038,
938 when a 4-byte signed time_t will overflow.
939 */
Christian Heimes40346852008-02-23 17:52:07 +0000940 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000941 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000942 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000943 return NULL;
944 }
945#endif
Tim Peters36515e22001-11-18 04:06:29 +0000946 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000947 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000948 if (cpathname != NULL &&
Christian Heimes40346852008-02-23 17:52:07 +0000949 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000950 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951 fclose(fpc);
952 if (co == NULL)
953 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000954 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000955 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000956 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000957 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958 }
959 else {
960 co = parse_source_module(pathname, fp);
961 if (co == NULL)
962 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000963 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000964 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000965 name, pathname);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000966 if (cpathname) {
967 PyObject *ro = PySys_GetObject("dont_write_bytecode");
968 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes40346852008-02-23 17:52:07 +0000969 write_compiled_module(co, cpathname, &st);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000970 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000971 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000972 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000973 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000974
975 return m;
976}
977
978
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000979/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000980static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
981static struct filedescr *find_module(char *, char *, PyObject *,
982 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000983static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000984
985/* Load a package and return its module object WITH INCREMENTED
986 REFERENCE COUNT */
987
988static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000989load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000990{
Tim Peters1cd70172004-08-02 03:52:12 +0000991 PyObject *m, *d;
992 PyObject *file = NULL;
993 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000994 int err;
995 char buf[MAXPATHLEN+1];
996 FILE *fp = NULL;
997 struct filedescr *fdp;
998
999 m = PyImport_AddModule(name);
1000 if (m == NULL)
1001 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001002 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001003 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001004 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001005 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001006 file = PyString_FromString(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001007 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001008 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001009 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001010 if (path == NULL)
1011 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012 err = PyDict_SetItemString(d, "__file__", file);
1013 if (err == 0)
1014 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001015 if (err != 0)
1016 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001018 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001019 if (fdp == NULL) {
1020 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1021 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001022 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001023 }
1024 else
1025 m = NULL;
1026 goto cleanup;
1027 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001028 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001029 if (fp != NULL)
1030 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001031 goto cleanup;
1032
1033 error:
1034 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001035 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001036 Py_XDECREF(path);
1037 Py_XDECREF(file);
1038 return m;
1039}
1040
1041
1042/* Helper to test for built-in module */
1043
1044static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001045is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001046{
1047 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001048 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1049 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1050 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051 return -1;
1052 else
1053 return 1;
1054 }
1055 }
1056 return 0;
1057}
1058
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001059
Just van Rossum52e14d62002-12-30 22:08:05 +00001060/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1061 possibly by fetching it from the path_importer_cache dict. If it
Brett Cannon94b69f62006-09-28 22:10:14 +00001062 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001063 that can handle the path item. Return None if no hook could;
1064 this tells our caller it should fall back to the builtin
1065 import mechanism. Cache the result in path_importer_cache.
1066 Returns a borrowed reference. */
1067
1068static PyObject *
1069get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1070 PyObject *p)
1071{
1072 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001073 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001074
1075 /* These conditions are the caller's responsibility: */
1076 assert(PyList_Check(path_hooks));
1077 assert(PyDict_Check(path_importer_cache));
1078
1079 nhooks = PyList_Size(path_hooks);
1080 if (nhooks < 0)
1081 return NULL; /* Shouldn't happen */
1082
1083 importer = PyDict_GetItem(path_importer_cache, p);
1084 if (importer != NULL)
1085 return importer;
1086
1087 /* set path_importer_cache[p] to None to avoid recursion */
1088 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1089 return NULL;
1090
1091 for (j = 0; j < nhooks; j++) {
1092 PyObject *hook = PyList_GetItem(path_hooks, j);
1093 if (hook == NULL)
1094 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001095 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001096 if (importer != NULL)
1097 break;
1098
1099 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1100 return NULL;
1101 }
1102 PyErr_Clear();
1103 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001104 if (importer == NULL) {
1105 importer = PyObject_CallFunctionObjArgs(
Nick Coghlan327a39b2007-11-18 11:56:28 +00001106 (PyObject *)&PyNullImporter_Type, p, NULL
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001107 );
1108 if (importer == NULL) {
1109 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1110 PyErr_Clear();
1111 return Py_None;
1112 }
1113 }
1114 }
1115 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001116 int err = PyDict_SetItem(path_importer_cache, p, importer);
1117 Py_DECREF(importer);
1118 if (err != 0)
1119 return NULL;
1120 }
1121 return importer;
1122}
1123
Nick Coghlan327a39b2007-11-18 11:56:28 +00001124PyAPI_FUNC(PyObject *)
1125PyImport_GetImporter(PyObject *path) {
1126 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1127
1128 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1129 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1130 importer = get_path_importer(path_importer_cache,
1131 path_hooks, path);
1132 }
1133 }
1134 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1135 return importer;
1136}
1137
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001138/* Search the path (default sys.path) for a module. Return the
1139 corresponding filedescr struct, and (via return arguments) the
1140 pathname and an open file. Return NULL if the module is not found. */
1141
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001142#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001143extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001145#endif
1146
Martin v. Löwis18e16552006-02-15 17:27:45 +00001147static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001148static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001149static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001150
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001152find_module(char *fullname, char *subname, PyObject *path, char *buf,
1153 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001155 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001156 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001157 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001158 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001159 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001160 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001161#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001162 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001163#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001164 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1165 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1166 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001167 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001168#if defined(PYOS_OS2)
1169 size_t saved_len;
1170 size_t saved_namelen;
1171 char *saved_buf = NULL;
1172#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001173 if (p_loader != NULL)
1174 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001175
Just van Rossum52e14d62002-12-30 22:08:05 +00001176 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001177 PyErr_SetString(PyExc_OverflowError,
1178 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001179 return NULL;
1180 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001181 strcpy(name, subname);
1182
1183 /* sys.meta_path import hook */
1184 if (p_loader != NULL) {
1185 PyObject *meta_path;
1186
1187 meta_path = PySys_GetObject("meta_path");
1188 if (meta_path == NULL || !PyList_Check(meta_path)) {
1189 PyErr_SetString(PyExc_ImportError,
1190 "sys.meta_path must be a list of "
1191 "import hooks");
1192 return NULL;
1193 }
1194 Py_INCREF(meta_path); /* zap guard */
1195 npath = PyList_Size(meta_path);
1196 for (i = 0; i < npath; i++) {
1197 PyObject *loader;
1198 PyObject *hook = PyList_GetItem(meta_path, i);
1199 loader = PyObject_CallMethod(hook, "find_module",
1200 "sO", fullname,
1201 path != NULL ?
1202 path : Py_None);
1203 if (loader == NULL) {
1204 Py_DECREF(meta_path);
1205 return NULL; /* true error */
1206 }
1207 if (loader != Py_None) {
1208 /* a loader was found */
1209 *p_loader = loader;
1210 Py_DECREF(meta_path);
1211 return &importhookdescr;
1212 }
1213 Py_DECREF(loader);
1214 }
1215 Py_DECREF(meta_path);
1216 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001217
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001218 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001219 /* The only type of submodule allowed inside a "frozen"
1220 package are other frozen modules or packages. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001221 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001222 PyErr_SetString(PyExc_ImportError,
1223 "full frozen module name too long");
1224 return NULL;
1225 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001226 strcpy(buf, PyString_AsString(path));
Guido van Rossum0506a431998-08-11 15:07:39 +00001227 strcat(buf, ".");
1228 strcat(buf, name);
1229 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001230 if (find_frozen(name) != NULL) {
1231 strcpy(buf, name);
1232 return &fd_frozen;
1233 }
1234 PyErr_Format(PyExc_ImportError,
1235 "No frozen submodule named %.200s", name);
1236 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001237 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001238 if (path == NULL) {
1239 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001240 strcpy(buf, name);
1241 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001242 }
Greg Ward201baee2001-10-04 14:52:06 +00001243 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001244 strcpy(buf, name);
1245 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001246 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
Guido van Rossumac279101996-08-22 23:10:58 +00001248#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001249 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1250 if (fp != NULL) {
1251 *p_fp = fp;
1252 return fdp;
1253 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001254#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001255 path = PySys_GetObject("path");
1256 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001257 if (path == NULL || !PyList_Check(path)) {
1258 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001259 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260 return NULL;
1261 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001262
1263 path_hooks = PySys_GetObject("path_hooks");
1264 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1265 PyErr_SetString(PyExc_ImportError,
1266 "sys.path_hooks must be a list of "
1267 "import hooks");
1268 return NULL;
1269 }
1270 path_importer_cache = PySys_GetObject("path_importer_cache");
1271 if (path_importer_cache == NULL ||
1272 !PyDict_Check(path_importer_cache)) {
1273 PyErr_SetString(PyExc_ImportError,
1274 "sys.path_importer_cache must be a dict");
1275 return NULL;
1276 }
1277
Guido van Rossum79f25d91997-04-29 20:08:16 +00001278 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001279 namelen = strlen(name);
1280 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001281 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001283 if (!v)
1284 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001285#ifdef Py_USING_UNICODE
1286 if (PyUnicode_Check(v)) {
1287 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1288 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1289 if (copy == NULL)
1290 return NULL;
1291 v = copy;
1292 }
1293 else
1294#endif
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001295 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001296 continue;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001297 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001298 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1299 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001300 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001301 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001302 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001303 if (strlen(buf) != len) {
1304 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001305 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001306 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001307
1308 /* sys.path_hooks import hook */
1309 if (p_loader != NULL) {
1310 PyObject *importer;
1311
1312 importer = get_path_importer(path_importer_cache,
1313 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001314 if (importer == NULL) {
1315 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001316 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001317 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001318 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001319 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001320 PyObject *loader;
1321 loader = PyObject_CallMethod(importer,
1322 "find_module",
1323 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001324 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001325 if (loader == NULL)
1326 return NULL; /* error */
1327 if (loader != Py_None) {
1328 /* a loader was found */
1329 *p_loader = loader;
1330 return &importhookdescr;
1331 }
1332 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001333 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001334 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001335 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001336 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001337
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001338 if (len > 0 && buf[len-1] != SEP
1339#ifdef ALTSEP
1340 && buf[len-1] != ALTSEP
1341#endif
1342 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001343 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001344 strcpy(buf+len, name);
1345 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001346
1347 /* Check for package import (buf holds a directory name,
1348 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001349#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001350 if (stat(buf, &statbuf) == 0 && /* it exists */
1351 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001352 case_ok(buf, len, namelen, name)) { /* case matches */
1353 if (find_init_module(buf)) { /* and has __init__.py */
1354 Py_XDECREF(copy);
1355 return &fd_package;
1356 }
1357 else {
1358 char warnstr[MAXPATHLEN+80];
1359 sprintf(warnstr, "Not importing directory "
1360 "'%.*s': missing __init__.py",
1361 MAXPATHLEN, buf);
1362 if (PyErr_Warn(PyExc_ImportWarning,
1363 warnstr)) {
1364 Py_XDECREF(copy);
1365 return NULL;
1366 }
1367 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001368 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001369#else
1370 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001371#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001372 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001373 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001374 if (find_init_module(buf)) {
1375 Py_XDECREF(copy);
1376 return &fd_package;
1377 }
1378 else {
1379 char warnstr[MAXPATHLEN+80];
1380 sprintf(warnstr, "Not importing directory "
1381 "'%.*s': missing __init__.py",
1382 MAXPATHLEN, buf);
1383 if (PyErr_Warn(PyExc_ImportWarning,
1384 warnstr)) {
1385 Py_XDECREF(copy);
1386 return NULL;
1387 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001388 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001389#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001390#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001391#if defined(PYOS_OS2)
1392 /* take a snapshot of the module spec for restoration
1393 * after the 8 character DLL hackery
1394 */
1395 saved_buf = strdup(buf);
1396 saved_len = len;
1397 saved_namelen = namelen;
1398#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001399 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Georg Brandladd36e52007-08-23 18:08:06 +00001400#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001401 /* OS/2 limits DLLs to 8 character names (w/o
1402 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001403 * so if the name is longer than that and its a
1404 * dynamically loaded module we're going to try,
1405 * truncate the name before trying
1406 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001407 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001408 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001409 const struct filedescr *scan;
1410 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001411 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001412 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001413 break;
1414 else
1415 scan++;
1416 }
1417 if (scan->suffix != NULL) {
1418 /* yes, so truncate the name */
1419 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001420 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001421 buf[len] = '\0';
1422 }
1423 }
1424#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001425 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001426 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001427 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001428 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001429 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001430 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001431 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001432 if (fp != NULL) {
1433 if (case_ok(buf, len, namelen, name))
1434 break;
1435 else { /* continue search */
1436 fclose(fp);
1437 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001438 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001439 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001440#if defined(PYOS_OS2)
1441 /* restore the saved snapshot */
1442 strcpy(buf, saved_buf);
1443 len = saved_len;
1444 namelen = saved_namelen;
1445#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001446 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001447#if defined(PYOS_OS2)
1448 /* don't need/want the module name snapshot anymore */
1449 if (saved_buf)
1450 {
1451 free(saved_buf);
1452 saved_buf = NULL;
1453 }
1454#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001455 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001456 if (fp != NULL)
1457 break;
1458 }
1459 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001460 PyErr_Format(PyExc_ImportError,
1461 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001462 return NULL;
1463 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001464 *p_fp = fp;
1465 return fdp;
1466}
1467
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001468/* Helpers for main.c
1469 * Find the source file corresponding to a named module
1470 */
1471struct filedescr *
1472_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1473 size_t buflen, FILE **p_fp, PyObject **p_loader)
1474{
1475 return find_module((char *) name, (char *) name, path,
1476 buf, buflen, p_fp, p_loader);
1477}
1478
1479PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1480{
1481 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1482}
1483
Martin v. Löwis18e16552006-02-15 17:27:45 +00001484/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001485 * The arguments here are tricky, best shown by example:
1486 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1487 * ^ ^ ^ ^
1488 * |--------------------- buf ---------------------|
1489 * |------------------- len ------------------|
1490 * |------ name -------|
1491 * |----- namelen -----|
1492 * buf is the full path, but len only counts up to (& exclusive of) the
1493 * extension. name is the module name, also exclusive of extension.
1494 *
1495 * We've already done a successful stat() or fopen() on buf, so know that
1496 * there's some match, possibly case-insensitive.
1497 *
Tim Peters50d8d372001-02-28 05:34:27 +00001498 * case_ok() is to return 1 if there's a case-sensitive match for
1499 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1500 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001501 *
Tim Peters50d8d372001-02-28 05:34:27 +00001502 * case_ok() is used to implement case-sensitive import semantics even
1503 * on platforms with case-insensitive filesystems. It's trivial to implement
1504 * for case-sensitive filesystems. It's pretty much a cross-platform
1505 * nightmare for systems with case-insensitive filesystems.
1506 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001507
Tim Peters50d8d372001-02-28 05:34:27 +00001508/* First we may need a pile of platform-specific header files; the sequence
1509 * of #if's here should match the sequence in the body of case_ok().
1510 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001511#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001512#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001513
Tim Peters50d8d372001-02-28 05:34:27 +00001514#elif defined(DJGPP)
1515#include <dir.h>
1516
Jason Tishler7961aa62005-05-20 00:56:54 +00001517#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001518#include <sys/types.h>
1519#include <dirent.h>
1520
Andrew MacIntyred9400542002-02-26 11:41:34 +00001521#elif defined(PYOS_OS2)
1522#define INCL_DOS
1523#define INCL_DOSERRORS
1524#define INCL_NOPMAPI
1525#include <os2.h>
1526
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001527#elif defined(RISCOS)
1528#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001529#endif
1530
Guido van Rossum0980bd91998-02-13 17:18:36 +00001531static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001533{
Tim Peters50d8d372001-02-28 05:34:27 +00001534/* Pick a platform-specific implementation; the sequence of #if's here should
1535 * match the sequence just above.
1536 */
1537
Jason Tishler7961aa62005-05-20 00:56:54 +00001538/* MS_WINDOWS */
1539#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001540 WIN32_FIND_DATA data;
1541 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001542
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001543 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001544 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001545
Guido van Rossum0980bd91998-02-13 17:18:36 +00001546 h = FindFirstFile(buf, &data);
1547 if (h == INVALID_HANDLE_VALUE) {
1548 PyErr_Format(PyExc_NameError,
1549 "Can't find file for module %.100s\n(filename %.300s)",
1550 name, buf);
1551 return 0;
1552 }
1553 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001554 return strncmp(data.cFileName, name, namelen) == 0;
1555
1556/* DJGPP */
1557#elif defined(DJGPP)
1558 struct ffblk ffblk;
1559 int done;
1560
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001561 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001562 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001563
1564 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1565 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001566 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001567 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001568 name, buf);
1569 return 0;
1570 }
Tim Peters50d8d372001-02-28 05:34:27 +00001571 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001572
Jason Tishler7961aa62005-05-20 00:56:54 +00001573/* new-fangled macintosh (macosx) or Cygwin */
1574#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001575 DIR *dirp;
1576 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001577 char dirname[MAXPATHLEN + 1];
1578 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001579
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001580 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001581 return 1;
1582
Tim Petersd1e87a82001-03-01 18:12:00 +00001583 /* Copy the dir component into dirname; substitute "." if empty */
1584 if (dirlen <= 0) {
1585 dirname[0] = '.';
1586 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001587 }
1588 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001589 assert(dirlen <= MAXPATHLEN);
1590 memcpy(dirname, buf, dirlen);
1591 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001592 }
1593 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001594 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001595 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001596 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001597 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001598 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001599#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001600 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001601#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001602 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001603#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001604 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001605 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001606 (void)closedir(dirp);
1607 return 1; /* Found */
1608 }
1609 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001610 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001611 }
Tim Peters430f5d42001-03-01 01:30:56 +00001612 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001613
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001614/* RISC OS */
1615#elif defined(RISCOS)
1616 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1617 char buf2[MAXPATHLEN+2];
1618 char *nameWithExt = buf+len-namelen;
1619 int canonlen;
1620 os_error *e;
1621
1622 if (Py_GETENV("PYTHONCASEOK") != NULL)
1623 return 1;
1624
1625 /* workaround:
1626 append wildcard, otherwise case of filename wouldn't be touched */
1627 strcpy(buf2, buf);
1628 strcat(buf2, "*");
1629
1630 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1631 canonlen = MAXPATHLEN+1-canonlen;
1632 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1633 return 0;
1634 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1635 return 1; /* match */
1636
1637 return 0;
1638
Andrew MacIntyred9400542002-02-26 11:41:34 +00001639/* OS/2 */
1640#elif defined(PYOS_OS2)
1641 HDIR hdir = 1;
1642 ULONG srchcnt = 1;
1643 FILEFINDBUF3 ffbuf;
1644 APIRET rc;
1645
Georg Brandlaed6c662008-01-07 17:25:53 +00001646 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001647 return 1;
1648
1649 rc = DosFindFirst(buf,
1650 &hdir,
1651 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1652 &ffbuf, sizeof(ffbuf),
1653 &srchcnt,
1654 FIL_STANDARD);
1655 if (rc != NO_ERROR)
1656 return 0;
1657 return strncmp(ffbuf.achName, name, namelen) == 0;
1658
Tim Peters50d8d372001-02-28 05:34:27 +00001659/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1660#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001661 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001662
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001663#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001664}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001665
Guido van Rossum0980bd91998-02-13 17:18:36 +00001666
Guido van Rossum197346f1997-10-31 18:38:52 +00001667#ifdef HAVE_STAT
1668/* Helper to look for __init__.py or __init__.py[co] in potential package */
1669static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001670find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001671{
Tim Peters0f9431f2001-07-05 03:47:53 +00001672 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001673 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001674 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001675 struct stat statbuf;
1676
Tim Peters0f9431f2001-07-05 03:47:53 +00001677/* For calling case_ok(buf, len, namelen, name):
1678 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1679 * ^ ^ ^ ^
1680 * |--------------------- buf ---------------------|
1681 * |------------------- len ------------------|
1682 * |------ name -------|
1683 * |----- namelen -----|
1684 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001685 if (save_len + 13 >= MAXPATHLEN)
1686 return 0;
1687 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001688 pname = buf + i;
1689 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001690 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001691 if (case_ok(buf,
1692 save_len + 9, /* len("/__init__") */
1693 8, /* len("__init__") */
1694 pname)) {
1695 buf[save_len] = '\0';
1696 return 1;
1697 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001698 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001699 i += strlen(pname);
1700 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001701 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001702 if (case_ok(buf,
1703 save_len + 9, /* len("/__init__") */
1704 8, /* len("__init__") */
1705 pname)) {
1706 buf[save_len] = '\0';
1707 return 1;
1708 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001709 }
1710 buf[save_len] = '\0';
1711 return 0;
1712}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001713
1714#else
1715
1716#ifdef RISCOS
1717static int
1718find_init_module(buf)
1719 char *buf;
1720{
1721 int save_len = strlen(buf);
1722 int i = save_len;
1723
1724 if (save_len + 13 >= MAXPATHLEN)
1725 return 0;
1726 buf[i++] = SEP;
1727 strcpy(buf+i, "__init__/py");
1728 if (isfile(buf)) {
1729 buf[save_len] = '\0';
1730 return 1;
1731 }
1732
1733 if (Py_OptimizeFlag)
1734 strcpy(buf+i, "o");
1735 else
1736 strcpy(buf+i, "c");
1737 if (isfile(buf)) {
1738 buf[save_len] = '\0';
1739 return 1;
1740 }
1741 buf[save_len] = '\0';
1742 return 0;
1743}
1744#endif /*RISCOS*/
1745
Guido van Rossum197346f1997-10-31 18:38:52 +00001746#endif /* HAVE_STAT */
1747
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001748
Tim Petersdbd9ba62000-07-09 03:09:57 +00001749static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001750
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001751/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001752 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001753
Guido van Rossum79f25d91997-04-29 20:08:16 +00001754static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001755load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001756{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001757 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001758 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001759 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001760
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001761 /* First check that there's an open file (if we need one) */
1762 switch (type) {
1763 case PY_SOURCE:
1764 case PY_COMPILED:
1765 if (fp == NULL) {
1766 PyErr_Format(PyExc_ValueError,
1767 "file object required for import (type code %d)",
1768 type);
1769 return NULL;
1770 }
1771 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001773 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774
1775 case PY_SOURCE:
1776 m = load_source_module(name, buf, fp);
1777 break;
1778
1779 case PY_COMPILED:
1780 m = load_compiled_module(name, buf, fp);
1781 break;
1782
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001783#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001784 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001785 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001786 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001787#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001788
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001789 case PKG_DIRECTORY:
1790 m = load_package(name, buf);
1791 break;
1792
1793 case C_BUILTIN:
1794 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001795 if (buf != NULL && buf[0] != '\0')
1796 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001797 if (type == C_BUILTIN)
1798 err = init_builtin(name);
1799 else
1800 err = PyImport_ImportFrozenModule(name);
1801 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001802 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001803 if (err == 0) {
1804 PyErr_Format(PyExc_ImportError,
1805 "Purported %s module %.200s not found",
1806 type == C_BUILTIN ?
1807 "builtin" : "frozen",
1808 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001809 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001810 }
1811 modules = PyImport_GetModuleDict();
1812 m = PyDict_GetItemString(modules, name);
1813 if (m == NULL) {
1814 PyErr_Format(
1815 PyExc_ImportError,
1816 "%s module %.200s not properly initialized",
1817 type == C_BUILTIN ?
1818 "builtin" : "frozen",
1819 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001820 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001821 }
1822 Py_INCREF(m);
1823 break;
1824
Just van Rossum52e14d62002-12-30 22:08:05 +00001825 case IMP_HOOK: {
1826 if (loader == NULL) {
1827 PyErr_SetString(PyExc_ImportError,
1828 "import hook without loader");
1829 return NULL;
1830 }
1831 m = PyObject_CallMethod(loader, "load_module", "s", name);
1832 break;
1833 }
1834
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001835 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001836 PyErr_Format(PyExc_ImportError,
1837 "Don't know how to import %.200s (type code %d)",
1838 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001839 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
1841 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001842
1843 return m;
1844}
1845
1846
1847/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001848 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001849 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001850
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001851static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001852init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001853{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001854 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001855
Greg Ward201baee2001-10-04 14:52:06 +00001856 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001857 return 1;
1858
Guido van Rossum771c6c81997-10-31 18:37:24 +00001859 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001860 if (strcmp(name, p->name) == 0) {
1861 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001862 PyErr_Format(PyExc_ImportError,
1863 "Cannot re-init internal module %.200s",
1864 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001865 return -1;
1866 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001867 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001868 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001869 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001870 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001871 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001872 if (_PyImport_FixupExtension(name, name) == NULL)
1873 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001874 return 1;
1875 }
1876 }
1877 return 0;
1878}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001879
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001880
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001881/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001882
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001883static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001884find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001885{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001886 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001887
Guido van Rossum79f25d91997-04-29 20:08:16 +00001888 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001889 if (p->name == NULL)
1890 return NULL;
1891 if (strcmp(p->name, name) == 0)
1892 break;
1893 }
1894 return p;
1895}
1896
Guido van Rossum79f25d91997-04-29 20:08:16 +00001897static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001898get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001899{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001900 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001901 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001902
1903 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001904 PyErr_Format(PyExc_ImportError,
1905 "No such frozen object named %.200s",
1906 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001907 return NULL;
1908 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001909 if (p->code == NULL) {
1910 PyErr_Format(PyExc_ImportError,
1911 "Excluded frozen object named %.200s",
1912 name);
1913 return NULL;
1914 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001915 size = p->size;
1916 if (size < 0)
1917 size = -size;
1918 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001919}
1920
1921/* Initialize a frozen module.
1922 Return 1 for succes, 0 if the module is not found, and -1 with
1923 an exception set if the initialization failed.
1924 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001925
1926int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001927PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001928{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001929 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001930 PyObject *co;
1931 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001932 int ispackage;
1933 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001934
1935 if (p == NULL)
1936 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001937 if (p->code == NULL) {
1938 PyErr_Format(PyExc_ImportError,
1939 "Excluded frozen object named %.200s",
1940 name);
1941 return -1;
1942 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001943 size = p->size;
1944 ispackage = (size < 0);
1945 if (ispackage)
1946 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001947 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001948 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001949 name, ispackage ? " package" : "");
1950 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001951 if (co == NULL)
1952 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001953 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001954 PyErr_Format(PyExc_TypeError,
1955 "frozen object %.200s is not a code object",
1956 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001957 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001958 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001959 if (ispackage) {
1960 /* Set __path__ to the package name */
1961 PyObject *d, *s;
1962 int err;
1963 m = PyImport_AddModule(name);
1964 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001965 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001966 d = PyModule_GetDict(m);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001967 s = PyString_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001968 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001969 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001970 err = PyDict_SetItemString(d, "__path__", s);
1971 Py_DECREF(s);
1972 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001973 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001974 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001975 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001976 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001977 goto err_return;
1978 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001979 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001980 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001981err_return:
1982 Py_DECREF(co);
1983 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001984}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001985
1986
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001987/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001988 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001989
Guido van Rossum79f25d91997-04-29 20:08:16 +00001990PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001991PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001992{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001993 PyObject *pname;
1994 PyObject *result;
1995
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001996 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001997 if (pname == NULL)
1998 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001999 result = PyImport_Import(pname);
2000 Py_DECREF(pname);
2001 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002002}
2003
Christian Heimes000a0742008-01-03 22:16:32 +00002004/* Import a module without blocking
2005 *
2006 * At first it tries to fetch the module from sys.modules. If the module was
2007 * never loaded before it loads it with PyImport_ImportModule() unless another
2008 * thread holds the import lock. In the latter case the function raises an
2009 * ImportError instead of blocking.
2010 *
2011 * Returns the module object with incremented ref count.
2012 */
2013PyObject *
2014PyImport_ImportModuleNoBlock(const char *name)
2015{
2016 PyObject *result;
2017 PyObject *modules;
2018 long me;
2019
2020 /* Try to get the module from sys.modules[name] */
2021 modules = PyImport_GetModuleDict();
2022 if (modules == NULL)
2023 return NULL;
2024
2025 result = PyDict_GetItemString(modules, name);
2026 if (result != NULL) {
2027 Py_INCREF(result);
2028 return result;
2029 }
2030 else {
2031 PyErr_Clear();
2032 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002033#ifdef WITH_THREAD
Christian Heimes000a0742008-01-03 22:16:32 +00002034 /* check the import lock
2035 * me might be -1 but I ignore the error here, the lock function
2036 * takes care of the problem */
2037 me = PyThread_get_thread_ident();
2038 if (import_lock_thread == -1 || import_lock_thread == me) {
2039 /* no thread or me is holding the lock */
2040 return PyImport_ImportModule(name);
2041 }
2042 else {
2043 PyErr_Format(PyExc_ImportError,
2044 "Failed to import %.200s because the import lock"
2045 "is held by another thread.",
2046 name);
2047 return NULL;
2048 }
Benjamin Peterson17f03ca2008-09-01 14:18:30 +00002049#else
2050 return PyImport_ImportModule(name);
2051#endif
Christian Heimes000a0742008-01-03 22:16:32 +00002052}
2053
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002054/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002055static PyObject *get_parent(PyObject *globals, char *buf,
2056 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002057static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002058 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002059static int mark_miss(char *name);
2060static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002061 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002062static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002063
2064/* The Magnum Opus of dotted-name import :-) */
2065
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002066static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002067import_module_level(char *name, PyObject *globals, PyObject *locals,
2068 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002069{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002070 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002071 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002072 PyObject *parent, *head, *next, *tail;
2073
Christian Heimes3403f152008-01-09 19:56:33 +00002074 if (strchr(name, '/') != NULL
2075#ifdef MS_WINDOWS
2076 || strchr(name, '\\') != NULL
2077#endif
2078 ) {
2079 PyErr_SetString(PyExc_ImportError,
2080 "Import by filename is not supported.");
2081 return NULL;
2082 }
2083
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002084 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002085 if (parent == NULL)
2086 return NULL;
2087
2088 head = load_next(parent, Py_None, &name, buf, &buflen);
2089 if (head == NULL)
2090 return NULL;
2091
2092 tail = head;
2093 Py_INCREF(tail);
2094 while (name) {
2095 next = load_next(tail, tail, &name, buf, &buflen);
2096 Py_DECREF(tail);
2097 if (next == NULL) {
2098 Py_DECREF(head);
2099 return NULL;
2100 }
2101 tail = next;
2102 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002103 if (tail == Py_None) {
2104 /* If tail is Py_None, both get_parent and load_next found
2105 an empty module name: someone called __import__("") or
2106 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002107 Py_DECREF(tail);
2108 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002109 PyErr_SetString(PyExc_ValueError,
2110 "Empty module name");
2111 return NULL;
2112 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002113
2114 if (fromlist != NULL) {
2115 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2116 fromlist = NULL;
2117 }
2118
2119 if (fromlist == NULL) {
2120 Py_DECREF(tail);
2121 return head;
2122 }
2123
2124 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002125 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002126 Py_DECREF(tail);
2127 return NULL;
2128 }
2129
2130 return tail;
2131}
2132
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002133PyObject *
2134PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2135 PyObject *fromlist, int level)
2136{
2137 PyObject *result;
2138 lock_import();
2139 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002140 if (unlock_import() < 0) {
2141 Py_XDECREF(result);
2142 PyErr_SetString(PyExc_RuntimeError,
2143 "not holding the import lock");
2144 return NULL;
2145 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002146 return result;
2147}
2148
Fred Drake87590902004-05-28 20:21:36 +00002149/* Return the package that an import is being performed in. If globals comes
2150 from the module foo.bar.bat (not itself a package), this returns the
2151 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002152 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002153
2154 The *name* of the returned package is returned in buf, with the length of
2155 the name in *p_buflen.
2156
2157 If globals doesn't come from a package or a module in a package, or a
2158 corresponding entry is not found in sys.modules, Py_None is returned.
2159*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002160static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002161get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002162{
2163 static PyObject *namestr = NULL;
2164 static PyObject *pathstr = NULL;
Nick Coghlanef01d822007-12-03 12:55:17 +00002165 static PyObject *pkgstr = NULL;
2166 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Nick Coghlanb028f502008-07-13 14:52:36 +00002167 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002168
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002169 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002170 return Py_None;
2171
2172 if (namestr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002173 namestr = PyString_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002174 if (namestr == NULL)
2175 return NULL;
2176 }
2177 if (pathstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002178 pathstr = PyString_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002179 if (pathstr == NULL)
2180 return NULL;
2181 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002182 if (pkgstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002183 pkgstr = PyString_InternFromString("__package__");
Nick Coghlanef01d822007-12-03 12:55:17 +00002184 if (pkgstr == NULL)
2185 return NULL;
2186 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002187
2188 *buf = '\0';
2189 *p_buflen = 0;
Nick Coghlanef01d822007-12-03 12:55:17 +00002190 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002191
Nick Coghlanef01d822007-12-03 12:55:17 +00002192 if ((pkgname != NULL) && (pkgname != Py_None)) {
2193 /* __package__ is set, so use it */
2194 Py_ssize_t len;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002195 if (!PyString_Check(pkgname)) {
Nick Coghlanef01d822007-12-03 12:55:17 +00002196 PyErr_SetString(PyExc_ValueError,
2197 "__package__ set to non-string");
2198 return NULL;
2199 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002200 len = PyString_GET_SIZE(pkgname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002201 if (len == 0) {
2202 if (level > 0) {
2203 PyErr_SetString(PyExc_ValueError,
2204 "Attempted relative import in non-package");
2205 return NULL;
2206 }
2207 return Py_None;
2208 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002209 if (len > MAXPATHLEN) {
2210 PyErr_SetString(PyExc_ValueError,
Nick Coghlanef01d822007-12-03 12:55:17 +00002211 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002212 return NULL;
2213 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002214 strcpy(buf, PyString_AS_STRING(pkgname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002215 } else {
2216 /* __package__ not set, so figure it out and set it */
2217 modname = PyDict_GetItem(globals, namestr);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002218 if (modname == NULL || !PyString_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002219 return Py_None;
Nick Coghlanef01d822007-12-03 12:55:17 +00002220
2221 modpath = PyDict_GetItem(globals, pathstr);
2222 if (modpath != NULL) {
2223 /* __path__ is set, so modname is already the package name */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002224 Py_ssize_t len = PyString_GET_SIZE(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002225 int error;
2226 if (len > MAXPATHLEN) {
2227 PyErr_SetString(PyExc_ValueError,
2228 "Module name too long");
2229 return NULL;
2230 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002231 strcpy(buf, PyString_AS_STRING(modname));
Nick Coghlanef01d822007-12-03 12:55:17 +00002232 error = PyDict_SetItem(globals, pkgstr, modname);
2233 if (error) {
2234 PyErr_SetString(PyExc_ValueError,
2235 "Could not set __package__");
2236 return NULL;
2237 }
2238 } else {
2239 /* Normal module, so work out the package name if any */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002240 char *start = PyString_AS_STRING(modname);
Nick Coghlanef01d822007-12-03 12:55:17 +00002241 char *lastdot = strrchr(start, '.');
2242 size_t len;
2243 int error;
2244 if (lastdot == NULL && level > 0) {
2245 PyErr_SetString(PyExc_ValueError,
2246 "Attempted relative import in non-package");
2247 return NULL;
2248 }
2249 if (lastdot == NULL) {
2250 error = PyDict_SetItem(globals, pkgstr, Py_None);
2251 if (error) {
2252 PyErr_SetString(PyExc_ValueError,
2253 "Could not set __package__");
2254 return NULL;
2255 }
2256 return Py_None;
2257 }
2258 len = lastdot - start;
2259 if (len >= MAXPATHLEN) {
2260 PyErr_SetString(PyExc_ValueError,
2261 "Module name too long");
2262 return NULL;
2263 }
2264 strncpy(buf, start, len);
2265 buf[len] = '\0';
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002266 pkgname = PyString_FromString(buf);
Nick Coghlanef01d822007-12-03 12:55:17 +00002267 if (pkgname == NULL) {
2268 return NULL;
2269 }
2270 error = PyDict_SetItem(globals, pkgstr, pkgname);
2271 Py_DECREF(pkgname);
2272 if (error) {
2273 PyErr_SetString(PyExc_ValueError,
2274 "Could not set __package__");
2275 return NULL;
2276 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002277 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002278 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002279 while (--level > 0) {
2280 char *dot = strrchr(buf, '.');
2281 if (dot == NULL) {
2282 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002283 "Attempted relative import beyond "
2284 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002285 return NULL;
2286 }
2287 *dot = '\0';
2288 }
2289 *p_buflen = strlen(buf);
2290
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002291 modules = PyImport_GetModuleDict();
2292 parent = PyDict_GetItemString(modules, buf);
Nick Coghlanb028f502008-07-13 14:52:36 +00002293 if (parent == NULL) {
2294 if (orig_level < 1) {
2295 PyObject *err_msg = PyString_FromFormat(
2296 "Parent module '%.200s' not found "
2297 "while handling absolute import", buf);
2298 if (err_msg == NULL) {
2299 return NULL;
2300 }
2301 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2302 PyString_AsString(err_msg), 1)) {
2303 *buf = '\0';
2304 *p_buflen = 0;
2305 parent = Py_None;
2306 }
2307 Py_DECREF(err_msg);
2308 } else {
2309 PyErr_Format(PyExc_SystemError,
2310 "Parent module '%.200s' not loaded, "
2311 "cannot perform relative import", buf);
2312 }
2313 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002314 return parent;
2315 /* We expect, but can't guarantee, if parent != None, that:
2316 - parent.__name__ == buf
2317 - parent.__dict__ is globals
2318 If this is violated... Who cares? */
2319}
2320
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002321/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002322static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002323load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002324 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002325{
2326 char *name = *p_name;
2327 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002328 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002329 char *p;
2330 PyObject *result;
2331
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002332 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002333 /* completely empty module name should only happen in
2334 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002335 Py_INCREF(mod);
2336 *p_name = NULL;
2337 return mod;
2338 }
2339
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002340 if (dot == NULL) {
2341 *p_name = NULL;
2342 len = strlen(name);
2343 }
2344 else {
2345 *p_name = dot+1;
2346 len = dot-name;
2347 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002348 if (len == 0) {
2349 PyErr_SetString(PyExc_ValueError,
2350 "Empty module name");
2351 return NULL;
2352 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002353
2354 p = buf + *p_buflen;
2355 if (p != buf)
2356 *p++ = '.';
2357 if (p+len-buf >= MAXPATHLEN) {
2358 PyErr_SetString(PyExc_ValueError,
2359 "Module name too long");
2360 return NULL;
2361 }
2362 strncpy(p, name, len);
2363 p[len] = '\0';
2364 *p_buflen = p+len-buf;
2365
2366 result = import_submodule(mod, p, buf);
2367 if (result == Py_None && altmod != mod) {
2368 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002369 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002370 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002371 if (result != NULL && result != Py_None) {
2372 if (mark_miss(buf) != 0) {
2373 Py_DECREF(result);
2374 return NULL;
2375 }
2376 strncpy(buf, name, len);
2377 buf[len] = '\0';
2378 *p_buflen = len;
2379 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002380 }
2381 if (result == NULL)
2382 return NULL;
2383
2384 if (result == Py_None) {
2385 Py_DECREF(result);
2386 PyErr_Format(PyExc_ImportError,
2387 "No module named %.200s", name);
2388 return NULL;
2389 }
2390
2391 return result;
2392}
2393
2394static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002395mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002396{
2397 PyObject *modules = PyImport_GetModuleDict();
2398 return PyDict_SetItemString(modules, name, Py_None);
2399}
2400
2401static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002402ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002403 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002404{
2405 int i;
2406
2407 if (!PyObject_HasAttrString(mod, "__path__"))
2408 return 1;
2409
2410 for (i = 0; ; i++) {
2411 PyObject *item = PySequence_GetItem(fromlist, i);
2412 int hasit;
2413 if (item == NULL) {
2414 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2415 PyErr_Clear();
2416 return 1;
2417 }
2418 return 0;
2419 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002420 if (!PyString_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002421 PyErr_SetString(PyExc_TypeError,
2422 "Item in ``from list'' not a string");
2423 Py_DECREF(item);
2424 return 0;
2425 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002426 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002427 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002428 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002429 /* See if the package defines __all__ */
2430 if (recursive)
2431 continue; /* Avoid endless recursion */
2432 all = PyObject_GetAttrString(mod, "__all__");
2433 if (all == NULL)
2434 PyErr_Clear();
2435 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002436 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002437 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002438 if (!ret)
2439 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002440 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002441 continue;
2442 }
2443 hasit = PyObject_HasAttr(mod, item);
2444 if (!hasit) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002445 char *subname = PyString_AS_STRING(item);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002446 PyObject *submod;
2447 char *p;
2448 if (buflen + strlen(subname) >= MAXPATHLEN) {
2449 PyErr_SetString(PyExc_ValueError,
2450 "Module name too long");
2451 Py_DECREF(item);
2452 return 0;
2453 }
2454 p = buf + buflen;
2455 *p++ = '.';
2456 strcpy(p, subname);
2457 submod = import_submodule(mod, subname, buf);
2458 Py_XDECREF(submod);
2459 if (submod == NULL) {
2460 Py_DECREF(item);
2461 return 0;
2462 }
2463 }
2464 Py_DECREF(item);
2465 }
2466
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002467 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002468}
2469
Neil Schemenauer00b09662003-06-16 21:03:07 +00002470static int
2471add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2472 PyObject *modules)
2473{
2474 if (mod == Py_None)
2475 return 1;
2476 /* Irrespective of the success of this load, make a
2477 reference to it in the parent package module. A copy gets
2478 saved in the modules dictionary under the full name, so get a
2479 reference from there, if need be. (The exception is when the
2480 load failed with a SyntaxError -- then there's no trace in
2481 sys.modules. In that case, of course, do nothing extra.) */
2482 if (submod == NULL) {
2483 submod = PyDict_GetItemString(modules, fullname);
2484 if (submod == NULL)
2485 return 1;
2486 }
2487 if (PyModule_Check(mod)) {
2488 /* We can't use setattr here since it can give a
2489 * spurious warning if the submodule name shadows a
2490 * builtin name */
2491 PyObject *dict = PyModule_GetDict(mod);
2492 if (!dict)
2493 return 0;
2494 if (PyDict_SetItemString(dict, subname, submod) < 0)
2495 return 0;
2496 }
2497 else {
2498 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2499 return 0;
2500 }
2501 return 1;
2502}
2503
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002504static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002505import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002506{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002507 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002508 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002509
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002510 /* Require:
2511 if mod == None: subname == fullname
2512 else: mod.__name__ + "." + subname == fullname
2513 */
2514
Tim Peters50d8d372001-02-28 05:34:27 +00002515 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002516 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002517 }
2518 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002519 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002520 char buf[MAXPATHLEN+1];
2521 struct filedescr *fdp;
2522 FILE *fp = NULL;
2523
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002524 if (mod == Py_None)
2525 path = NULL;
2526 else {
2527 path = PyObject_GetAttrString(mod, "__path__");
2528 if (path == NULL) {
2529 PyErr_Clear();
2530 Py_INCREF(Py_None);
2531 return Py_None;
2532 }
2533 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002534
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002535 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002536 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2537 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002538 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002539 if (fdp == NULL) {
2540 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2541 return NULL;
2542 PyErr_Clear();
2543 Py_INCREF(Py_None);
2544 return Py_None;
2545 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002546 m = load_module(fullname, fp, buf, fdp->type, loader);
2547 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002548 if (fp)
2549 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002550 if (!add_submodule(mod, m, fullname, subname, modules)) {
2551 Py_XDECREF(m);
2552 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002553 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002554 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002555
2556 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002557}
2558
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002559
2560/* Re-import a module of any kind and return its module object, WITH
2561 INCREMENTED REFERENCE COUNT */
2562
Guido van Rossum79f25d91997-04-29 20:08:16 +00002563PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002564PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002565{
Collin Winter47c52a82007-03-13 23:02:15 +00002566 PyInterpreterState *interp = PyThreadState_Get()->interp;
2567 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002568 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002569 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002570 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002571 char buf[MAXPATHLEN+1];
2572 struct filedescr *fdp;
2573 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002574 PyObject *newm;
Collin Winter47c52a82007-03-13 23:02:15 +00002575
2576 if (modules_reloading == NULL) {
2577 Py_FatalError("PyImport_ReloadModule: "
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002578 "no modules_reloading dictionary!");
Collin Winter47c52a82007-03-13 23:02:15 +00002579 return NULL;
2580 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002581
Guido van Rossum79f25d91997-04-29 20:08:16 +00002582 if (m == NULL || !PyModule_Check(m)) {
2583 PyErr_SetString(PyExc_TypeError,
2584 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002585 return NULL;
2586 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002587 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002588 if (name == NULL)
2589 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002590 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002591 PyErr_Format(PyExc_ImportError,
2592 "reload(): module %.200s not in sys.modules",
2593 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002594 return NULL;
2595 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002596 existing_m = PyDict_GetItemString(modules_reloading, name);
2597 if (existing_m != NULL) {
2598 /* Due to a recursive reload, this module is already
2599 being reloaded. */
2600 Py_INCREF(existing_m);
2601 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002602 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002603 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2604 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002605
Guido van Rossum222ef561997-09-06 19:41:09 +00002606 subname = strrchr(name, '.');
2607 if (subname == NULL)
2608 subname = name;
2609 else {
2610 PyObject *parentname, *parent;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002611 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002612 if (parentname == NULL) {
2613 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002614 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002615 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002616 parent = PyDict_GetItem(modules, parentname);
2617 if (parent == NULL) {
2618 PyErr_Format(PyExc_ImportError,
2619 "reload(): parent %.200s not in sys.modules",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002620 PyString_AS_STRING(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002621 Py_DECREF(parentname);
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002622 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002623 return NULL;
2624 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002625 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002626 subname++;
2627 path = PyObject_GetAttrString(parent, "__path__");
2628 if (path == NULL)
2629 PyErr_Clear();
2630 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002631 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002632 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002633 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002634
2635 if (fdp == NULL) {
2636 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002637 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002638 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002639 }
2640
2641 newm = load_module(name, fp, buf, fdp->type, loader);
2642 Py_XDECREF(loader);
2643
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002644 if (fp)
2645 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002646 if (newm == NULL) {
2647 /* load_module probably removed name from modules because of
2648 * the error. Put back the original module object. We're
2649 * going to return NULL in this case regardless of whether
2650 * replacing name succeeds, so the return value is ignored.
2651 */
2652 PyDict_SetItemString(modules, name, m);
2653 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002654 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002655 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002656}
2657
2658
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002659/* Higher-level import emulator which emulates the "import" statement
2660 more accurately -- it invokes the __import__() function from the
2661 builtins of the current globals. This means that the import is
2662 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002663 environment, e.g. by "rexec".
2664 A dummy list ["__doc__"] is passed as the 4th argument so that
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002665 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002666 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002667
2668PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002669PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002670{
2671 static PyObject *silly_list = NULL;
2672 static PyObject *builtins_str = NULL;
2673 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002674 PyObject *globals = NULL;
2675 PyObject *import = NULL;
2676 PyObject *builtins = NULL;
2677 PyObject *r = NULL;
2678
2679 /* Initialize constant string objects */
2680 if (silly_list == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002681 import_str = PyString_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002682 if (import_str == NULL)
2683 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002684 builtins_str = PyString_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002685 if (builtins_str == NULL)
2686 return NULL;
2687 silly_list = Py_BuildValue("[s]", "__doc__");
2688 if (silly_list == NULL)
2689 return NULL;
2690 }
2691
2692 /* Get the builtins from current globals */
2693 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002694 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002695 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002696 builtins = PyObject_GetItem(globals, builtins_str);
2697 if (builtins == NULL)
2698 goto err;
2699 }
2700 else {
2701 /* No globals -- use standard builtins, and fake globals */
2702 PyErr_Clear();
2703
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002704 builtins = PyImport_ImportModuleLevel("__builtin__",
2705 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002706 if (builtins == NULL)
2707 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002708 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2709 if (globals == NULL)
2710 goto err;
2711 }
2712
2713 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002715 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 if (import == NULL)
2717 PyErr_SetObject(PyExc_KeyError, import_str);
2718 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002719 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002720 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002721 if (import == NULL)
2722 goto err;
2723
Christian Heimes000a0742008-01-03 22:16:32 +00002724 /* Call the __import__ function with the proper argument list
2725 * Always use absolute import here. */
2726 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2727 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002728
2729 err:
2730 Py_XDECREF(globals);
2731 Py_XDECREF(builtins);
2732 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002733
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002734 return r;
2735}
2736
2737
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002738/* Module 'imp' provides Python access to the primitives used for
2739 importing modules.
2740*/
2741
Guido van Rossum79f25d91997-04-29 20:08:16 +00002742static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002743imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002744{
2745 char buf[4];
2746
Guido van Rossum96774c12000-05-01 20:19:08 +00002747 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2748 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2749 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2750 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002751
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002752 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002753}
2754
Guido van Rossum79f25d91997-04-29 20:08:16 +00002755static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002756imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002757{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002758 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002759 struct filedescr *fdp;
2760
Guido van Rossum79f25d91997-04-29 20:08:16 +00002761 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002762 if (list == NULL)
2763 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002764 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2765 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002766 fdp->suffix, fdp->mode, fdp->type);
2767 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002768 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002769 return NULL;
2770 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002771 if (PyList_Append(list, item) < 0) {
2772 Py_DECREF(list);
2773 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002774 return NULL;
2775 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002776 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002777 }
2778 return list;
2779}
2780
Guido van Rossum79f25d91997-04-29 20:08:16 +00002781static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002782call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002783{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002784 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002785 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002786 struct filedescr *fdp;
2787 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002788 FILE *fp = NULL;
2789
2790 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002791 if (path == Py_None)
2792 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002793 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002794 if (fdp == NULL)
2795 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002796 if (fp != NULL) {
2797 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2798 if (fob == NULL) {
2799 fclose(fp);
2800 return NULL;
2801 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002802 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002803 else {
2804 fob = Py_None;
2805 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002806 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002807 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002809 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002810 return ret;
2811}
2812
Guido van Rossum79f25d91997-04-29 20:08:16 +00002813static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002814imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002815{
2816 char *name;
2817 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002818 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002819 return NULL;
2820 return call_find_module(name, path);
2821}
2822
2823static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002824imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002825{
2826 char *name;
2827 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002828 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002829 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002830 return NULL;
2831 ret = init_builtin(name);
2832 if (ret < 0)
2833 return NULL;
2834 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002835 Py_INCREF(Py_None);
2836 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002837 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002838 m = PyImport_AddModule(name);
2839 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002840 return m;
2841}
2842
Guido van Rossum79f25d91997-04-29 20:08:16 +00002843static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002844imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002845{
2846 char *name;
2847 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002848 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002849 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002850 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002851 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002852 if (ret < 0)
2853 return NULL;
2854 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002855 Py_INCREF(Py_None);
2856 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002857 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002858 m = PyImport_AddModule(name);
2859 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002860 return m;
2861}
2862
Guido van Rossum79f25d91997-04-29 20:08:16 +00002863static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002864imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002865{
2866 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002867
Guido van Rossum43713e52000-02-29 13:59:29 +00002868 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002869 return NULL;
2870 return get_frozen_object(name);
2871}
2872
Guido van Rossum79f25d91997-04-29 20:08:16 +00002873static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002874imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002875{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002877 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002878 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002879 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002880}
2881
Guido van Rossum79f25d91997-04-29 20:08:16 +00002882static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002883imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002884{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002885 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002886 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002887 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002888 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002889 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002890 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002891}
2892
2893static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002894get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002895{
2896 FILE *fp;
2897 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002898 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002899 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002900 fp = fopen(pathname, mode);
2901 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002902 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002903 }
2904 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002905 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002906 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002907 PyErr_SetString(PyExc_ValueError,
2908 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002909 }
2910 return fp;
2911}
2912
Guido van Rossum79f25d91997-04-29 20:08:16 +00002913static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002914imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002915{
2916 char *name;
2917 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002918 PyObject *fob = NULL;
2919 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002920 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002921 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002922 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002923 return NULL;
2924 fp = get_file(pathname, fob, "rb");
2925 if (fp == NULL)
2926 return NULL;
2927 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002928 if (fob == NULL)
2929 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002930 return m;
2931}
2932
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002933#ifdef HAVE_DYNAMIC_LOADING
2934
Guido van Rossum79f25d91997-04-29 20:08:16 +00002935static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002936imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002937{
2938 char *name;
2939 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002940 PyObject *fob = NULL;
2941 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002942 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002943 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002944 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002945 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002946 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002947 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002948 if (fp == NULL)
2949 return NULL;
2950 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002951 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002952 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002953}
2954
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002955#endif /* HAVE_DYNAMIC_LOADING */
2956
Guido van Rossum79f25d91997-04-29 20:08:16 +00002957static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002958imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002959{
2960 char *name;
2961 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002962 PyObject *fob = NULL;
2963 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002964 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002965 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002966 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002967 return NULL;
2968 fp = get_file(pathname, fob, "r");
2969 if (fp == NULL)
2970 return NULL;
2971 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002972 if (fob == NULL)
2973 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002974 return m;
2975}
2976
Guido van Rossum79f25d91997-04-29 20:08:16 +00002977static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002978imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002979{
2980 char *name;
2981 PyObject *fob;
2982 char *pathname;
2983 char *suffix; /* Unused */
2984 char *mode;
2985 int type;
2986 FILE *fp;
2987
Guido van Rossum43713e52000-02-29 13:59:29 +00002988 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002989 &name, &fob, &pathname,
2990 &suffix, &mode, &type))
2991 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002992 if (*mode) {
2993 /* Mode must start with 'r' or 'U' and must not contain '+'.
2994 Implicit in this test is the assumption that the mode
2995 may contain other modifiers like 'b' or 't'. */
2996
2997 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002998 PyErr_Format(PyExc_ValueError,
2999 "invalid file open mode %.200s", mode);
3000 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003001 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003002 }
3003 if (fob == Py_None)
3004 fp = NULL;
3005 else {
3006 if (!PyFile_Check(fob)) {
3007 PyErr_SetString(PyExc_ValueError,
3008 "load_module arg#2 should be a file or None");
3009 return NULL;
3010 }
3011 fp = get_file(pathname, fob, mode);
3012 if (fp == NULL)
3013 return NULL;
3014 }
Just van Rossum52e14d62002-12-30 22:08:05 +00003015 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003016}
3017
3018static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003019imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003020{
3021 char *name;
3022 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00003023 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003024 return NULL;
3025 return load_package(name, pathname);
3026}
3027
3028static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003029imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003030{
3031 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003032 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003033 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003034 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003035}
3036
Brett Cannon3aa2a492008-08-06 22:28:09 +00003037static PyObject *
3038imp_reload(PyObject *self, PyObject *v)
3039{
3040 return PyImport_ReloadModule(v);
3041}
3042
3043
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003044/* Doc strings */
3045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003046PyDoc_STRVAR(doc_imp,
3047"This module provides the components needed to build your own\n\
3048__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003049
Brett Cannon3aa2a492008-08-06 22:28:09 +00003050PyDoc_STRVAR(doc_reload,
3051"reload(module) -> module\n\
3052\n\
3053Reload the module. The module must have been successfully imported before.");
3054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003055PyDoc_STRVAR(doc_find_module,
3056"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003057Search for a module. If path is omitted or None, search for a\n\
3058built-in, frozen or special module and continue search in sys.path.\n\
3059The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003060package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003062PyDoc_STRVAR(doc_load_module,
3063"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003064Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003065The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003067PyDoc_STRVAR(doc_get_magic,
3068"get_magic() -> string\n\
3069Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003071PyDoc_STRVAR(doc_get_suffixes,
3072"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003073Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003074that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003076PyDoc_STRVAR(doc_new_module,
3077"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003078Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003079The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003081PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003082"lock_held() -> boolean\n\
3083Return True if the import lock is currently held, else False.\n\
3084On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003085
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003086PyDoc_STRVAR(doc_acquire_lock,
3087"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003088Acquires the interpreter's import lock for the current thread.\n\
3089This lock should be used by import hooks to ensure thread-safety\n\
3090when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003091On platforms without threads, this function does nothing.");
3092
3093PyDoc_STRVAR(doc_release_lock,
3094"release_lock() -> None\n\
3095Release the interpreter's import lock.\n\
3096On platforms without threads, this function does nothing.");
3097
Guido van Rossum79f25d91997-04-29 20:08:16 +00003098static PyMethodDef imp_methods[] = {
Brett Cannon3aa2a492008-08-06 22:28:09 +00003099 {"reload", imp_reload, METH_O, doc_reload},
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003100 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3101 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3102 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3103 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3104 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3105 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3106 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3107 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003108 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003109 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3110 {"init_builtin", imp_init_builtin, METH_VARARGS},
3111 {"init_frozen", imp_init_frozen, METH_VARARGS},
3112 {"is_builtin", imp_is_builtin, METH_VARARGS},
3113 {"is_frozen", imp_is_frozen, METH_VARARGS},
3114 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003115#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003116 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003117#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003118 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003119 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003120 {NULL, NULL} /* sentinel */
3121};
3122
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003123static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003124setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003125{
3126 PyObject *v;
3127 int err;
3128
3129 v = PyInt_FromLong((long)value);
3130 err = PyDict_SetItemString(d, name, v);
3131 Py_XDECREF(v);
3132 return err;
3133}
3134
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003135typedef struct {
3136 PyObject_HEAD
3137} NullImporter;
3138
3139static int
3140NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3141{
3142 char *path;
Christian Heimescea681b2007-11-07 17:50:54 +00003143 Py_ssize_t pathlen;
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003144
3145 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3146 return -1;
3147
3148 if (!PyArg_ParseTuple(args, "s:NullImporter",
3149 &path))
3150 return -1;
3151
Christian Heimescea681b2007-11-07 17:50:54 +00003152 pathlen = strlen(path);
3153 if (pathlen == 0) {
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003154 PyErr_SetString(PyExc_ImportError, "empty pathname");
3155 return -1;
3156 } else {
3157#ifndef RISCOS
3158 struct stat statbuf;
3159 int rv;
3160
3161 rv = stat(path, &statbuf);
Christian Heimes004c1c12007-11-07 18:30:22 +00003162#ifdef MS_WINDOWS
3163 /* MS Windows stat() chokes on paths like C:\path\. Try to
3164 * recover *one* time by stripping off a trailing slash or
3165 * backslash. http://bugs.python.org/issue1293
3166 */
Christian Heimescea681b2007-11-07 17:50:54 +00003167 if (rv != 0 && pathlen <= MAXPATHLEN &&
3168 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3169 char mangled[MAXPATHLEN+1];
3170
3171 strcpy(mangled, path);
3172 mangled[pathlen-1] = '\0';
3173 rv = stat(mangled, &statbuf);
3174 }
Christian Heimescea681b2007-11-07 17:50:54 +00003175#endif
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003176 if (rv == 0) {
3177 /* it exists */
3178 if (S_ISDIR(statbuf.st_mode)) {
3179 /* it's a directory */
3180 PyErr_SetString(PyExc_ImportError,
3181 "existing directory");
3182 return -1;
3183 }
3184 }
3185#else
3186 if (object_exists(path)) {
3187 /* it exists */
3188 if (isdir(path)) {
3189 /* it's a directory */
3190 PyErr_SetString(PyExc_ImportError,
3191 "existing directory");
3192 return -1;
3193 }
3194 }
3195#endif
3196 }
3197 return 0;
3198}
3199
3200static PyObject *
3201NullImporter_find_module(NullImporter *self, PyObject *args)
3202{
3203 Py_RETURN_NONE;
3204}
3205
3206static PyMethodDef NullImporter_methods[] = {
3207 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3208 "Always return None"
3209 },
3210 {NULL} /* Sentinel */
3211};
3212
3213
Nick Coghlan327a39b2007-11-18 11:56:28 +00003214PyTypeObject PyNullImporter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003215 PyVarObject_HEAD_INIT(NULL, 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003216 "imp.NullImporter", /*tp_name*/
3217 sizeof(NullImporter), /*tp_basicsize*/
3218 0, /*tp_itemsize*/
3219 0, /*tp_dealloc*/
3220 0, /*tp_print*/
3221 0, /*tp_getattr*/
3222 0, /*tp_setattr*/
3223 0, /*tp_compare*/
3224 0, /*tp_repr*/
3225 0, /*tp_as_number*/
3226 0, /*tp_as_sequence*/
3227 0, /*tp_as_mapping*/
3228 0, /*tp_hash */
3229 0, /*tp_call*/
3230 0, /*tp_str*/
3231 0, /*tp_getattro*/
3232 0, /*tp_setattro*/
3233 0, /*tp_as_buffer*/
3234 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3235 "Null importer object", /* tp_doc */
3236 0, /* tp_traverse */
3237 0, /* tp_clear */
3238 0, /* tp_richcompare */
3239 0, /* tp_weaklistoffset */
3240 0, /* tp_iter */
3241 0, /* tp_iternext */
3242 NullImporter_methods, /* tp_methods */
3243 0, /* tp_members */
3244 0, /* tp_getset */
3245 0, /* tp_base */
3246 0, /* tp_dict */
3247 0, /* tp_descr_get */
3248 0, /* tp_descr_set */
3249 0, /* tp_dictoffset */
3250 (initproc)NullImporter_init, /* tp_init */
3251 0, /* tp_alloc */
3252 PyType_GenericNew /* tp_new */
3253};
3254
3255
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003256PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003257initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003258{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003259 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003260
Nick Coghlan327a39b2007-11-18 11:56:28 +00003261 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003262 goto failure;
3263
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003264 m = Py_InitModule4("imp", imp_methods, doc_imp,
3265 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003266 if (m == NULL)
3267 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003268 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003269 if (d == NULL)
3270 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003271
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003272 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3273 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3274 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3275 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3276 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3277 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3278 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3279 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003280 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003281 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003282
Nick Coghlan327a39b2007-11-18 11:56:28 +00003283 Py_INCREF(&PyNullImporter_Type);
3284 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003285 failure:
3286 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003287}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003288
3289
Guido van Rossumb18618d2000-05-03 23:44:39 +00003290/* API for embedding applications that want to add their own entries
3291 to the table of built-in modules. This should normally be called
3292 *before* Py_Initialize(). When the table resize fails, -1 is
3293 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003294
3295 After a similar function by Just van Rossum. */
3296
3297int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003298PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003299{
3300 static struct _inittab *our_copy = NULL;
3301 struct _inittab *p;
3302 int i, n;
3303
3304 /* Count the number of entries in both tables */
3305 for (n = 0; newtab[n].name != NULL; n++)
3306 ;
3307 if (n == 0)
3308 return 0; /* Nothing to do */
3309 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3310 ;
3311
3312 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003313 p = our_copy;
3314 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003315 if (p == NULL)
3316 return -1;
3317
3318 /* Copy the tables into the new memory */
3319 if (our_copy != PyImport_Inittab)
3320 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3321 PyImport_Inittab = our_copy = p;
3322 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3323
3324 return 0;
3325}
3326
3327/* Shorthand to add a single entry given a name and a function */
3328
3329int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003330PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003331{
3332 struct _inittab newtab[2];
3333
3334 memset(newtab, '\0', sizeof newtab);
3335
3336 newtab[0].name = name;
3337 newtab[0].initfunc = initfunc;
3338
3339 return PyImport_ExtendInittab(newtab);
3340}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003341
3342#ifdef __cplusplus
3343}
3344#endif